Delegates given request and response to be processed by given service.

@throws RequestDelegationException in case the delegated request processing fails
18253
private void delegate(RequestDelegationService service, HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) {
        try {
            service.delegate(request, response, filterChain);
        } catch (Exception e) {
            throw new RequestDelegationException(
                String.format("The request processing delegation failed: %s", e.getCause()), e);
        }
    }
556701
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        String servletPath = (String) request.getAttribute(Dispatcher.__INCLUDE_SERVLET_PATH);
        String pathInfo = null;
        if (servletPath == null)
        {
            servletPath = request.getServletPath();
            pathInfo = request.getPathInfo();
        }
        else
            pathInfo = (String) request.getAttribute(Dispatcher.__INCLUDE_PATH_INFO);

        String pathInContext = URI.addPaths(servletPath, pathInfo);
                
        boolean endsWithSlash = pathInContext.endsWith("/");
        Resource resource = getResource(pathInContext);

        // Is the method allowed?
        String method = request.getMethod();
        if (_AllowString.indexOf(method) < 0)
        {
            if (resource != null && resource.exists())
            {
                response.setHeader(HttpFields.__Allow, _AllowString);
                response.sendError(HttpResponse.__405_Method_Not_Allowed);
            }
            else
                response.sendError(HttpResponse.__404_Not_Found);
            return;
        }

        // Handle the request
        try
        {
            // handle by method.
            if (method.equals(HttpRequest.__GET) || method.equals(HttpRequest.__POST) || method.equals(HttpRequest.__HEAD))
                handleGet(request, response, pathInContext, resource, endsWithSlash);
            else if (_putAllowed && method.equals(HttpRequest.__PUT))
                handlePut(request, response, pathInContext, resource);
            else if (_delAllowed && method.equals(HttpRequest.__DELETE))
                handleDelete(request, response, pathInContext, resource);
            else if (_putAllowed && _delAllowed && method.equals(HttpRequest.__MOVE))
                handleMove(request, response, pathInContext, resource);
            else if (method.equals(HttpRequest.__OPTIONS))
                handleOptions(request, response);
            else if (method.equals(HttpRequest.__TRACE))
                _servletHandler.handleTrace(request, response);
            else
            {
                // anything else...
                try
                {
                    if (resource.exists())
                        response.sendError(HttpResponse.__501_Not_Implemented);
                    else
                        _servletHandler.notFound(request, response);
                }
                catch (Exception e)
                {
                    LogSupport.ignore(log, e);
                }
            }
        }
        catch (IllegalArgumentException e)
        {
            LogSupport.ignore(log, e);
        }
        finally
        {
            if (resource != null && !(resource instanceof CachedResource))
                resource.release();
        }

    }
1132631
def process_request(self, request_object):
        """"""

        resource = request_object.entity_cls.create(**request_object.data)
        return ResponseSuccessCreated(resource)
26500
void invoke(HttpRequest request) throws Exception {
    bodyConsumer = null;
    Object invokeResult;
    try {
      args[0] = this.request = request;
      invokeResult = method.invoke(handler, args);
    } catch (InvocationTargetException e) {
      exceptionHandler.handle(e.getTargetException(), request, responder);
      return;
    } catch (Throwable t) {
      exceptionHandler.handle(t, request, responder);
      return;
    }

    if (isStreaming) {
      // Casting guarantee to be succeeded.
      bodyConsumer = (BodyConsumer) invokeResult;
    }
  }
256800
@Override
	public void handleRequest(final Request request) {
		if (isDisabled()) {
			// Protect against client-side tampering of disabled/read-only fields.
			return;
		}

		if (isMenuPresent(request)) {
			String requestValue = request.getParameter(getId());

			if (requestValue != null) {
				// Only process on a POST
				if (!"POST".equals(request.getMethod())) {
					LOG.warn("Menu item on a request that is not a POST. Will be ignored.");
					return;
				}

				// Execute associated action, if set
				final Action action = getAction();

				if (action != null) {
					final ActionEvent event = new ActionEvent(this, this.getActionCommand(), this.
							getActionObject());

					Runnable later = new Runnable() {
						@Override
						public void run() {
							action.execute(event);
						}
					};

					invokeLater(later);
				}
			}
		}
	}
