Processes a request using the input stream.

@param string $inputstream Name of the input stream (usually php://input)
@return string|null JSON RPC 2.0 message response
358675
protected function _processStream( $inputstream )
	{
		$response = array();

		try
		{
			if( ( $raw = file_get_contents( $inputstream ) ) === false ) {
				throw new Controller_ExtJS_Exception( 'Unable to read JSON encoded request', -32700 );
			}

			if( ( $request = json_decode( $raw ) ) === null ) {
				throw new Controller_ExtJS_Exception( 'Invalid JSON encoded request', -32700 );
			}

			if( is_array( $request ) )
			{
				foreach( $request as $item )
				{
					if( ( $result = $this->_processJson( $item ) ) !== null ) {
						$response[] = $result;
					}
				}
			}
			else if( is_object( $request ) )
			{
				if( ( $result = $this->_processJson( $request ) ) !== null ) {
					$response = $result;
				}
			}
			else
			{
				throw new Controller_ExtJS_Exception( 'Invalid JSON RPC request', -32600 );
			}
		}
		catch( Exception $e )
		{
			$response = array(
				'error' => array(
					'code' => ( $e->getCode() != 0 ? $e->getCode() : -1 ),
					'message' => $e->getMessage(),
				),
				'id' => null,
			);
		}

		if( !empty( $response ) ) {
			return json_encode( $response );
		}

		return null;
	}
686377
protected static function getStream($response)
    {
        $stream = 'php://memory';
        $body = $response->body();
        if (is_string($body) && strlen($body)) {
            $stream = new Stream('php://memory', 'wb');
            $stream->write($body);

            return $stream;
        }
        if (is_callable($body)) {
            $stream = new CallbackStream($body);

            return $stream;
        }
        $file = $response->getFile();
        if ($file) {
            $stream = new Stream($file->path, 'rb');

            return $stream;
        }

        return $stream;
    }
1303588
public T get(InputStream stream) throws IOException, JsonFormatException {
		JsonPullParser parser = JsonPullParser.newParser(stream);
		return get(parser, null);
	}
270155
public static InputStream inputStreamForResponse(InputStream is, AmazonWebServiceRequest req) {
        return req == null
             ? is
             : new ResponseProgressInputStream(is, req.getGeneralProgressListener());
    }
510626
public function initFromStream($stream)
    {
        $stream = Factory::stream($stream);

        try {
            $offset = $stream->tell();
        } catch (\RuntimeException $e) {
            $offset = 0;
        }

        $shouldAndCanSeek = $offset !== 0 && $stream->isSeekable();

        if ($shouldAndCanSeek) {
            $stream->rewind();
        }

        try {
            $data = $stream->getContents();
        } catch (\RuntimeException $e) {
            $data = null;
        }

        if ($shouldAndCanSeek) {
            $stream->seek($offset);
        }

        if ($data) {
            return $this->initFromBinary($data);
        }

        throw new Exception\NotReadableException(
            "Unable to init from given stream"
        );
    }
450710
private function transformResponse($response)
    {
        if (is_null($response)) {
            return;
        }

        if ($body = $response->getBody()) {
            $body = new Stream($body->getStream());
        } else {
            $body = null;
        }

        $transformed = new Response(
            $response->getStatusCode(),
            null,
            $response->getHeaders(),
            $body,
            $response->getProtocolVersion()
        );

        return $transformed;
    }
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)";
        }
    }
1198920
public function readInput($inputStream = STDIN)
    {
        $output = new ConsoleOutput();

        $sttyMode = shell_exec('stty -g');

        // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
        shell_exec('stty -icanon -echo intr undef');

        $this->userInput = '';
        $this->cursorPosition = 0;

        // Make sure the array cursor of the history is at the last element.
        if (($commands = $this->history->getCommands()) != []) {
            end($commands);
            $this->history->setCommands($commands);
        }

        // Reset the counter for the up arrow.
        $this->countUpPressed = 0;

        // Read a keypress
        while (!feof($inputStream)) {
            $c = fread($inputStream, 1);

            // Backspace Character
            if ("\177" === $c) {
                $this->onBackspacePressed();
            } elseif (ord($c) == 1) { // ctrl+a has been pressed
                $this->moveCursorToBeginOfInputLine();
            } elseif (ord($c) == 3) { // ctrl+c has been pressed
                // todo: exit the shell.
            } elseif (ord($c) == 5) { // ctrl+e has been pressed
                $this->moveCursorToEndOfLine();
            } elseif (ord($c) == 11) { // ctrl+k has been pressed
                $this->removeInputRightFromCursor();
            } elseif ("\033" === $c) {
                // Did we read an escape sequence?
                $c .= fread($inputStream, 2);

                // A = Up Arrow. B = Down Arrow
                if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
                    // Clear the current line.
                    $this->clearLine();

                    if ('A' === $c[2]) {
                        $this->onUpArrowPressed();
                    } elseif ('B' === $c[2]) {
                        $this->onDownArrowPressed();
                    }

                } elseif (isset($c[2]) && ('D' === $c[2])) {
                    $this->onLeftArrowPressed();
                } elseif (isset($c[2]) && ('C' === $c[2])) {
                    $this->onRightArrowPressed();
                }
                // Enter key pressed.
            } elseif (ord($c) < 32) {
                if ("\t" === $c || "\n" === $c) {
                    if ("\n" === $c) {
                        $this->onEnterPressed();
                        break;
                    }
                }

                continue;
            } else {
                $this->userInput =
                    substr($this->userInput, 0, $this->cursorPosition) . $c .
                    substr($this->userInput, $this->cursorPosition);

                $this->cursorPosition++;
            }

            $this->printCurrentUserInput();
        }

        // Reset stty so it behaves normally again
        shell_exec(sprintf('stty %s', $sttyMode));

        $userInput = trim($this->userInput);

        return $userInput;
    }
