serializes resource to output stream

@param   mixed  $resource
@param   \stubbles\streams\OutputStream  $out
@return  \stubbles\streams\OutputStream
192956
public function serialize($resource, OutputStream $out): OutputStream
    {
        if (is_object($resource) && method_exists($resource, '__toString')) {
            $out->write((string) $resource);
        } elseif (is_object($resource) || is_array($resource)) {
            $out->write(var_export($resource, true));
        } elseif (is_bool($resource) && $resource) {
            $out->write('true');
        } elseif (is_bool($resource) && !$resource) {
            $out->write('false');
        } else {
            $out->write((string) $resource);
        }

        return $out;
    }
41619
protected function loadResource($resource)
    {
        $stream = fopen($resource, 'r');

        $stat = fstat($stream);

        if ($stat['size'] < self::MO_HEADER_SIZE) {
            throw new InvalidResourceException('MO stream content has an invalid format.');
        }
        $magic = unpack('V1', fread($stream, 4));
        $magic = hexdec(substr(dechex(current($magic)), -8));

        if (self::MO_LITTLE_ENDIAN_MAGIC == $magic) {
            $isBigEndian = false;
        } elseif (self::MO_BIG_ENDIAN_MAGIC == $magic) {
            $isBigEndian = true;
        } else {
            throw new InvalidResourceException('MO stream content has an invalid format.');
        }

        // formatRevision
        $this->readLong($stream, $isBigEndian);
        $count = $this->readLong($stream, $isBigEndian);
        $offsetId = $this->readLong($stream, $isBigEndian);
        $offsetTranslated = $this->readLong($stream, $isBigEndian);
        // sizeHashes
        $this->readLong($stream, $isBigEndian);
        // offsetHashes
        $this->readLong($stream, $isBigEndian);

        $messages = [];

        for ($i = 0; $i < $count; ++$i) {
            $pluralId = null;
            $translated = null;

            fseek($stream, $offsetId + $i * 8);

            $length = $this->readLong($stream, $isBigEndian);
            $offset = $this->readLong($stream, $isBigEndian);

            if ($length < 1) {
                continue;
            }

            fseek($stream, $offset);
            $singularId = fread($stream, $length);

            if (false !== strpos($singularId, "\000")) {
                list($singularId, $pluralId) = explode("\000", $singularId);
            }

            fseek($stream, $offsetTranslated + $i * 8);
            $length = $this->readLong($stream, $isBigEndian);
            $offset = $this->readLong($stream, $isBigEndian);

            if ($length < 1) {
                continue;
            }

            fseek($stream, $offset);
            $translated = fread($stream, $length);

            if (false !== strpos($translated, "\000")) {
                $translated = explode("\000", $translated);
            }

            $ids = ['singular' => $singularId, 'plural' => $pluralId];
            $item = compact('ids', 'translated');

            if (\is_array($item['translated'])) {
                $messages[$item['ids']['singular']] = stripcslashes($item['translated'][0]);
                if (isset($item['ids']['plural'])) {
                    $plurals = [];
                    foreach ($item['translated'] as $plural => $translated) {
                        $plurals[] = sprintf('{%d} %s', $plural, $translated);
                    }
                    $messages[$item['ids']['plural']] = stripcslashes(implode('|', $plurals));
                }
            } elseif (!empty($item['ids']['singular'])) {
                $messages[$item['ids']['singular']] = stripcslashes($item['translated']);
            }
        }

        fclose($stream);

        return array_filter($messages);
    }
858301
public static Writer getOutputStreamWriter(OutputStream out) {
    try {
      return new OutputStreamWriter(out, "UTF-8");
    }
    catch (UnsupportedEncodingException ex) {
      throw new RuntimeException(ex); // shouldn't happen since UTF-8 is supported by all JVMs per spec
    }
  }
111257
public function writeStream($path, $resource, \League\Flysystem\Config $config) {
			return $this->write($path, $resource, $config);
		}
308981
public static void setOutputStream(final OutputStream out) {
        LowLevelLogUtil.writer = new PrintWriter(Objects.requireNonNull(out), true);
    }
475277
public synchronized void setOutputStream(OutputStream out)
    {
        _reopen=isStarted() && out!=out;
        _filename=null;
        if (_buffer!=null)
            _buffer.resetWriter();
        _out=out;
    }
334503
protected function createResourceOutput(?array $resources) : ?string
    {
        if (empty($resources)) {
            return null;
        }

        $output = [];

        foreach ($resources as $resource) {
            $str = <<<'SCRIPTSTR'
<script type="application/javascript" src="{{url}}"{{async}}{{defer}}{{integ}}{{cors}}></script>
SCRIPTSTR;

            $output[] = Str::format($str, [
                'url'   => $this->parseOutputUrl($resource->url, $resource->filename),
                'async' => $resource->async ? ' async' : null,
                'defer' => $resource->defer ? ' defer' : null,
                'integ' => $resource->integrity !== null ? ' integrity="' . $resource->integrity . '"' : null,
                'cors'  => $resource->crossorigin !== null ? ' crossorigin="' . $resource->crossorigin . '"' : null,
            ]);
        }

        return implode("\n", $output);
    }