302980
protected void handleResponse(HttpRequest<?> request, MutableHttpResponse<?> response) {
        HttpHeaders headers = request.getHeaders();
        Optional<String> originHeader = headers.getOrigin();
        originHeader.ifPresent(requestOrigin -> {

            Optional<CorsOriginConfiguration> optionalConfig = getConfiguration(requestOrigin);

            if (optionalConfig.isPresent()) {
                CorsOriginConfiguration config = optionalConfig.get();

                if (CorsUtil.isPreflightRequest(request)) {
                    Optional<HttpMethod> result = headers.getFirst(ACCESS_CONTROL_REQUEST_METHOD, HttpMethod.class);
                    setAllowMethods(result.get(), response);
                    Argument<List> type = Argument.of(List.class, String.class);
                    Optional<List> allowedHeaders = headers.get(ACCESS_CONTROL_REQUEST_HEADERS, type);
                    allowedHeaders.ifPresent(val ->
                        setAllowHeaders(val, response)
                    );

                    setMaxAge(config.getMaxAge(), response);
                }

                setOrigin(requestOrigin, response);
                setVary(response);
                setExposeHeaders(config.getExposedHeaders(), response);
                setAllowCredentials(config, response);
            }
        });
    }
455441
public function process(HTTPRequest $request, callable $delegate)
    {
        /** @var HTTPResponse $response */
        $response = $delegate($request);

        // Ignore by regexes.
        if ($this->shouldCheckHttpHost() && $this->isIgnoredDomain($_SERVER['HTTP_HOST'])) {
            return $response;
        }

        foreach ($this->requestedPolicies as $requestedPolicy) {
            /** @var ControllerPolicy $policyInstance */
            $policyInstance = $requestedPolicy['policy'];

            $policyInstance->applyToResponse(
                $requestedPolicy['originator'],
                $request,
                $response
            );
        }

        return $response;
    }
853030
@Override
	public void serviceRequest(final Request request) {
		// Get the expected session token
		UIContext uic = UIContextHolder.getCurrent();
		String expected = uic.getEnvironment().getSessionToken();

		// Get the session token from the request
		String got = request.getParameter(Environment.SESSION_TOKEN_VARIABLE);

		// Check tokens match (Both null if new session)
		// or processing a GET and no token
		if (Util.equals(expected, got) || (got == null && "GET".equals(request.getMethod()))) {
			// Process request
			getBackingComponent().serviceRequest(request);
		} else {  // Invalid token
			String msg;
			if (expected == null && got != null) {
				msg = "Session for token [" + got + "] is no longer valid or timed out.";
			} else {
				msg = "Wrong session token detected for servlet request. Expected token [" + expected
						+ "] but got token [" + got + "].";
			}
			LOG.error(msg);
			String message = I18nUtilities.format(uic.getLocale(),
					InternalMessages.DEFAULT_SESSION_TOKEN_ERROR);
			throw new SystemException(message);
		}

	}
216669
public void requestCompleted (T result)
    {
        if (_chain != null) {
            _chain.requestCompleted(result);

        } else if (_invChain instanceof InvocationService.ResultListener) {
            ((InvocationService.ResultListener)_invChain).requestProcessed(result);

        } else if (_invChain instanceof InvocationService.ConfirmListener) {
            ((InvocationService.ConfirmListener)_invChain).requestProcessed();
        }
    }
1298070
protected void processLegacyRequest(HyperionContext hyperionContext)
    {
        EndpointRequest request = hyperionContext.getEndpointRequest();
        EndpointResponse response = hyperionContext.getEndpointResponse();

        ApiVersionPlugin<ApiObject<Serializable>,PersistentObject<Serializable>,Serializable> apiVersionPlugin = hyperionContext.getVersionPlugin();
        EntityPlugin plugin = hyperionContext.getEntityPlugin();

        ApiObject clientObject = null;
        try
        {
            clientObject = marshaller.unmarshall(request.getInputStream(),apiVersionPlugin.getApiClass());
        }
        catch (MarshallingException e)
        {
            throw new BadRequestException(messageSource.getErrorMessage(ERROR_READING_REQUEST,hyperionContext.getLocale(),e.getMessage()),e);
        }
        clientObject.setId(null);

        PersistenceContext persistenceContext = buildPersistenceContext(hyperionContext);
        Set<String> fieldSet = persistenceContext.getRequestedFields();
        if(fieldSet != null)
            fieldSet.add("id");

        ApiObject saved = (ApiObject) plugin.getPersistenceOperations().createOrUpdateItems(
                Collections.singletonList(clientObject),
                persistenceContext).get(0);

        processChangeEvents(hyperionContext, persistenceContext);
        response.setResponseCode(200);
        hyperionContext.setResult(saved);
    }
