Return request signed data.

@param AbstractRequestHandler $requestHandler
@param string $endpoint
@param string $httpMethod
@param Payload|NULL $payload

@return array

@throws RequestException
356947
public static function signRequest(
        AbstractRequestHandler $requestHandler,
        $endpoint,
        $httpMethod,
        Payload $payload = null
    ) {
        $endPointPath = self::generateEndPointPath($endpoint, $requestHandler->getSDKId());

        $messageToSign = "{$httpMethod}&$endPointPath";
        if ($payload instanceof Payload) {
            $messageToSign .= "&{$payload->getBase64Payload()}";
        }

        openssl_sign($messageToSign, $signedMessage, $requestHandler->getPem(), OPENSSL_ALGO_SHA256);

        self::validateSignedMessage($signedMessage);

        $base64SignedMessage = base64_encode($signedMessage);

        return [
            self::SIGNED_MESSAGE_KEY => $base64SignedMessage,
            self::END_POINT_PATH_KEY => $endPointPath
        ];
    }
1000044
@Singleton
    HttpServerHandler<HttpRequest<?>, HttpResponse<?>> httpServerHandler(HttpTracing httpTracing) {
        return HttpServerHandler.create(httpTracing, new HttpServerAdapter<HttpRequest<?>, HttpResponse<?>>() {
            @Override
            public String method(HttpRequest<?> request) {
                return request.getMethod().name();
            }

            @Override
            public String url(HttpRequest<?> request) {
                return request.getUri().toString();
            }

            @Override
            public String requestHeader(HttpRequest<?> request, String name) {
                return request.getHeaders().get(name);
            }

            @Override
            public Integer statusCode(HttpResponse<?> response) {
                return response.getStatus().getCode();
            }

            @Override
            public String route(HttpResponse<?> response) {
                Optional<String> value = response.getAttribute(HttpAttributes.URI_TEMPLATE, String.class);
                return value.orElseGet(() -> super.route(response));
            }

            @Override
            public String methodFromResponse(HttpResponse<?> httpResponse) {
                return httpResponse.getAttribute(HttpAttributes.METHOD_NAME, String.class).orElse(null);
            }

            @Override
            public boolean parseClientAddress(HttpRequest<?> httpRequest, Endpoint.Builder builder) {
                InetSocketAddress remoteAddress = httpRequest.getRemoteAddress();
                return builder.parseIp(remoteAddress.getAddress());
            }
        });
    }
1337562
protected function get($endpoint, $params = [], $accessToken = null)
    {
        return $this->sendRequest(self::GET_METHOD, $endpoint, $params, $accessToken);
    }
198706
public function dispatch($httpMethod, $uri)
    {
        list($handler, $filters, $vars) = $this->dispatchRoute($httpMethod, trim($uri, '/'));

        list($beforeFilter, $afterFilter) = $this->parseFilters($filters);

        if (($response = $this->dispatchFilters($beforeFilter)) !== null) {
            return $response;
        }

        $resolvedHandler = $this->handlerResolver->resolve($handler);
        $vars['request'] = $this->getRequest();
        $reflection = new ReflectionMethod($resolvedHandler[0], $resolvedHandler[1]);
        $reflectionVariables = $this->getReflectionVars($reflection, $vars);
        $this->authorizeRequest();
        $this->validateRequest($reflectionVariables);
        $response = call_user_func_array(
            $resolvedHandler,
            $reflectionVariables
        );

        return $this->dispatchFilters($afterFilter, $response);
    }
1060949
private ResponseEntity<?> handleRequestInternal(HttpMethod method, HttpEntity<?> requestEntity) {
        HttpMessage request = endpointConfiguration.getMessageConverter().convertInbound(requestEntity, endpointConfiguration, null);

        HttpServletRequest servletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        UrlPathHelper pathHelper = new UrlPathHelper();

        Enumeration allHeaders = servletRequest.getHeaderNames();
        for (String headerName : CollectionUtils.toArray(allHeaders, new String[] {})) {
            if (request.getHeader(headerName) == null) {
                String headerValue = servletRequest.getHeader(headerName);
                request.header(headerName, headerValue != null ? headerValue : "");
            }
        }

        if (endpointConfiguration.isHandleCookies()) {
            request.setCookies(servletRequest.getCookies());
        }

        if (endpointConfiguration.isHandleAttributeHeaders()) {
            Enumeration<String> attributeNames = servletRequest.getAttributeNames();
            while (attributeNames.hasMoreElements()) {
                String attributeName = attributeNames.nextElement();
                Object attribute = servletRequest.getAttribute(attributeName);
                request.setHeader(attributeName, attribute);
            }
        }

        request.path(pathHelper.getRequestUri(servletRequest))
                .uri(pathHelper.getRequestUri(servletRequest))
                .contextPath(pathHelper.getContextPath(servletRequest))
                .queryParams(Optional.ofNullable(pathHelper.getOriginatingQueryString(servletRequest))
                                    .map(queryString -> queryString.replaceAll("&", ","))
                                    .orElse(""))
                .version(servletRequest.getProtocol())
                .method(method);

        Message response = endpointAdapter.handleMessage(request);

        ResponseEntity<?> responseEntity;
        if (response == null) {
            responseEntity = new ResponseEntity<>(HttpStatus.valueOf(endpointConfiguration.getDefaultStatusCode()));
        } else {
            HttpMessage httpResponse;
            if (response instanceof HttpMessage) {
                httpResponse = (HttpMessage) response;
            } else {
                httpResponse = new HttpMessage(response);
            }

            if (httpResponse.getStatusCode() == null) {
                httpResponse.status(HttpStatus.valueOf(endpointConfiguration.getDefaultStatusCode()));
            }

            responseEntity = (ResponseEntity<?>) endpointConfiguration.getMessageConverter().convertOutbound(httpResponse, endpointConfiguration, null);

            if (endpointConfiguration.isHandleCookies() && httpResponse.getCookies() != null) {
                HttpServletResponse servletResponse = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
                for (Cookie cookie : httpResponse.getCookies()) {
                    servletResponse.addCookie(cookie);
                }
            }
        }
        responseCache.add(responseEntity);
        
        return responseEntity;
    }
