Handles block open request.
490357
@Override
  public void onNext(OpenLocalBlockRequest request) {
    RpcUtils.streamingRPCAndLog(LOG, new RpcUtils.StreamingRpcCallable<OpenLocalBlockResponse>() {
      @Override
      public OpenLocalBlockResponse call() throws Exception {
        Preconditions.checkState(mRequest == null);
        mRequest = request;
        if (mLockId == BlockLockManager.INVALID_LOCK_ID) {
          mSessionId = IdUtils.createSessionId();
          // TODO(calvin): Update the locking logic so this can be done better
          if (mRequest.getPromote()) {
            try {
              mWorker
                  .moveBlock(mSessionId, mRequest.getBlockId(), mStorageTierAssoc.getAlias(0));
            } catch (BlockDoesNotExistException e) {
              LOG.debug("Block {} to promote does not exist in Alluxio: {}",
                  mRequest.getBlockId(), e.getMessage());
            } catch (Exception e) {
              LOG.warn("Failed to promote block {}: {}", mRequest.getBlockId(), e.getMessage());
            }
          }
          mLockId = mWorker.lockBlock(mSessionId, mRequest.getBlockId());
          mWorker.accessBlock(mSessionId, mRequest.getBlockId());
        } else {
          LOG.warn("Lock block {} without releasing previous block lock {}.",
              mRequest.getBlockId(), mLockId);
          throw new InvalidWorkerStateException(
              ExceptionMessage.LOCK_NOT_RELEASED.getMessage(mLockId));
        }
        OpenLocalBlockResponse response = OpenLocalBlockResponse.newBuilder()
            .setPath(mWorker.readBlock(mSessionId, mRequest.getBlockId(), mLockId)).build();
        return response;
      }

      @Override
      public void exceptionCaught(Throwable e) {
        if (mLockId != BlockLockManager.INVALID_LOCK_ID) {
          try {
            mWorker.unlockBlock(mLockId);
          } catch (BlockDoesNotExistException ee) {
            LOG.error("Failed to unlock block {}.", mRequest.getBlockId(), e);
          }
          mLockId = BlockLockManager.INVALID_LOCK_ID;
        }
        mResponseObserver.onError(GrpcExceptionUtils.fromThrowable(e));
      }
    }, "OpenBlock", true, false, mResponseObserver, "Session=%d, Request=%s",
        mSessionId, mRequest);
  }
562228
def handler(self, environ, start_response):
        """"""

        if environ['REQUEST_METHOD'] == 'POST':
            return self.handle_POST(environ, start_response)
        else:
            start_response("400 Bad request", [('Content-Type', 'text/plain')])
            return ['']
79621
protected void handleTriggerOpenAction(final Request request) {
		// Run the action (if set)
		final Action action = getTriggerOpenAction();
		if (action != null) {
			final ActionEvent event = new ActionEvent(this, OPEN_DIALOG_ACTION);
			Runnable later = new Runnable() {
				@Override
				public void run() {
					action.execute(event);
				}
			};
			invokeLater(later);
		}
	}
555118
public function handleOptionsRequest()
    {
        // Generate the "Allow" header
        $allow = '';
        foreach ($this->router->getMethodsByRoute($this->uri) as $method) {
            $allow .= strtoupper($method) . ',';
        }
        $allow = substr($allow, 0, strlen($allow) - 1);
        header('Allow: ' . $allow);
        $this->setResponse('');
    }
446430
private void blockingRefresh() {
        try {
            if (blockingRefreshLock
                    .tryLock(BLOCKING_REFRESH_MAX_WAIT_IN_SECONDS, TimeUnit.SECONDS)) {
                try {
                    // Return if successful refresh occurred while waiting for the lock
                    if (!shouldDoBlockingRefresh()) {
                        return;
                    } else {
                        // Otherwise do a synchronous refresh if the last lock holder was unable to
                        // refresh the value
                        refreshValue();
                        return;
                    }
                } finally {
                    blockingRefreshLock.unlock();
                }
            }
        } catch (InterruptedException ex) {
            handleInterruptedException("Interrupted waiting to refresh the value.", ex);
        }
        // Couldn't acquire the lock. Just try a synchronous refresh
        refreshValue();
    }
