Decodes the JSONRPC response stream.
Request is used for matching id.
@todo Name is not set to response from request - a bit weird...
@param ggJSONRPCRequest $request
329197
function decodeStream( $request, $stream, $headers=false, $cookies=array(), $statuscode="200"  )
    {
        $this->decodeStreamCommon( $request, $stream, $headers, $cookies, $statuscode );

        /// @todo refuse bad content-types?

        $results = json_decode( $stream, true );
        if ( !is_array($results) ||
            !array_key_exists( 'result', $results ) ||
            !array_key_exists( 'error', $results ) ||
            !array_key_exists( 'id', $results )
            )
        {
            // invalid jsonrpc response
            $this->IsFault = true;
            $this->FaultCode = self::INVALIDRESPONSEERROR;
            $this->FaultString = self::INVALIDRESPONSESTRING;
        }
        else
        {
            $this->Id =  $results['id'];

            /// we should check if id of response is same as id of request, and raise error if not
            if ( $results['id'] != $request->id() )
            {
                $this->IsFault = true;
                $this->FaultCode = self::INVALIDIDERROR;
                $this->FaultString = self::INVALIDIDSTRING;
            }
            else if ( $results['error'] === null )
            {
                /// NB: spec is formally strange: what if both error and result are null???

                $this->Value = $results['result'];
            }
            else
            {
                $this->IsFault = true;
                $error = $results['error'];
                if ( is_array( $error ) && array_key_exists( 'faultCode', $error ) && array_key_exists( 'faultString', $error ) )
                {
                    // since server conforms to our error syntax, we force the types on him, too
                    $this->FaultCode = (int)$error['faultCode'];
                    $this->FaultString = (string)$error['faultString'];
                }
                else
                {
                    $this->FaultCode = self::GENERICRESPONSEERROR;
                    /// @todo we should somehow typecast to string here??? maybe reencode as json?
                    $this->FaultString = $results['error'];
                }
            }
        }
    }
1114709
function decodeJSON($json)
    {
        $json_response = json_decode($json);
        if ($json_response === null) {
            throw new Clientside\Exception("Unable to decode JSON response from: {$json}");
        }
        return $json_response;
    }
1321592
private function decodeJSON($json)
    {
        $query = json_decode($json);

        if (json_last_error()) {
            throw new QBParseException('JSON parsing threw an error: '.json_last_error_msg());
        }

        if (!is_object($query)) {
            throw new QBParseException('The query is not valid JSON');
        }

        return $query;
    }
1371572
function processRequestObj( $request )
    {
        $functionName = $request->name();
        if ( array_key_exists( $functionName, $this->FunctionList ) )
        {
            /// we use a self-generated wsdl (even if user gave no param description), as it is supposedly better than nothing...
            $wsdlUrl = ggeZWebservices::methodsWSDL( $this, array( $functionName ), $functionName, true );
            $server = new SoapServer( $wsdlUrl, array( 'soap_version' => $request->getSoapVersion(), /*'uri' => '...'*/ ) );
            foreach( $this->FunctionList as $function => $desc )
            {
                $server->addFunction( $function );
            }
            //ob_start();
            $server->handle( $request->payload() );
            //$response = ob_get_clean();
        }
        else
        {
            $this->showResponse( $functionName, '...', new ggWebservicesFault( self::INVALIDMETHODERROR, self::INVALIDMETHODSTRING . " '$functionName'" ) );
        }
    }
624402
private function decode($json)
  {
    $decodedResult = json_decode($json, true);
    if (JSON_ERROR_NONE != json_last_error()) {
      throw new ResponseDecodeException('JSON error: '.json_last_error_msg());
    }

    return $decodedResult;
  }