739809
private boolean canDelegate(RequestDelegationService delegate, HttpServletRequest request) {
        try {
            return delegate.canDelegate(request);
        } catch (Exception e) {
            log.log(Level.SEVERE,
                String.format("The delegation service can't check the delegability of the request: %s", e.getCause()),
                e.getCause());
            return false;
        }
    }
725800
public function process(HTTPRequest $request, callable $delegate)
    {
        try {
            $this
                ->getAuthenticationHandler()
                ->authenticateRequest($request);
        } catch (ValidationException $e) {
            return new HTTPResponse(
                "Bad log-in details: " . $e->getMessage(),
                400
            );
        } catch (DatabaseException $e) {
            // Database isn't ready, carry on.
        }

        return $delegate($request);
    }
1273753
public function process(ServerRequestInterface $request, DelegateInterface $delegate)
    {
        $contentType = $request->getHeaderLine('Content-Type');

        if (!$this->match($contentType)) {
            return $delegate->process($request);
        }

        $rawBody = (string)$request->getBody();
        $parsedBody = json_decode($rawBody, true);

        if (!empty($rawBody) && json_last_error() !== JSON_ERROR_NONE) {
            $statusCode = 400;
            $apiMessage = new HttpStatusCodeApiMessage($statusCode);
            $apiMessage->setCode('invalid-json');
            $apiMessage->setValue('Invalid JSON');
            $apiResponse = $this->newPsrResponseWithTranslatedMessages->__invoke(
                null,
                $statusCode,
                $apiMessage
            );

            return $apiResponse;
        }

        $request = $request
            ->withAttribute('rawBody', $rawBody)
            ->withParsedBody($parsedBody);

        return $delegate->process($request);
    }
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();
    }
  }
63096
public void processRequest(RequestEvent requestEvent) {
        // This will be invoked only by external endpoint
    	BalancerAppContent content=(BalancerAppContent)requestEvent.getSource();
    	boolean isIpv6 = content.isIpv6();
        final SipProvider sipProvider = content.getProvider();
        final Request request = requestEvent.getRequest();
        final String requestMethod = request.getMethod();

        if(logger.isDebugEnabled()) {
            logger.debug("got request:\n"+request);
        }
        
        if((requestMethod.equals(Request.OPTIONS) ||
                requestMethod.equals(Request.INFO)) &&
                request.getHeader("Mobicents-Heartbeat") != null &&
                sipProvider == balancerRunner.balancerContext.internalSipProvider) {
            byte[] bytes = (byte[]) request.getContent();
            Properties prop = new Properties();
            try {
                prop.load(new ByteArrayInputStream(bytes, 0, bytes.length));
                Node node = new Node(prop.getProperty("hostname"), prop.getProperty("ip"));
                for(String id : prop.stringPropertyNames()) {
                    node.getProperties().put(id, prop.getProperty(id));
                }
                ArrayList<Node> list = new ArrayList<Node>();
                list.add(node);
                this.register.handlePingInRegister(list);
                Response response = balancerRunner.balancerContext.messageFactory.createResponse(Response.OK, request);			
                sipProvider.sendResponse(response);	
                return;
            } catch (Exception e) {
                logger.error("Failure parsing heartbeat properties from this request " + request, e);
            }
        }
        //Issue 10: https://telestax.atlassian.net/browse/LB-10
        if (request.getContent() != null || (requestMethod.equals(Request.REGISTER) && sipProvider != balancerRunner.balancerContext.internalSipProvider)) {
            SIPMessage message = (SIPMessage)request;            

            String initialRemoteAddr = message.getPeerPacketSourceAddress().getHostAddress();
            String initialRemotePort = String.valueOf(message.getPeerPacketSourcePort());

            Header remoteAddrHeader = null;
            Header remotePortHeader = null;
            try {
                remoteAddrHeader = SipFactory.getInstance().createHeaderFactory().createHeader("X-Sip-Balancer-InitialRemoteAddr", initialRemoteAddr);
                remotePortHeader = SipFactory.getInstance().createHeaderFactory().createHeader("X-Sip-Balancer-InitialRemotePort", initialRemotePort);
            } catch (PeerUnavailableException e) {
                logger.error("Unexpected exception while creating custom headers for REGISTER message ", e);
            } catch (ParseException e) {
                logger.error("Unexpected exception while creating custom headers for REGISTER message ", e);
            }
            if (remoteAddrHeader != null)
                request.addHeader(remoteAddrHeader);
            if (remotePortHeader != null)
                request.addHeader(remotePortHeader);
        } 
        try {	
            updateStats(request);
            forwardRequest(sipProvider,request, isIpv6);          						
        } catch (Throwable throwable) {
            logger.error("Unexpected exception while forwarding the request " + request, throwable);
            if(!Request.ACK.equalsIgnoreCase(requestMethod)) {
                try {
                    Response response = balancerRunner.balancerContext.messageFactory.createResponse(Response.SERVER_INTERNAL_ERROR, request);			
                    sipProvider.sendResponse(response);	
                } catch (Exception e) {
                    logger.error("Unexpected exception while trying to send the error response for this " + request, e);
                }
            }
        }
    }
