Handles HTTP request collection

@todo This method needs refactoring along with HttpRequest class. In current shape it cannot accept requests
with additional data attached (eg. POST or PUT).
@throws HttpException
421154
protected function processInputBuffer()
    {
        //$this->logger->debug('Trying to process buffer of HttpClient');

        if ($this->request === null) { //New request
            if (isset($this->inputBuffer[HttpRequest::MAX_HEADER_LENGTH])) { //Much faster than strlen ;)
                $this->logger->warning("Client $this sent headers larger than " . HttpRequest::MAX_HEADER_LENGTH . ' bytes');
                $this->inputBuffer = '';
                throw new HttpException('Server refused request exceeding ' . HttpRequest::MAX_HEADER_LENGTH . ' bytes',
                    HttpCode::REQUEST_HEADER_FIELDS_TOO_LARGE, array(), true);
            }

            $headersBreakpoint = strpos($this->inputBuffer, "\r\n\r\n"); //Try to find headers breakpoint
            if ($headersBreakpoint === false) { //Not found, nothing to do
                //$this->logger->debug('Buffer doesn't contain full HTTP headers [yet]');
                return;
            }

            //TODO: Refactor to 2x substr (based on $headersBreakpoint) - it's ~5% faster [but it need to be changed along with payloads support]
            list($headers, $this->inputBuffer) = explode("\r\n\r\n", $this->inputBuffer, 2);
            //$this->logger->debug('Got HTTP headers, creating HttpRequest...');
            $this->request = new HttpRequest($headers, $this->logger);
        }
        //In future: else { add data to already created request }
    }
188882
public void handle(String pathInContext, String pathParams, HttpRequest request,
            HttpResponse response) throws HttpException, IOException
    {

        // exempt error pages
        // TODO This probably should be more general?
        if (request.getAttribute("javax.servlet.error.status_code") != null) return;

        try
        {

            String ip = request.getRemoteAddr();
            boolean authorized = checkIP(ip);

            if (!authorized)
            {
                // The IP is NOT allowed
                response.sendError(HttpResponse.__403_Forbidden);
                request.setHandled(true);
                return;
            }
            else
            {
                // The IP is allowed
                return;
            }
        }
        catch (Exception ex)
        {
            System.out.println(ex);
            response.sendError(HttpResponse.__500_Internal_Server_Error);
            request.setHandled(true);
        }
    }
985927
private function throwExceptionOnHttpErrors(Response $response)
    {
        $httpCode = $response->getHttpCode();

        if ($httpCode >= 400)
        {
            // Get the description of the http error code
            $httpMessage = $response->getHttpMessage($httpCode);

            throw new HttpException($response, $httpMessage, $httpCode);
        }
    }
644081
protected function handleException()
    {
        $this->handleNotJsonException($this->getResponse());

        if (false === $this->getInstapushClient()->isHandleException()) {
            return $this
                ->getInstapushClient()
                ->getTransformer()
                ->transform($this->getResponse(), ApiError::class);
        }

        $content = \json_decode($this->getResponse()->getBody()->__toString(), true);

        $message = true === isset($content['msg']) ? $content['msg'] : 'An unexpected error occurred : '.$content;

        throw new ApiException($message, $this->getRequest(), $this->getResponse());
    }
405981
public function handleRequest()
    {
        // Create the request very early so the ResourceManagement has a chance to grab it:
        $request = Request::createFromEnvironment();
        $response = new Response();
        $this->componentContext = new ComponentContext($request, $response);

        $this->boot();
        $this->resolveDependencies();
        $response = $this->addPoweredByHeader($response);
        $this->componentContext->replaceHttpResponse($response);
        $baseUriSetting = $this->bootstrap->getObjectManager()->get(ConfigurationManager::class)->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, 'Neos.Flow.http.baseUri');
        if (!empty($baseUriSetting)) {
            $baseUri = new Uri($baseUriSetting);
            $request = $request->withAttribute(Request::ATTRIBUTE_BASE_URI, $baseUri);
            $this->componentContext->replaceHttpRequest($request);
        }

        $this->baseComponentChain->handle($this->componentContext);
        $response = $this->baseComponentChain->getResponse();

        $response->send();

        $this->bootstrap->shutdown(Bootstrap::RUNLEVEL_RUNTIME);
        $this->exit->__invoke();
    }