806492
public function handleRequest()
    {
        // Create the request very early so the Resource Management has a chance to grab it:
        $this->request = Request::createFromEnvironment();
        $this->response = new Response();

        $this->checkBasicRequirementsAndDisplayLoadingScreen();

        $this->boot();
        $this->resolveDependencies();
        if (isset($this->settings['http']['baseUri'])) {
            $this->request->setBaseUri(new Uri($this->settings['http']['baseUri']));
        }

        $componentContext = new ComponentContext($this->request, $this->response);
        $this->baseComponentChain->handle($componentContext);

        $this->baseComponentChain->getResponse()->send();

        $this->bootstrap->shutdown('Runtime');
        $this->exit->__invoke();
    }
593196
void handleClosed() {
    if (!closed) {
      closed = true;

      for (ContextualFuture<?> responseFuture : responseFutures.values()) {
        responseFuture.context.executor().execute(() -> responseFuture.completeExceptionally(new ConnectException("connection closed")));
      }
      responseFutures.clear();

      for (Listener<Connection> listener : closeListeners) {
        listener.accept(this);
      }
      timeout.cancel();
    }
  }
444014
@Override
  public void onCompleted() {
    RpcUtils.streamingRPCAndLog(LOG, new RpcUtils.StreamingRpcCallable<OpenLocalBlockResponse>() {
      @Override
      public OpenLocalBlockResponse call() throws Exception {
        if (mLockId != BlockLockManager.INVALID_LOCK_ID) {
          mWorker.unlockBlock(mLockId);
          mLockId = BlockLockManager.INVALID_LOCK_ID;
        } else if (mRequest != null) {
          LOG.warn("Close a closed block {}.", mRequest.getBlockId());
        }
        return null;
      }

      @Override
      public void exceptionCaught(Throwable e) {
        mResponseObserver.onError(GrpcExceptionUtils.fromThrowable(e));
        mLockId = BlockLockManager.INVALID_LOCK_ID;
      }
    }, "CloseBlock", false, true, mResponseObserver, "Session=%d, Request=%s",
        mSessionId, mRequest);
  }
1187870
def call!(request)
      operation = proc {
        app.dispatch(request)
      }
      callback = proc {|result|
        send_response result
        close_connection_after_writing
      }

      #
      # if we don't want to block on slow calls, use EM#defer
      # @see http://eventmachine.rubyforge.org/EventMachine.html#M000486
      #
      if app.non_blocking?
        EventMachine.defer( operation, callback )
      else
        callback.call(operation.call)
      end
    end
186218
public function RequestHandle()
    {
        if ($this->visible == false) {
            return;
        }

        $child = next(WebApplication::getApplication()->getRequest()->request_c);

        if ($child != false && $this->components[$child] instanceof Requestable) {
            $this->components[$child]->RequestHandle();
        }
    }
25771
def _handle_request(self, request):
        """"""

        # Check if this is a persistent connection.
        if request['version'] == 'HTTP/1.1':
            self.keepalive = not request.get('Connection') == 'close'
        elif request['version'] == 'HTTP/1.0':
            self.keepalive = request.get('Connection') == 'Keep-Alive'

        # Check if we're getting a sane request
        if request['method'] not in ('GET'):
            raise InvalidRequestError(501, 'Method not implemented')
        if request['version'] not in ('HTTP/1.0', 'HTTP/1.1'):
            raise InvalidRequestError(
                505, 'Version not supported. Supported versions are: {}, {}'
                .format('HTTP/1.0', 'HTTP/1.1'))

        host, location = self._get_request_uri(request)

        # We must ignore the Host header if a host is specified in GET
        if host is None:
            host = request.get('Host')

        # Check if this request is intended for this webserver
        if host is not None and not host == self.host:
            self.logger.info('Got a request for unknown host %s', host)
            raise InvalidRequestError(404, "We don't serve this host")

        filename = os.path.join(self.folder, unquote(location))
        self.logger.debug('trying to serve %s', filename)

        if os.path.isdir(filename):
            filename = os.path.join(filename, 'index.html')

        if not os.path.isfile(filename):
            raise InvalidRequestError(404, 'Not Found')

        # Start response with version
        response = _get_response(version=request['version'])

        # timeout negotiation
        match = re.match(r'timeout=(\d+)', request.get('Keep-Alive', ''))
        if match is not None:
            requested_timeout = int(match.group(1))
            if requested_timeout < self._timeout:
                self._timeout = requested_timeout

        # tell the client our timeout
        if self.keepalive:
            response['headers'][
                'Keep-Alive'] = 'timeout={}'.format(self._timeout)

        # Set Content-Type
        response['headers']['Content-Type'] = mimetypes.guess_type(
            filename)[0] or 'text/plain'

        # Generate E-tag
        sha1 = hashlib.sha1()
        with open(filename, 'rb') as fp:
            response['body'] = fp.read()
            sha1.update(response['body'])
        etag = sha1.hexdigest()

        # Create 304 response if if-none-match matches etag
        if request.get('If-None-Match') == '"{}"'.format(etag):
            # 304 responses shouldn't contain many headers we might already
            # have added.
            response = _get_response(code=304)

        response['headers']['Etag'] = '"{}"'.format(etag)

        self._write_response(response)