851110
public function writeStream($path, $resource, Config $config)
    {
        $options = $this->getOptions($this->options, $config);
        $contents = stream_get_contents($resource);

        return $this->write($path, $contents, $config);
    }
1373218
public ByteArrayInputStream output2InputStream(final OutputStream out) {
        if (out == null) return null;
        return new ByteArrayInputStream(((ByteArrayOutputStream) out).toByteArray());
    }
378875
public function serialize($resource, OutputStream $out): OutputStream
    {
        $out->write($this->xmlSerializerFacade->serializeToXml($resource));
        return $out;
    }
19921
public static function stream($body = null): StreamInterface
    {
        if ($body instanceof StreamInterface) {
            return $body;
        }

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

        $resource = \fopen('php://temp', 'rw+b');
        $stream = new Stream($resource);
        if ($body) {
            $stream->write($body);
        }

        return $stream;
    }
31314
public static function toArray($resource) {
		if (self::isArray($resource)) {
			return $resource;

		} else if (self::isObject($resource)) {
			return self::buildArray($resource);

		} else if (self::isJson($resource)) {
			return json_decode($resource, true);

		} else if ($ser = self::isSerialized($resource)) {
			return self::toArray($ser);

		} else if ($xml = self::isXml($resource)) {
			return self::xmlToArray($xml);
		}

		return $resource;
	}
24863
private static function create(string $target): OutputStream
    {
        $out      = new self(fopen($target, 'w'));
        $encoding = self::detectOutputEncoding();
        if ('UTF-8' !== $encoding) {
            $out = new EncodingOutputStream($out, $encoding . '//IGNORE');
        }

        return $out;
    }
513905
public function getResourceStream(DatabaseResource $resource): StreamInterface
    {
        switch ($this->conn->getDriverName()) {
            case DB::DRIVER_MYSQL:
            case DB::DRIVER_SQLITE:
                $stmt = $this->conn->prepare("SELECT `data` FROM `#__webdav_file_data` WHERE `resource_id` = :id ORDER BY `resource_id`, `chunk`");
                $stmt->bindValue('id', $resource->getIdentifier());
                $stmt->transform('data', new StreamTransformer());
                
                return new DatabaseOutputStream($stmt);
        }
        
        $stmt = $this->conn->prepare("SELECT `data` FROM `#__webdav_file_data` WHERE `resource_id` = :id");
        $stmt->bindValue('id', $resource->getIdentifier());
        $stmt->transform('data', new StreamTransformer());
        $stmt->execute();
        
        return $stmt->fetchNextColumn('data');
    }