804002
async def from_payload(cls, payload, endpoint, idgen, debug, force_protocol=None):
        """"""
        service_name = payload["service"]

        if "protocols" not in payload:
            raise SongpalException(
                "Unable to find protocols from payload: %s" % payload
            )

        protocols = payload["protocols"]
        _LOGGER.debug("Available protocols for %s: %s", service_name, protocols)
        if force_protocol and force_protocol.value in protocols:
            protocol = force_protocol
        elif "websocket:jsonizer" in protocols:
            protocol = ProtocolType.WebSocket
        elif "xhrpost:jsonizer" in protocols:
            protocol = ProtocolType.XHRPost
        else:
            raise SongpalException(
                "No known protocols for %s, got: %s" % (service_name, protocols)
            )
        _LOGGER.debug("Using protocol: %s" % protocol)

        service_endpoint = "%s/%s" % (endpoint, service_name)

        # creation here we want to pass the created service class to methods.
        service = cls(service_name, service_endpoint, protocol, idgen, debug)

        sigs = await cls.fetch_signatures(
            service_endpoint, protocol, idgen
        )

        if debug > 1:
            _LOGGER.debug("Signatures: %s", sigs)
        if "error" in sigs:
            _LOGGER.error("Got error when fetching sigs: %s", sigs["error"])
            return None

        methods = {}

        for sig in sigs["results"]:
            name = sig[0]
            parsed_sig = MethodSignature.from_payload(*sig)
            if name in methods:
                _LOGGER.debug("Got duplicate signature for %s, existing was %s. Keeping the existing one",
                              parsed_sig, methods[name])
            else:
                methods[name] = Method(service, parsed_sig, debug)

        service.methods = methods

        if "notifications" in payload and "switchNotifications" in methods:
            notifications = [
                Notification(
                    service_endpoint, methods["switchNotifications"], notification
                )
                for notification in payload["notifications"]
            ]
            service.notifications = notifications
            _LOGGER.debug("Got notifications: %s" % notifications)

        return service
765779
public function send($method, $url, $payload = null)
    {
        $socket = @fsockopen($this->host, $this->port, $errno, $errstr);

        if (!$socket) {
            throw new RuntimeException($errno.': '.$errstr);
        }

        $request = sprintf(
          "%s %s HTTP/1.1\r\nHost: %s:%d\r\nContent-Type: application/json\r\nConnection: close\r\n",
          $method,
          $url,
          $this->host,
          $this->port
        );

        if ($payload !== null) {
            $request .= 'Content-Length: '.strlen($payload)."\r\n\r\n".
                        $payload;
        }

        $request .= "\r\n";

        // @codeCoverageIgnoreStart
        if ($this->debug) {
            echo $request;
        }
        // @codeCoverageIgnoreEnd

        fwrite($socket, $request);

        $buffer = '';

        while (!feof($socket)) {
            $buffer .= fgets($socket);
        }

        list($headers, $body) = explode("\r\n\r\n", $buffer);

        return ['headers' => $headers, 'body' => $body];
    }
1299724
private function get($endPoint, array $queryParameters = array())
    {
        $request = $this->client->get($this->serverUri . $endPoint, array(
            'accept' => 'application/json'
        ));

        foreach ($queryParameters as $key => $value) {
            $request->getQuery()->add($key, $value);
        }

        try {
            $result = json_decode($request->send()->getBody(true), true);
        } catch (ClientErrorResponseException $e) {
            if (404 === $e->getResponse()->getStatusCode()) {
                throw new NotFoundException('Resource not found', $e->getCode(), $e);
            }
            throw new TransportException('Failed to execute query', $e->getCode(), $e);
        } catch (GuzzleException $e) {
            throw new TransportException('Failed to execute query', $e->getCode(), $e);
        }

        if (JSON_ERROR_NONE !== json_last_error()) {
            throw new TransportException('Unable to parse result');
        }

        return $result;
    }