791156
public CrossDomainRpc loadRpc(HttpServletRequest request) throws IOException {
    Charset encoding;
    try {
      String enc = request.getCharacterEncoding();
      encoding = Charset.forName(enc);
    } catch (IllegalArgumentException | NullPointerException e) {
      encoding = UTF_8;
    }

    // We tend to look at the input stream, rather than the reader.
    try (InputStream in = request.getInputStream();
        Reader reader = new InputStreamReader(in, encoding);
        JsonInput jsonInput = json.newInput(reader)) {
      Map<String, Object> read = jsonInput.read(MAP_TYPE);

      return new CrossDomainRpc(
          getField(read, Field.METHOD),
          getField(read, Field.PATH),
          getField(read, Field.DATA));
    } catch (JsonException e) {
      throw new IllegalArgumentException(
          "Failed to parse JSON request: " + e.getMessage(), e);
    }
  }
763582
function parseRequest( $payload )
    {
        $request = new ggRESTRequest();
        if ( $request->decodeStream( $payload ) )
        {
            $this->ResponseType = $request->responseType();
            $this->JsonpCallback = $request->jsonpCallback();
            return $request;
        }
        else
        {
            $this->ResponseType = '';
            return false;
        }
    }
357674
public function decode($json)
    {
        $decoded = json_decode($json, true);
        if (null !== $decoded) {
            return $decoded;
        }
        if (JSON_ERROR_NONE === json_last_error()) {
            return $json;
        }

        return self::$json_errors[json_last_error()];
    }
435271
public function setRequest(JsonRequest $request)
    {
        $this->id = $request->getId();
        $this->jsonrpc = $request->getJsonrpc();
        $this->method = $request->getMethod();
        $this->request = $request;

        if (!$request->getResponse()) {
            $request->setResponse($this);
        }

        return $this;
    }
460350
protected function processFoxyRequest(HTTPRequest $request)
    {
        $encryptedData = $request->postVar('FoxyData')
            ? urldecode($request->postVar('FoxyData'))
            : urldecode($request->postVar('FoxySubscriptionData'));
        $decryptedData = $this->decryptFeedData($encryptedData);

        $this->parseFeedData($encryptedData, $decryptedData);

        $this->extend('addIntegrations', $encryptedData);
    }
179514
private function decodeJsonBody($body)
    {
        $data = json_decode($body, true);
        if ($data === null) {
            throw new InvalidRequestException('The request JSON body could not be decoded');
        }

        return $data;
    }
1160955
public function makeRequest(Google_HttpRequest $request) {
    // First, check to see if we have a valid cached version.
    $cached = $this->getCachedRequest($request);
    if ($cached !== false) {
      if (!$this->checkMustRevaliadateCachedRequest($cached, $request)) {
        return $cached;
      }
    }

    $default_options = stream_context_get_options(stream_context_get_default());

    $requestHttpContext = array_key_exists('http', $default_options) ?
        $default_options['http'] : array();
    if (array_key_exists($request->getRequestMethod(),
          self::$ENTITY_HTTP_METHODS)) {
      $request = $this->processEntityRequest($request);
    }

    if ($request->getPostBody()) {
      $requestHttpContext["content"] = $request->getPostBody();
    }

    $requestHeaders = $request->getRequestHeaders();
    if ($requestHeaders && is_array($requestHeaders)) {
      $headers = "";
      foreach($requestHeaders as $k => $v) {
        $headers .= "$k: $v\n";
      }
      $requestHttpContext["header"] = $headers;
    }

    $requestHttpContext["method"] = $request->getRequestMethod();
    $requestHttpContext["user_agent"] = $request->getUserAgent();

    $requestSslContext = array_key_exists('ssl', $default_options) ?
        $default_options['ssl'] : array();

    if (!array_key_exists("cafile", $requestSslContext)) {
      $requestSslContext["cafile"] = dirname(__FILE__) . '/cacerts.pem';
    }

    $options = array("http" => array_merge(self::$DEFAULT_HTTP_CONTEXT,
                                                 $requestHttpContext),
                     "ssl" => array_merge(self::$DEFAULT_SSL_CONTEXT,
                                          $requestSslContext));

    $context = stream_context_create($options);

    $response_data = file_get_contents($request->getUrl(),
                                       false,
                                       $context);

    if (false === $response_data) {
      throw new Google_IOException("HTTP Error: Unable to connect");
    }

    $respHttpCode = $this->getHttpResponseCode($http_response_header);
    $responseHeaders = $this->getHttpResponseHeaders($http_response_header);

    if ($respHttpCode == 304 && $cached) {
      // If the server responded NOT_MODIFIED, return the cached request.
      $this->updateCachedRequest($cached, $responseHeaders);
      return $cached;
    }

    $request->setResponseHttpCode($respHttpCode);
    $request->setResponseHeaders($responseHeaders);
    $request->setResponseBody($response_data);
    // Store the request in cache (the function checks to see if the request
    // can actually be cached)
    $this->setCachedRequest($request);
    return $request;
  }