338636
public synchronized String requestBlock(String name) {
        if (blocks.isEmpty()) {
            return "exit";
        }

        remainingBlocks.decrementAndGet();
        return blocks.poll().createResponse();
    }
799158
def block_before(self):
        
        # To avoid unnecessary database queries, ignore the IP check for
        # requests for static files
        if request.path.startswith(url_for('static', filename='')):
            return

        # Some static files might be served from the root path (e.g.
        # favicon.ico, robots.txt, etc.). Ignore the IP check for most
        # common extensions of those files.
        ignored_extensions = ('ico', 'png', 'txt', 'xml')
        if request.path.rsplit('.', 1)[-1] in ignored_extensions:
            return

        ips = request.headers.getlist('X-Forwarded-For')
        if not ips:
            return

        # If the X-Forwarded-For header contains multiple comma-separated
        # IP addresses, we're only interested in the last one.
        ip = ips[0].strip()
        if ip[-1] == ',':
            ip = ip[:-1]
        ip = ip.rsplit(',', 1)[-1].strip()

        if self.matches_ip(ip):
            if self.logger is not None:
                self.logger.info("IPBlock: matched {}, {}".format(ip, self.block_msg))
            if self.blocking_enabled:
                return 'IP Blocked', 200
864874
def notblocked(page):
    """"""
    for blocked in PAGES_TO_BLOCK:
        if blocked[0] != '*':
            blocked = '*' + blocked
        rx = re.compile(blocked.replace('*', '[^$]*'))
        if rx.match(page):
            return False
    return True
1025528
function(xhr, o) {
		var opts = o || {};
		
		if (xhr) {
			opts.quiet && (xhr.quiet = true);
			if (opts.abort && xhr._requestId) {
				this.request({
					data: {
						cmd: 'abort',
						id: xhr._requestId
					},
					preventDefault: true
				});
			}
			xhr.abort();
			xhr = void 0;
		}
	}
1010172
def handleCheckIDRequest(request, openid_request):
    
    # If the request was an IDP-driven identifier selection request
    # (i.e., the IDP URL was entered at the RP), then return the
    # default identity URL for this server. In a full-featured
    # provider, there could be interaction with the user to determine
    # what URL should be sent.
    if not openid_request.idSelect():

        id_url = getViewURL(request, idPage)

        # Confirm that this server can actually vouch for that
        # identifier
        if id_url != openid_request.identity:
            # Return an error response
            error_response = ProtocolError(
                openid_request.message,
                "This server cannot verify the URL %r" %
                (openid_request.identity,))

            return displayResponse(request, error_response)

    if openid_request.immediate:
        # Always respond with 'cancel' to immediate mode requests
        # because we don't track information about a logged-in user.
        # If we did, then the answer would depend on whether that user
        # had trusted the request's trust root and whether the user is
        # even logged in.
        openid_response = openid_request.answer(False)
        return displayResponse(request, openid_response)
    else:
        # Store the incoming request object in the session so we can
        # get to it later.
        setRequest(request, openid_request)
        return showDecidePage(request, openid_request)
769541
void loadBlock(BlockId blockId, ByteBuffer block) throws IOException {
        synchronized (m_accessLock) {
            if (! m_blockPathMap.containsKey(blockId)) {
                throw new IllegalArgumentException("Request to load block that is not stored: " + blockId);
            }

            int origPosition = block.position();
            block.position(0);
            Path blockPath = m_blockPathMap.get(blockId);
            try (SeekableByteChannel channel = Files.newByteChannel(blockPath)) {
                channel.read(block);
            }
            finally {
                block.position(origPosition);
            }
        }
    }