179907
private void handleWebException(WebApplicationException  exception)  {

       Response response = exception.getResponse();
       if (response == null) {
           throw new AuxiliaryStorageException("Mapping exception error: response is null");
       }

       int responseStatus = response.getStatus();

       if (Status.BAD_REQUEST.getStatusCode() == responseStatus) {
           throw new IllegalParameterException("Bad request server error");
       } else if (Status.NOT_FOUND.getStatusCode() == responseStatus) {
           throw new ObjectNotFoundException("Object not found in auxiliary storage");
       } else if (Status.CONFLICT.getStatusCode() == responseStatus) {
           throw new ObjectAlreadyExistsException("Object already exists in auxiliary storage");
       } else if (Status.INTERNAL_SERVER_ERROR.getStatusCode() == responseStatus) {
           throw new AuxiliaryStorageException("Internal server error");
       } else {
           throw new AuxiliaryStorageException("Unknown server error");
       }
   }
782699
public void handle(String pathInContext,
                       String pathParams,
                       HttpRequest request,
                       HttpResponse response)
        throws HttpException, IOException
    {
        getHttpContext().checkSecurityConstraints(pathInContext,request,response);
    }
166495
private function handleRequestException(HttpClientException $e)
    {
        if ($response = $e->getResponse()) {
            $exception = new Exception($response->getReasonPhrase(), $response->getStatusCode(), $e);
            $exception->setBody(json_decode($response->getBody()));

            throw $exception;
        }

        throw new Exception($e->getMessage(), 500, $e);
    }
1012639
public function handleRequest()
    {
        try {
            $server = $this->environment->getRequestHelper()->getServerParams();
            $serviceName = preg_replace('/^(.*?)(\?.*)?$/', '$1', $this->getURI($server));
            $className = $this->findServiceClassName($this->services, $serviceName);
            $method = $this->getMethod($server);
            $this->handleAllowedOrigins();

            if ($method != 'options') {
                $this->callService($className, $serviceName, $method);
            }
        } catch (InvalidParameterException $e) {
            $msg = $e->getMessage() ?: "Missing parameter";
            $this->environment->sendResult('400 Bad Request', 'text/plain; charset=utf-8', $msg);
        } catch (DenyException $e) {
            $this->environment->sendResult('403 Forbidden', "text/plain; charset=utf-8", $e->getMessage());
        } catch (\Exception $e) {
            $this->environment->sendResult('500 Server error', "text/plain; charset=utf-8", $e->getMessage());
        }
    }
514326
private void processRequestHeaderOverrides(HttpMethod httpMethodProxyRequest) throws Exception {
        RequestInformation requestInfo = requestInformation.get();
        for (EndpointOverride selectedPath : requestInfo.selectedRequestPaths) {
            List<EnabledEndpoint> points = selectedPath.getEnabledEndpoints();
            for (EnabledEndpoint endpoint : points) {
                if (endpoint.getOverrideId() == Constants.PLUGIN_REQUEST_HEADER_OVERRIDE_ADD) {
                    httpMethodProxyRequest.addRequestHeader(endpoint.getArguments()[0].toString(),
                                                            endpoint.getArguments()[1].toString());
                    requestInfo.modified = true;
                } else if (endpoint.getOverrideId() == Constants.PLUGIN_REQUEST_HEADER_OVERRIDE_REMOVE) {
                    httpMethodProxyRequest.removeRequestHeader(endpoint.getArguments()[0].toString());
                    requestInfo.modified = true;
                }
            }
        }
    }
983279
public function collect(Request $request, Response $response, \Exception $exception = null)
    {

        $this->data = $this->client->getCalls();
        $this->data = array_merge($this->data, $this->transactionalClient->getCalls());
    }