619872
public function toResponse($request): JsonResponse
    {
        return response()->json([
            'success' => $this->result,
            'message' => ($this->result)
                ? trans('comments::messages.send_success')
                : trans('comments::messages.send_fail'),
        ]);
    }
665117
public function fromRequest(HttpRequestInterface $request)
    {
        return $this->createRequest(
            $request->getMethod(),
            $request->getUri(),
            $request->getHeaders(),
            JsonRpc\json_decode((string) $request->getBody(), true) ?: []
        );
    }
972707
public function doRequestInProcess($request)
    {
        if ($this->mockedResponse) {
            $response = $this->mockedResponse;
            $this->mockedResponse = null;
            return $response;
        }

        $requestCookie = $request->getCookies();
        $requestServer = $request->getServer();
        $requestFiles = $this->remapFiles($request->getFiles());

        $parseResult = parse_url($request->getUri());
        $uri = $parseResult["path"];
        if (array_key_exists("query", $parseResult)) {
            $uri .= "?" . $parseResult["query"];
        }

        $requestRequestArray = $this->remapRequestParameters($request->getParameters());

        $requestServer['REQUEST_METHOD'] = strtoupper($request->getMethod());
        $requestServer['REQUEST_URI'] = $uri;
        $requestServer['HTTP_HOST'] = $this->domain;
        $requestServer['SERVER_PROTOCOL'] = 'HTTP/1.1';
        $requestServer['SERVER_NAME'] = $this->domain;
        $requestServer['HTTP_CLIENT_IP'] = '127.0.0.1';

        $this->index = $this->uriToIndexMapper->getIndexForUri($uri);

        $phpSelf = str_replace($this->rootFolder, '', $this->index);
        $requestServer['PHP_SELF'] = $phpSelf;

        $env = [
            'headers' => $this->headers,
            'cookie' => $requestCookie,
            'server' => $requestServer,
            'files' => $requestFiles,
            'request' => $requestRequestArray,
        ];

        if (strtoupper($request->getMethod()) == 'GET') {
            $env['get'] = $env['request'];
        } else {
            $env['post'] = $env['request'];
        }

        $requestScript = dirname(dirname(__DIR__)) . '/scripts/request.php';

        $command = PHP_BINARY .
            ' ' . escapeshellarg($requestScript) .
            ' ' . escapeshellarg($this->index) .
            ' ' . escapeshellarg(base64_encode(serialize($env)));

        $process = new Process($command);
        $process->run();
        $rawProcessOutput = $process->getOutput();

        $unserializedResponse = @unserialize(base64_decode($rawProcessOutput));

        if (false === $unserializedResponse) {
            $message = 'Server responded with: ' . $rawProcessOutput;
            throw new ModuleException(\Codeception\Module\WordPress::class, $message);
        }

        $_SERVER = empty($unserializedResponse['server']) ? [] : $unserializedResponse['server'];
        $_FILES = empty($unserializedResponse['files']) ? [] : $unserializedResponse['files'];
        $_REQUEST = empty($unserializedResponse['request']) ? [] : $unserializedResponse['request'];
        $_GET = empty($unserializedResponse['get']) ? [] : $unserializedResponse['get'];
        $_POST = empty($unserializedResponse['post']) ? [] : $unserializedResponse['post'];

        $content = $unserializedResponse['content'];
        $headers = $this->replaceSiteUrlDeep($unserializedResponse['headers'], $this->url);

        $response = new Response($content, $unserializedResponse['status'], $headers);

        return $response;
    }
