Invoked when {@code req} is throttled. By default, this method responds with the
{@link HttpStatus#SERVICE_UNAVAILABLE} status.
507293
@Override
    protected HttpResponse onFailure(ServiceRequestContext ctx, HttpRequest req, @Nullable Throwable cause)
            throws Exception {
        return HttpResponse.of(HttpStatus.SERVICE_UNAVAILABLE);
    }
1069592
private void handleResponseFailure(long requestId, Throwable t) {
    ContextualFuture future = responseFutures.remove(requestId);
    if (future != null) {
      future.context.executor().execute(() -> future.completeExceptionally(t));
    }
  }
493283
@Override
  public boolean service(RequestBaratine request)
  {
    request.status(HttpStatus.NOT_FOUND);
    
    request.write("Not found: " + request.uri() + "\n");
    request.ok();
    
    return true;
  }
589128
function (i)
    {
        var self = this;
        var req = this._requests[i];
        var reqStatus = -1;

        try {
            if (req.xhr.readyState == 4) {
                reqStatus = req.xhr.status;
            }
        } catch (e) {
            Strophe.error("caught an error in _requests[" + i +
                          "], reqStatus: " + reqStatus);
        }

        if (typeof(reqStatus) == "undefined") {
            reqStatus = -1;
        }

        // make sure we limit the number of retries
        if (req.sends > this._conn.maxRetries) {
            this._conn._onDisconnectTimeout();
            return;
        }

        var time_elapsed = req.age();
        var primaryTimeout = (!isNaN(time_elapsed) &&
                              time_elapsed > Math.floor(Strophe.TIMEOUT * this.wait));
        var secondaryTimeout = (req.dead !== null &&
                                req.timeDead() > Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait));
        var requestCompletedWithServerError = (req.xhr.readyState == 4 &&
                                               (reqStatus < 1 ||
                                                reqStatus >= 500));
        if (primaryTimeout || secondaryTimeout ||
            requestCompletedWithServerError) {
            if (secondaryTimeout) {
                Strophe.error("Request " +
                              this._requests[i].id +
                              " timed out (secondary), restarting");
            }
            req.abort = true;
            req.xhr.abort();
            // setting to null fails on IE6, so set to empty function
            req.xhr.onreadystatechange = function () {};
            this._requests[i] = new Strophe.Request(req.xmlData,
                                                    req.origFunc,
                                                    req.rid,
                                                    req.sends);
            req = this._requests[i];
        }

        if (req.xhr.readyState === 0) {
            Strophe.debug("request id " + req.id +
                          "." + req.sends + " posting");

            try {
                req.xhr.open("POST", this._conn.service, this._conn.options.sync ? false : true);
                req.xhr.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
            } catch (e2) {
                Strophe.error("XHR open failed.");
                if (!this._conn.connected) {
                    this._conn._changeConnectStatus(Strophe.Status.CONNFAIL,
                                              "bad-service");
                }
                this._conn.disconnect();
                return;
            }

            // Fires the XHR request -- may be invoked immediately
            // or on a gradually expanding retry window for reconnects
            var sendFunc = function () {
                req.date = new Date();
                if (self._conn.options.customHeaders){
                    var headers = self._conn.options.customHeaders;
                    for (var header in headers) {
                        if (headers.hasOwnProperty(header)) {
                            req.xhr.setRequestHeader(header, headers[header]);
                        }
                    }
                }
                req.xhr.send(req.data);
            };

            // Implement progressive backoff for reconnects --
            // First retry (send == 1) should also be instantaneous
            if (req.sends > 1) {
                // Using a cube of the retry number creates a nicely
                // expanding retry window
                var backoff = Math.min(Math.floor(Strophe.TIMEOUT * this.wait),
                                       Math.pow(req.sends, 3)) * 1000;
                setTimeout(sendFunc, backoff);
            } else {
                sendFunc();
            }

            req.sends++;

            if (this._conn.xmlOutput !== Strophe.Connection.prototype.xmlOutput) {
                if (req.xmlData.nodeName === this.strip && req.xmlData.childNodes.length) {
                    this._conn.xmlOutput(req.xmlData.childNodes[0]);
                } else {
                    this._conn.xmlOutput(req.xmlData);
                }
            }
            if (this._conn.rawOutput !== Strophe.Connection.prototype.rawOutput) {
                this._conn.rawOutput(req.data);
            }
        } else {
            Strophe.debug("_processRequest: " +
                          (i === 0 ? "first" : "second") +
                          " request has readyState of " +
                          req.xhr.readyState);
        }
    }
796851
public WaitHttpConditionBuilder status(HttpStatus status) {
        getCondition().setHttpResponseCode(String.valueOf(status.value()));
        return this;
    }