574112
protected function handleRequestException(Request $request, RequestException $previousException)
    {
        if (null !== $previousException) {
            $response = $previousException->getResponse();

            if (null == $response || ($response->getStatusCode() >= 500 && $response->getStatusCode() <= 599)) {
                throw new NullResponseException($this->request, $previousException);
            }
        }

        throw $this->createApiException(
            $request,
            $this->createResponse($previousException->getResponse()),
            $previousException
        );
    }
229371
public function handleRequest()
    {
        try {
            $rtn = parent::handleRequest();

            if (extension_loaded('newrelic')) {
                $site = $this->toPhpName($this->config->get('site.name'));
                $controller = $this->toPhpName($this->route['controller']);
                $action = $this->toPhpName($this->route['action']);

                newrelic_name_transaction($site . '.' . $controller . '.' . $action);
            }
        } catch (HttpException\NotFoundException $ex) {
            $rtn = $this->handleHttpError($ex->getErrorCode());
        } catch (HttpException $ex) {
            if ((defined('CMS_ENV') && CMS_ENV == 'development') || array_key_exists('ex', $_GET)) {
                throw $ex;
            }

            $rtn = $this->handleHttpError($ex->getErrorCode());
        } catch (Exception $ex) {
            if ((defined('CMS_ENV') && CMS_ENV == 'development') || array_key_exists('ex', $_GET)) {
                throw $ex;
            }

            $rtn = $this->handleHttpError(500);
        }

        return $rtn;
    }
1164159
public void handle(
        String pathInContext,
        String pathParams,
        HttpRequest request,
        HttpResponse response)
        throws HttpException, IOException
    {
        response.setContentType(HttpFields.__TextHtml);
        ByteArrayISO8859Writer writer= new ByteArrayISO8859Writer(2048);
        writeErrorPage(request, writer, response.getStatus(), response.getReason());
        writer.flush();
        response.setContentLength(writer.size());
        writer.writeTo(response.getOutputStream());
        writer.destroy();
    }
1085104
def handle(self, request: HttpRequest) -> HttpResponse:
        
        self.__request_start = datetime.now()
        self.__request = request
        self.__uri = request.path[1:]
        self.__method = request.method

        # Initializes the callable controller and call it's connect method to get the mapped end-points.
        controller: RouteMapping = self.__controller().connect(self.app)

        self.__end_points = controller.get_routes()

        indent = self.get_json_ident(request.META)

        if self.set_end_point_uri() is False:
            return self.set_response_headers(self.no_route_found(self.__request).render(indent))

        response = HttpResponse(None)
        try:
            response = self.exec_route_callback()
        except RinzlerHttpException as e:
            client.captureException()
            self.app.log.error(f"< {e.status_code}", exc_info=True)
            response = Response(None, status=e.status_code)
        except RequestDataTooBig:
            client.captureException()
            self.app.log.error("< 413", exc_info=True)
            response = Response(None, status=413)
        except BaseException:
            client.captureException()
            self.app.log.error("< 500", exc_info=True)
            response = Response(None, status=500)
        finally:
            if type(response) == Response:
                return self.set_response_headers(response.render(indent))
            else:
                return self.set_response_headers(response)
902153
protected function postRequest()
    {
        $response = $this->client->post($this->buildUrl(),
            [
                'auth'    => $this->getAuth(),
                'json'    => $this->getBody(),
                'headers' => [
                    'Accept' => 'application/json',
                ],
            ]);

        if ($response->getStatusCode() != 201 && $response->getStatusCode() != 200) {
            throw new \Exception('Unable to request from API. HTTP Error: '.$response->getStatusCode());
        }

        return $response;
    }
1167733
public void handle(Request request, Response response) throws Exception {
		if (Environment.isDevelopment()) {
			this.middlewares = this.middlewareFactory.create();
		}
		
		try {
			handle(request, response, new ArrayList<Middleware>(Arrays.asList(middlewares)));
		} catch (Exception e) {
			if (exceptionHandler != null) {
				exceptionHandler.handle(e, request, response);
			} else {
				throw e;
			}
		}
	}