577448
function decodeStream( $request, $stream, $headers=false, $cookies=array(), $statuscode="200" )
    {
        $this->decodeStreamCommon( $request, $stream, $headers, $cookies, $statuscode );

        $contentType = $this->ContentType;
        $charset = $this->Charset;

        // allow request to force an expected response type
        // this is useful if servers do respond with eg. text/plain content-header for json or xml
        if ( ( $forcedType = $request->responseType() ) != '' )
        {
            list ( $contentType, $charset2 ) = $this->parseContentTypeHeader( $forcedType );
            $this->ContentType = $contentType . '; received="' . $this->ContentType . '"';
            if ( $charset2 != '' )
            {
                $charset = $charset2;
                $this->Charset = $charset . '; received="' . $this->Charset . '"';
            }
        }

        // Allow empty payloads regardless of declared content type, for 204 and 205 responses
        if ( $statuscode == '204' || $statuscode == '205' )
        {
            if ( $stream == '' && ( !isset( $headers['content-length'] ) || $headers['content-length'] == 0 ) )
            {
                $this->Value = null;
                return;
            }
            else
            {
                /// @todo this is not valid according to rfc 2616 - but we should leave that control to client really
                $this->IsFault = true;
                $this->FaultCode = ggRESTResponse::INVALIDRESPONSEERROR;
                $this->FaultString = ggRESTResponse::INVALIDRESPONSESTRING . " (received http response 204/205 with a body. Not valid http)";
            }
        }

        /// @todo take into account charset when decoding json / xml

        switch( $this->mimeTypeToEncodeType( $contentType ) )
        {
            case 'json':
            case 'application/json':
                $val = json_decode( $stream, true );
                if ( function_exists( 'json_last_error' ) )
                {
                    $err = json_last_error();
                }
                else
                {
                    $err = ( $val === null ) ? 1 : false;
                }
                if ( $err )
                {
                    $this->IsFault = true;
                    $this->FaultCode = ggRESTResponse::INVALIDRESPONSEERROR;
                    $this->FaultString = ggRESTResponse::INVALIDRESPONSESTRING . ' json. Decoding error: ' . $err;
                }
                else
                {
                    $this->Value = $val;
                }
                break;
            case 'xml':
            case 'text/xml':
            case 'application/xml':
                try
                {
                    $doc = new DOMDocument();
                    $prev = libxml_use_internal_errors( true );
                    libxml_clear_errors();
                    $doc->loadXML( $stream );
                    $node = $doc->documentElement;
                    if ( $node == null )
                    {
                        $errors = libxml_get_errors();
                        libxml_use_internal_errors( $prev );
                        $errorText = '';
                        foreach( $errors as $error)
                        {
                            if ( $error->level > LIBXML_ERR_WARNING )
                            {
                                $errorText .= trim ( $error->message ) . ", line: $error->line" . " column: $error->column\n";
                            }
                        }
                        throw new Exception( $errorText );
                    }
                    libxml_use_internal_errors( $prev );
                    $this->Value = new ggSimpleTemplateXML( $node );

                }
                catch ( Exception $e )
                {
                    $this->IsFault = true;
                    $this->FaultCode = ggRESTResponse::INVALIDRESPONSEERROR;
                    $this->FaultString = ggRESTResponse::INVALIDRESPONSESTRING . ' xml. ' . $e->getMessage();
                }
                break;
            case 'text/plain':
            case 'text/html':
                $this->Value = $stream;
                break;
            default:
                $this->IsFault = true;
                $this->FaultCode = ggRESTResponse::INVALIDRESPONSEERROR;
                $this->FaultString = ggRESTResponse::INVALIDRESPONSESTRING . " (unsupported format $contentType)";
        }
    }
438776
def jsonrpc_request(method, identifier, params=None):
    """"""
    return '{}\r\n'.format(json.dumps({
        'id': identifier,
        'method': method,
        'params': params or {},
        'jsonrpc': '2.0'
    })).encode()