410213
public void service(ServletRequest req, ServletResponse res) throws ServletException,
            IOException
    {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)res;
        if ("CONNECT".equalsIgnoreCase(request.getMethod()))
        {
            handleConnect(request,response);
        }
        else
        {
            String uri=request.getRequestURI();
            if (request.getQueryString()!=null)
                uri+="?"+request.getQueryString();
            URL url = new URL(request.getScheme(),
                    		  request.getServerName(),
                    		  request.getServerPort(),
                    		  uri);
            
            context.log("URL="+url);

            URLConnection connection = url.openConnection();
            connection.setAllowUserInteraction(false);
            
            // Set method
            HttpURLConnection http = null;
            if (connection instanceof HttpURLConnection)
            {
                http = (HttpURLConnection)connection;
                http.setRequestMethod(request.getMethod());
                http.setInstanceFollowRedirects(false);
            }

            // check connection header
            String connectionHdr = request.getHeader("Connection");
            if (connectionHdr!=null)
            {
                connectionHdr=connectionHdr.toLowerCase();
                if (connectionHdr.equals("keep-alive")||
                    connectionHdr.equals("close"))
                    connectionHdr=null;
            }
            
            // copy headers
            boolean xForwardedFor=false;
            boolean hasContent=false;
            Enumeration enm = request.getHeaderNames();
            while (enm.hasMoreElements())
            {
                // TODO could be better than this!
                String hdr=(String)enm.nextElement();
                String lhdr=hdr.toLowerCase();

                if (_DontProxyHeaders.contains(lhdr))
                    continue;
                if (connectionHdr!=null && connectionHdr.indexOf(lhdr)>=0)
                    continue;

                if ("content-type".equals(lhdr))
                    hasContent=true;

                Enumeration vals = request.getHeaders(hdr);
                while (vals.hasMoreElements())
                {
                    String val = (String)vals.nextElement();
                    if (val!=null)
                    {
                        connection.addRequestProperty(hdr,val);
                        context.log("req "+hdr+": "+val);
                        xForwardedFor|="X-Forwarded-For".equalsIgnoreCase(hdr);
                    }
                }
            }

            // Proxy headers
            connection.setRequestProperty("Via","1.1 (jetty)");
            if (!xForwardedFor)
                connection.addRequestProperty("X-Forwarded-For",
                                              request.getRemoteAddr());

            // a little bit of cache control
            String cache_control = request.getHeader("Cache-Control");
            if (cache_control!=null &&
                (cache_control.indexOf("no-cache")>=0 ||
                 cache_control.indexOf("no-store")>=0))
                connection.setUseCaches(false);

            // customize Connection
            
            try
            {    
                connection.setDoInput(true);
                
                // do input thang!
                InputStream in=request.getInputStream();
                if (hasContent)
                {
                    connection.setDoOutput(true);
                    IO.copy(in,connection.getOutputStream());
                }
                
                // Connect
                connection.connect();    
            }
            catch (Exception e)
            {
                context.log("proxy",e);
            }
            
            InputStream proxy_in = null;

            // handler status codes etc.
            int code=500;
            if (http!=null)
            {
                proxy_in = http.getErrorStream();
                
                code=http.getResponseCode();
                response.setStatus(code,http.getResponseMessage());
                context.log("response = "+http.getResponseCode());
            }
            
            if (proxy_in==null)
            {
                try {proxy_in=connection.getInputStream();}
                catch (Exception e)
                {
                    context.log("stream",e);
                    proxy_in = http.getErrorStream();
                }
            }
            
            // clear response defaults.
            response.setHeader("Date",null);
            response.setHeader("Server",null);
            
            // set response headers
            int h=0;
            String hdr=connection.getHeaderFieldKey(h);
            String val=connection.getHeaderField(h);
            while(hdr!=null || val!=null)
            {
                String lhdr = hdr!=null?hdr.toLowerCase():null;
                if (hdr!=null && val!=null && !_DontProxyHeaders.contains(lhdr))
                    response.addHeader(hdr,val);

                context.log("res "+hdr+": "+val);
                
                h++;
                hdr=connection.getHeaderFieldKey(h);
                val=connection.getHeaderField(h);
            }
            response.addHeader("Via","1.1 (jetty)");

            // Handle
            if (proxy_in!=null)
                IO.copy(proxy_in,response.getOutputStream());
            
        }
    }
651398
private void handleRequest(long requestId, Object request, HandlerHolder handler) {
    @SuppressWarnings("unchecked")
    CompletableFuture<Object> responseFuture = handler.handler.apply(request);
    if (responseFuture != null) {
      responseFuture.whenComplete((response, error) -> {
        ThreadContext context = ThreadContext.currentContext();
        if (context == null) {
          this.context.executor().execute(() -> {
            if (error == null) {
              handleRequestSuccess(requestId, response, this.context);
            } else {
              handleRequestFailure(requestId, error, this.context);
            }
          });
        } else {
          if (error == null) {
            handleRequestSuccess(requestId, response, context);
          } else {
            handleRequestFailure(requestId, error, context);
          }
        }
      });
    }
  }