1223954
@Override
    public void render(
            Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        final IPortletWindowId portletWindowId =
                (IPortletWindowId) model.get(DELEGATE_PORTLET_WINDOW_ID);
        final DelegationRequest delegationRequest = (DelegationRequest) model.get(DELEGATE_REQUEST);

        final PortletRequest portletRequest =
                (PortletRequest) request.getAttribute(Constants.PORTLET_REQUEST);
        final PortletResponse portletResponse =
                (PortletResponse) request.getAttribute(Constants.PORTLET_RESPONSE);

        final PortletDelegationDispatcher requestDispatcher =
                portletDelegationLocator.getRequestDispatcher(portletRequest, portletWindowId);
        if (requestDispatcher == null) {
            throw new IllegalArgumentException(
                    "No PortletDelegationDispatcher exists for portlet window id: "
                            + portletWindowId);
        }
        this.logger.debug(
                "Found delegation dispatcher for portlet window id {} - {}",
                portletWindowId,
                requestDispatcher);

        final DelegationResponse delegationResponse;
        final String phase = (String) request.getAttribute(PortletRequest.LIFECYCLE_PHASE);
        if (PortletRequest.RENDER_PHASE.equals(phase)) {
            final PortletOutputHandler portletOutputHandler =
                    (PortletOutputHandler) model.get(DELEGATE_RENDER_OUTPUT_HANDLER);
            if (portletOutputHandler != null) {
                this.logger.debug(
                        "Delegating RenderRequest with custom Writer and {}", delegationRequest);
                delegationResponse =
                        requestDispatcher.doRender(
                                (RenderRequest) portletRequest,
                                (RenderResponse) portletResponse,
                                delegationRequest,
                                portletOutputHandler);
            } else {
                this.logger.debug(
                        "Delegating RenderRequest with default Writer and {}", delegationRequest);
                delegationResponse =
                        requestDispatcher.doRender(
                                (RenderRequest) portletRequest,
                                (RenderResponse) portletResponse,
                                delegationRequest);
            }
        } else if (PortletRequest.RESOURCE_PHASE.equals(phase)) {
            this.logger.debug("Delegating ResourceRequest and {}", delegationRequest);
            delegationResponse =
                    requestDispatcher.doServeResource(
                            (ResourceRequest) portletRequest,
                            (ResourceResponse) portletResponse,
                            delegationRequest);
        } else {
            throw new UnsupportedOperationException(
                    "Portlet lifecycle phase "
                            + phase
                            + " is not supported by the delegation view");
        }

        this.logger.debug("{}", delegationResponse);
    }
1259529
@Override
    public void handleRequest(HttpServletRequest request, HttpServletResponse response) {
        handleRequest(request, response, null, null, false);
    }