197269
public void output(Resource resource) throws IOException {
		OutputStream nullo = ByteStreams.nullOutputStream();
		CountingOutputStream co = new CountingOutputStream(nullo);
		try {
			StreamCopy.copy(resource.getInputStream(), co);
		} catch(GZIPFormatException e) {
			e.printStackTrace();
			return;
		}
		long bytes = co.getCount();
		if(bytes > 0) {
			LOG.info(bytes + " unconsumed bytes in Resource InputStream.");
		}
		try {
			MetaData m = resource.getMetaData().getTopMetaData();
			// URL DATE OURL MIME HTTP-CODE SHA1 META REDIR OFFSET LENGTH FILE

			String filename = getContainerFilename(m);
			String offset = getContainerOffset(m);
			String gzLen = getGZLength(m);
			String format = getEnvelopeFormat(m);
			String origUrl = "TBD";
			String date = "TBD";
			String canUrl = "TBD";

			String mime = "TBD";
			String httpCode = "TBD";
			String digest = "TBD";
			String meta = "TBD";
			String redir = "TBD";
			
			if(format.startsWith("WARC")) {
				origUrl = getWARCURL(m);
				date = getWARCDate(m);
				String type = getWARCType(m);
				if(type.equals("response")) {
					// is it http or DNS:
					String recType = getWARCContentType(m);
					if(recType.equals("text/dns")) {
						// hrmm..
						redir = "-";
						meta = "-";
						httpCode = "-";
						mime = recType;
						digest = getEnvelopeBlockDigest(m);

					} else if(recType.equals("application/http; msgtype=response")) {
						httpCode = getHTTPStatus(m);
						digest = getHTTPEntityDigest(m);
						JSONObject headers = JSONUtils.extractObject(m, "Envelope.Payload-Metadata.HTTP-Response-Metadata.Headers");
						mime = normalizeHTTPMime(scanHeadersLC(headers, "content-type", "unk"));
						redir = scanHeadersLC(headers, "location", "-");
						meta = scanHeadersLC(headers, X_ROBOTS_HTTP_HEADER, null);
						if(meta != null) {
							meta = parseRobotInstructions(meta);
						} else {
							meta = "-";
						}
						if(mime.toLowerCase().contains("html")) {
							if(redir.equals("-")) {
								// maybe an obvious meta-refresh?
								redir = extractHTMLMetaRefresh(origUrl,m);
							}
							if(meta.equals("-")) {
								// see if there are HTML robot instructions:
								meta = extractHTMLRobots(m);
							}
						}
					}
				} else if(type.equals("warcinfo")) {
					origUrl = "warcinfo:/" + filename + "/" + IAUtils.COMMONS_VERSION.replaceAll(" ", "_");
					redir = "-";
					meta = "-";
					httpCode = "-";
					mime = "warc-info";
					digest = getEnvelopeBlockDigest(m);
				
				} else if(type.equals("request")) {
					mime = "warc/request";
					redir = "-";
					meta = "-";
					httpCode = "-";
					digest = getEnvelopeBlockDigest(m);
				} else if(type.equals("metadata")) {
					// interesting...?
					mime = "warc/metadata";
					redir = "-";
					meta = "-";
					httpCode = "-";
					digest = getEnvelopeBlockDigest(m);
				} else if(type.equals("revisit")) {
					mime = "warc/revisit";
					redir = "-";
					meta = "-";
					httpCode = "-";
					digest = getWARCPayloadDigest(m);
				}
			} else if(format.equals("ARC")) {
				origUrl = getARCURL(m);
				date = getARCDate(m);
				if(origUrl.startsWith("filedesc:")) {
					// ARC header record:
					origUrl = "filedesc:/" +filename + "/" + IAUtils.COMMONS_VERSION.replaceAll(" ", "_");
					mime = "arc-filedesc";
					redir = "-";
					meta = "-";
					httpCode = "-";
					digest = getEnvelopeBlockDigest(m);
				} else {
					// either an alexa/dat, or an HTTP response (we hope):
					mime = getARCContentType(m);
					if(mime.equals("alexa/dat")) {
						redir = "-";
						meta = "-";
						httpCode = "-";
						digest = getEnvelopeBlockDigest(m);
					} else {

						httpCode = getHTTPStatus(m);
						digest = getHTTPEntityDigest(m);
						JSONObject headers = JSONUtils.extractObject(m, "Envelope.Payload-Metadata.HTTP-Response-Metadata.Headers");
						mime = normalizeHTTPMime(scanHeadersLC(headers, "content-type", "unk"));
						redir = scanHeadersLC(headers, "location", "-");
						meta = scanHeadersLC(headers, X_ROBOTS_HTTP_HEADER, null);
						if(meta != null) {
							meta = parseRobotInstructions(meta);
						} else {
							meta = "-";
						}
						if(mime.toLowerCase().contains("html")) {
							if(redir.equals("-")) {
								// maybe an obvious meta-refresh?
								redir = extractHTMLMetaRefresh(origUrl,m);
							}
							if(meta.equals("-")) {
								// see if there are HTML robot instructions:
								meta = extractHTMLRobots(m);
							}
						}

					}
				}
			}
			if(!redir.equals("-")) {
				redir = resolve(origUrl, redir);
			}
			canUrl = keyMaker.makeKey(origUrl);
			// URL DATE OURL MIME HTTP-CODE SHA1 META REDIR OFFSET LENGTH FILE
			if(dumpJSON) {
				out.format("%s %s %s %s %s %s %s %s %s %s %s %s\n", 
						canUrl, 
						date, 
						origUrl,
						mime,
						httpCode,
						digest,
						redir,
						meta,
						gzLen, 
						offset, 
						filename, 
						m.toString(1));
			} else {
				out.format("%s %s %s %s %s %s %s %s %s %s %s\n", 
						canUrl, 
						date, 
						origUrl,
						mime,
						httpCode,
						digest,
						redir,
						meta,
						gzLen, 
						offset, 
						filename);

			}
//			out.println(filename + " "+resource.getMetaData().getTopMetaData().toString(1));
		} catch (JSONException e) {
			throw new IOException(e);
		} catch (URISyntaxException e) {
			throw new IOException(e);
		}
		out.flush();
	}
556333
public void stringToOutputStream(String content, OutputStream out) throws IOException {
        out.write(content.getBytes());
        out.close();
    }
1246832
private function outputStream(): ResourceOutputStream
    {
        if (null === $this->outputStream)
        {
            $this->outputStream = new ResourceOutputStream(self::createStream($this->host, $this->port), 65000);
        }

        return $this->outputStream;
    }