215610
protected function send($method, $endpoint = '', array $headers = null, $body = null)
    {
        $this->lastResponse = null;
        $url = $this->baseUrl . $endpoint;
        $options = ['headers' => \array_merge($this->defaultHeaders, $headers)];

        if (!empty($body)) {
            $options['body'] = $body;
        }

        $this->lastRequest = $this->httpClient->request(
            $method,
            $url,
            $options
        );

        try {
            $this->lastResponse = $this->httpClient->send($this->lastRequest);
        } catch (\Exception $error) {
            throw new HttpServiceException(
                HttpServiceException::BAD_SERVICE_REQUEST,
                [$error->getMessage()]
            );
        }

        return $this->lastResponse;
    }
948196
public function parse(): Payload
    {
        /** Check signature from header */
        if (!$this->_checkSignature()) {
            throw new BadSignatureException('Hook secret does not match.');
        }

        /** Get data from different locations according to content-type */
        switch ($this->serverBag->get('CONTENT_TYPE')) {
            case 'application/json':
                $data = $this->getRawData();
                break;

            case 'application/x-www-form-urlencoded':
                $data = $_POST['payload'];
                break;

            default:
                throw new Exception('Unsupported content type: "' . $this->serverBag->get('CONTENT_TYPE') . '"');
        }
        $this->setParsedData($data);

        return $this;
    }
648332
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
    {
        $this->startTransaction();
        $response = $handler->handle($request);
        $this->endTransaction();

        return $response;
    }
731148
protected function APICallWithOptions($requestType, $endpoint, $options,  $params = null)
    {
        $postkey = $this->httpClientVersionCheck();


        $response = $this->getHttpClient()->{$requestType}($this->buildRequestUrl($endpoint, $params), [

            'headers' => $this->getResponseHeaders($this->user->token),
            $postkey =>  $options

        ]);

        $return = json_decode($response->getBody(), true);

        return $return;

    }
549764
public function retrieveResponse(OAuthUriInterface $endpoint, $requestBody, array $extraHeaders = [], $method = 'POST')
    {
        $request = new Request();
        $request
            ->setUri($endpoint->getAbsoluteUri())
            ->setMethod($method)
            ->getHeaders()->addHeaders($extraHeaders);
        if (is_array($requestBody)) {
            $request->getPost()->fromArray($requestBody);
        } else {
            $request->setContent($requestBody);
        }
        $response = $this->client->send($request);

        return $response->getBody();
    }
798271
public static function request($method, $url, $payload = [], $curlOptions = [])
    {
        return static::_httpRequest($method, $url, $payload, $curlOptions);
    }
683142
@RequestMapping(method = POST)
    public void handle(@Valid @RequestBody P payload) {
        logger.debug("{} handlers", handlers.size());
        for (H handler : handlers) {
            executor.execute(runnableHandler(handler, payload));
        }
    }
222191
public function getRequestTransformations($api, $endpoint)
    {
        if (isset($this->requestTransformations[$api])) {
            $patterns = array_keys($this->requestTransformations[$api]);

            foreach ($patterns as $pattern) {
                preg_match($pattern, $endpoint, $matches);

                if (!empty($matches[1])) {
                    return $this->requestTransformations[$api][$pattern];
                }
            }
        }

        return [];
    }
1103087
public static function send($httpMethod, $url, $body = null, $headers = array())
    {
        if ($headers == null) {
            $headers = array();
        }
        $annexHeaders = array();
        $finalHeaders = array_merge($headers, self::$defaultHeaders);
        foreach ($finalHeaders as $key => $val) {
            $annexHeaders[] = self::getHeader($key, $val);
        }
        $lowerCaseFinalHeaders = array_change_key_case($finalHeaders);
        $ch = curl_init();
        if ($httpMethod != self::GET) {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $httpMethod);
            if (is_array($body) || $body instanceof Traversable) {
                self::http_build_query_for_curl($body, $postBody);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $postBody);
            } else {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
            }
        } elseif (is_array($body)) {
            if (strpos($url, '?') !== false) {
                $url .= "&";
            } else {
                $url .= "?";
            }
            self::http_build_query_for_curl($body, $postBody);
            $url .= urldecode(http_build_query($postBody));
        }
        curl_setopt($ch, CURLOPT_URL, self::encodeUrl($url));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $annexHeaders);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, self::$verifyPeer);
        curl_setopt($ch, CURLOPT_ENCODING, ""); // If an empty string, "", is set, a header containing all supported encoding types is sent.
        if (self::$socketTimeout != null) {
            curl_setopt($ch, CURLOPT_TIMEOUT, self::$socketTimeout);
        }
        $response = curl_exec($ch);
        $error    = curl_error($ch);
        if ($error) {
            throw new \Exception($error);
        }
        // Split the full response in its headers and body
        $curl_info   = curl_getinfo($ch);
        $header_size = $curl_info["header_size"];
        $header      = substr($response, 0, $header_size);
        $body        = substr($response, $header_size);
        $httpCode    = $curl_info["http_code"];
        if ($httpCode != 200) {
            throw new \Exception("\nhttpcode:".$httpCode."\nmessage".$body);
        }
        return new HttpResponse($httpCode, $body, $header);
    }