1064649
public function input($input): ProcessBuilder
    {
        if ($input === null) {
            $this->input = null;

            return $this;
        }

        if (is_resource($input)) {
            $this->input = $input;

            return $this;
        }

        if (is_scalar($input)) {
            $this->input = (string) $input;
        }

        return $this;
    }
503142
public function setStream($stream = null)
    {
        // String passed in? Try converting it to a stream
        if (is_string($stream)) {
            $stream = @fopen($stream, 'a');
        }

        // Make sure the stream is a resource
        if (!is_resource($stream)) {
            throw new \InvalidArgumentException('Invalid Stream');
        }

        // Store it
        $this->stream = $stream;

        // Afford chaining
        return $this;
    }
668929
public function createStream($body = null)
    {
        if ($body instanceof StreamInterface)
        {
            return $body;
        }

        if (\is_resource($body))
        {
            return Stream::createFromResource($body);
        }

        return Stream::create($body ?? '');
    }
292458
public static function fromStream($response_str, $stream)
    {
        $code    = self::extractCode($response_str);
        $headers = self::extractHeaders($response_str);
        $version = self::extractVersion($response_str);
        $message = self::extractMessage($response_str);

        return new self($code, $headers, $stream, $version, $message);
    }
1317404
public static function convert($input = STDIN)
    {
        $stream = fopen('php://temp', 'rw');

        foreach ($_SERVER as $key => $value) {
            if (0 === strpos($key, 'HTTP_')) {
                $key = str_replace('_', '-', strtolower(substr($key, 5)));
                fwrite($stream, "$key: $value\r\n");
            } elseif (in_array($key, ['CONTENT_LENGTH', 'CONTENT_MD5', 'CONTENT_TYPE'])) {
                $key = str_replace('_', '-', strtolower($key));
                fwrite($stream, "$key: $value\r\n");
            }
        }

        fwrite($stream, "\r\n");

        stream_copy_to_stream($input, $stream);

        rewind($stream);

        return new StreamedPart($stream);
    }
1285501
public function getInputStream()
    {
        if (0 === func_num_args() || func_get_arg(0)) {
            @trigger_error(sprintf('The %s() method is deprecated since version 3.2 and will be removed in 4.0. Use %s::getStream() instead.', __METHOD__, StreamableInputInterface::class), E_USER_DEPRECATED);
        }

        return $this->inputStream;
    }
837774
private function request_response()
    {
        // Must not block while reading
        stream_set_blocking($this->stream, false);
        
        $response = '';
        while (true) {
            $buffer = fgets($this->stream);
            $response .= $buffer;
            if (strstr($buffer, "\n")) {
                break;
            } else {
                usleep(1000);
            }
        }

        $data = '';
        if (!$response) {
            $this->close();
            $desc = $this->request_description();
            throw new ProtocolException("Unable to read response from server ({$desc})");
        } else if (null === ($data = json_decode(trim($response), true))) {
            $desc = $this->request_description();
            throw new ProtocolException("Unable to parse response from server ({$desc}): {$response}");
        } else if (!is_array($data)) {
            $desc = $this->request_description();
            throw new ProtocolException("Invalid response from server ({$desc}): ".json_encode($data));
        }

        if (isset($data['$error'])) {
            throw new ServerException((string)$data['$error']);
        }
        if (isset($data['$end'])) {
            $this->close();
        }

        return $data;
    }
978145
private function processHttpResponse($response)
    {
        if ($response === null) {
            return null;
        }

        switch ($this->fakeType) {
            case 'pngb64':
                $base64 = base64_encode($response->getBody());
                return 'data:image/png;base64,' . $base64;
            case 'object': // 'object' not supported yet, we return array instead.
            case 'array':
                return json_decode($response->getBody(), true);
            default:
                return $response->getBody()->__toString();
        }
    }
680619
@Override
   public InputStream getInputStream() throws IOException
   {
      if (!connected)
         connect();

      try
      {
         return nodeRepresentation.getInputStream();
      }
      catch (IOException e)
      {
         //e.printStackTrace();
         throw new IOException("can't get input stream", e);
      }
      catch (RepositoryException e)
      {
         //e.printStackTrace();
         throw new IOException("can't get input stream", e);
      }
   }