207199
private void checkResumableDownloadEnabled(int downloadId) {
		synchronized (mCurrentRequests) {
			for (DownloadRequest request : mCurrentRequests) {
				if (downloadId == -1 && !request.isResumable()) {
					Log.e("ThinDownloadManager",
							String.format(Locale.getDefault(), "This request has not enabled resume feature hence request will be cancelled. Request Id: %d", request.getDownloadId()));
				} else if ((request.getDownloadId() == downloadId && !request.isResumable())) {
					throw new IllegalStateException("You cannot pause the download, unless you have enabled Resume feature in DownloadRequest.");
				} else {
					//ignored, It can not be a scenario to happen.
				}
			}
		}
	}
1290522
def is_throttled(e):
    
    return True if (hasattr(e, 'response') and
                    e.response is not None and
                    'Error' in e.response and
                    e.response['Error']['Code'] in ['Throttling', 'RequestLimitExceeded', 'ThrottlingException']) else \
        False
780945
synchronized public void check() {
		if(lastCheckpoint < 0) {
			lastCheckpoint = System.currentTimeMillis();
		}
		
		requests++;
		long interval = System.currentTimeMillis() - lastCheckpoint;
		if(requests >= maxRequests) {
			try {
				long sleepTime = minInterval - interval;
				if(sleepTime > 0) {
					logger.info("Request limit reached. Wait for " + sleepTime/1000 + " seconds");
					Thread.sleep(sleepTime);
				}
			} catch (InterruptedException e) {
				logger.error(e.getMessage());
				return;
			}
			finally {
				requests = 0;
				lastCheckpoint = System.currentTimeMillis();
			}
		}
		else if(interval > minInterval) {
			requests = 0;
			lastCheckpoint = System.currentTimeMillis();
		}
	}
689914
def throttle(self, key, amount=1, rate=None, capacity=None,
            exc_class=Throttled, **kwargs):
        """"""

        if not self.consume(key, amount, rate, capacity, **kwargs):
            raise exc_class("Request of %d unit for %s exceeds capacity."
                    % (amount, key))
255211
private void handleChangeManagerStatusRequest(final HttpServletRequest req,
      final Map<String, Object> ret, final boolean enableMetricManager) {
    try {
      logger.info("Updating metric manager status");
      if ((enableMetricManager && MetricReportManager.isInstantiated())
          || MetricReportManager.isAvailable()) {
        final MetricReportManager metricManager = MetricReportManager.getInstance();
        if (enableMetricManager) {
          metricManager.enableManager();
        } else {
          metricManager.disableManager();
        }
        ret.put(STATUS_PARAM, RESPONSE_SUCCESS);
      } else {
        ret.put(RESPONSE_ERROR, "MetricManager is not available");
      }
    } catch (final Exception e) {
      logger.error(e);
      ret.put(RESPONSE_ERROR, e.getMessage());
    }
  }
638544
public static boolean activate(ServletRequest req) throws IOException {
        CompressionServletResponse rsp = (CompressionServletResponse) req.getAttribute(CompressionServletResponse.class.getName());
        if (rsp!=null) {
            rsp.activate();
            return true;
        } else {
            return false;
        }
    }
70730
@GET
  @Path("/loadStatus")
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.APPLICATION_JSON)
  @ResourceFilters(BasicSecurityResourceFilter.class)
  public Response getLoadStatus(
      @Context HttpServletRequest req
  )
  {
    return handler.getLoadStatus();
  }
948317
function (_callback)
    {
        if (_callback) {
            _callback = _callback.bind(this._conn);
        } else {
            _callback = this._conn._connect_cb.bind(this._conn);
        }
        var body = this._buildBody();
        this._requests.push(
                new Strophe.Request(body.tree(),
                    this._onRequestStateChange.bind(
                        this, _callback.bind(this._conn)),
                    body.tree().getAttribute("rid")));
        this._throttledRequestHandler();
    }
1259851
protected void statsRequestEnd()
    {
        if (_statsOn && _reqTime>0)
        {
            _httpServer.statsEndRequest(System.currentTimeMillis()-_reqTime,
                                        (_response!=null));
            _reqTime=0;
        }
    }
775900
public <T> boolean waitForResource(int res, int timeout) {
        int RETRY_PERIOD = 250;
        int retryNum = timeout / RETRY_PERIOD;
        for (int i = 0; i < retryNum; i++) {
            T View = (T) this.getView(res);
            if (View != null) {
                break;
            }
            if (i == retryNum - 1) {
                return false;
            }
            this.sleep(RETRY_PERIOD);
        }
        return true;
    }