serializes iterable to csv

@param  iterable  $resource
@param  \stubbles\streams\OutputStream  $out
779852
private function serializeIterable($resource, OutputStream $out)
    {
        $memory = fopen('php://memory', 'wb');
        if (is_array($resource) && is_scalar(current($resource))) {
            if (!is_numeric(key($resource))) {
                $out->write($this->toCsvLine(array_keys($resource), $memory));
            }

            $out->write($this->toCsvLine($resource, $memory));
        } else {
            $head = true;
            foreach (Sequence::of($resource)->map('stubbles\sequence\castToArray') as $elements) {
                if ($head && !is_numeric(key($elements))) {
                    $out->write($this->toCsvLine(array_keys($elements), $memory));
                }

                $head = false;
                $out->write($this->toCsvLine($elements, $memory));
            }
        }

        fclose($memory);
    }
1025670
public static void exportToStream(final OutputStream outputStream, final Iterable<? extends NodeInterface> nodes, final Iterable<? extends RelationshipInterface> relationships, final Iterable<String> filePaths, final boolean includeFiles) throws FrameworkException {

		try (final ZipOutputStream zos = new ZipOutputStream(outputStream)) {

			final Set<String> filesToInclude = new LinkedHashSet<>();
			if (filePaths != null) {

				for (String file : filePaths) {

					filesToInclude.add(file);
				}
			}

			// set compression
			zos.setLevel(6);

			if (includeFiles) {

				logger.info("Exporting files..");

				// export files first
				exportDirectory(zos, new File("files"), "", filesToInclude.isEmpty() ? null : filesToInclude);
			}

			// export database
			exportDatabase(zos, new BufferedOutputStream(zos), nodes, relationships);

			// finish ZIP file
			zos.finish();

			// close stream
			zos.flush();
			zos.close();

		} catch (Throwable t) {

			logger.warn("", t);

			throw new FrameworkException(500, t.getMessage());
		}
	}
1162355
public function serialize(CurrentState $state, $outputStream)
    {
        $statusLeaseInfo = [
            'StatusLease' => [
                '@attributes' => [
                    'ClientId' => $state->getClientId(),
                ],
            ],
        ];

        if ($state instanceof AcquireCurrentState) {
            $statusLeaseInfo['StatusLease']['Acquire'] = [
                'Incarnation' => $state->getIncarnation(),
                'Status' => $state->getStatus(),
                'Expiration' => Utilities::isoDate(
                    date_timestamp_get($state->getExpiration())
                ),
            ];
        } elseif ($state instanceof ReleaseCurrentState) {
            $statusLeaseInfo['StatusLease']['Release'] = [];
        }

        $currentState = Utilities::serialize($statusLeaseInfo, 'CurrentState');
        fwrite($outputStream, $currentState);
    }
393683
public static void write(Writer out, Object object) throws IOException {
        if (object instanceof String) {
            out.write((String) object);
        } else if (object instanceof Object[]) {
            out.write(toArrayString((Object[]) object));
        } else if (object instanceof Map) {
            out.write(toMapString((Map) object));
        } else if (object instanceof Collection) {
            out.write(toListString((Collection) object));
        } else if (object instanceof Writable) {
            Writable writable = (Writable) object;
            writable.writeTo(out);
        } else if (object instanceof InputStream || object instanceof Reader) {
            // Copy stream to stream
            Reader reader;
            if (object instanceof InputStream) {
                reader = new InputStreamReader((InputStream) object);
            } else {
                reader = (Reader) object;
            }

            try (Reader r = reader) {
                char[] chars = new char[8192];
                for (int i; (i = r.read(chars)) != -1; ) {
                    out.write(chars, 0, i);
                }
            }
        } else {
            out.write(toString(object));
        }
    }
1370859
public static function create($resource = '', array $options = []): StreamInterface
    {
        switch (gettype($resource)) {
            case 'string':
                $stream = fopen('php://temp', 'r+');
                if ($resource !== '') {
                    fwrite($stream, $resource);
                    fseek($stream, 0);
                }
                return new Stream($stream, $options);
            case 'resource':
                return new Stream($resource, $options);
            case 'object':
                if ($resource instanceof StreamInterface) {
                    return $resource;
                } elseif ($resource instanceof \Traversable) {
                    return new IteratorStream($resource, $options);
                } elseif (method_exists($resource, '__toString')) {
                    return static::createStream((string)$resource, $options);
                }
                break;
            case 'NULL':
                return new Stream('php://temp', 'r+');
        }

        throw new InvalidStreamException(
            'Invalid resource type: ' . gettype($resource)
        );
    }
566737
@SneakyThrows
    public static void serialize(final Serializable object, final OutputStream outputStream) {
        try (val out = new ObjectOutputStream(outputStream)) {
            out.writeObject(object);
        }
    }
640751
public static void writeToOutputStream(String s, OutputStream output) throws IOException {
		writeToOutputStream(s, output, null);
	}
373607
public void serialize(XAttributeMap map, DataOutput out) throws IOException {
		serialize(map.values(), out);
	}
378875
public function serialize($resource, OutputStream $out): OutputStream
    {
        $out->write($this->xmlSerializerFacade->serializeToXml($resource));
        return $out;
    }
404623
public function writeRow(iterable $row): void
    {
        $str = Csv::dump($row, $this->delimiter, $this->enclosure, $this->escape);

        try {
            $written = $this->stream->write($str);
        } catch (\Throwable $e) {
            throw new \RuntimeException('Failed to write CSV row.', 0, $e);
        }

        if (strlen($str) !== $written) {
            throw new \RuntimeException('Failed to write CSV row.');
        }
    }
719292
public static function writeCsvToStream(array $csvData, $handle)
    {
        if (is_null($handle)) {
            throw new InvalidArgumentException('File handle is null.');
        }

        foreach ($csvData as $line) {
            fputcsv($handle, $line);
        }
    }
162209
public static void writeObjectToStream(final Object o, OutputStream out) {
    out = new BufferedOutputStream(out);
    try {
      final ObjectOutputStream oos = new ObjectOutputStream(out);
      oos.writeObject(o);
      oos.flush();
    } catch (final IOException e) {
      e.printStackTrace();
    }
  }
1158850
protected function writeCsvContent($resource)
    {
        $columns    = $this->exportInfo->columns;
        $strategies = $this->getColumnStrategyInstances();

        $delimiter = $this->getDelimiterSymbol();
        $enclosure = $this->getEnclosureSymbol();
        $escape    = $this->getEscapeSymbol();


        // Generate header row, if not disabled
        if ($this->shouldHaveHeaderRow()) {

            $headers = array_map(
                function (ModelExportColumnDataInterface $column) {
                    return $column->header();
                },
                $columns
            );

            fputcsv($resource, $headers, $delimiter, $enclosure, $escape);
        }

        // For each query chunk: get a model instance,
        // and for each column, generate the column content using the strategies
        $this->query->chunk(
            static::CHUNK_SIZE,
            function ($records) use ($resource, $columns, $strategies, $delimiter, $enclosure, $escape) {
                /** @var Collection|Model[] $records */

                foreach ($records as $record) {

                    $fields = [];

                    foreach ($strategies as $key => $strategy) {
                        $fields[] = $strategy->render($record, $columns[$key]->source);
                    }

                    fputcsv($resource, $fields, $delimiter, $enclosure, $escape);
                }
            }
        );
    }
971285
private static void serializeCweData(Map<String, String> cwe, File out) {
        try (FileOutputStream fout = new FileOutputStream(out);
                ObjectOutputStream objOut = new ObjectOutputStream(fout);) {
            System.out.println("Writing " + cwe.size() + " cwe entries.");
            objOut.writeObject(cwe);
            System.out.println(String.format("Serialized CWE data written to %s", out.getCanonicalPath()));
            System.out.println("To update the ODC CWE data copy the serialized file to 'src/main/resources/data/cwe.hashmap.serialized'");
        } catch (IOException ex) {
            System.err.println(String.format("Error generating serialized data: %s", ex.getMessage()));
        }
    }
443499
public void writeTo(final OutputStream out) throws IOException
	{
		if(out == null) throw new NullPointerException();
		
		final int n = arrays.size();
		for(int k = 0; k < n; k++) {
			byte[] src = (byte[])arrays.get(k);
			out.write(src);
		}
		if(pos > 0) out.write(buffer, 0, pos);
	}
29200
private void writeObject(ObjectOutputStream out) throws IOException
    {
        out.defaultWriteObject();
        out.writeInt(table.length);

        // Have to use null-terminated list because size might shrink
        // during iteration

        for (Iterator iter = entrySet().iterator(); iter.hasNext();)
        {
            Map.Entry entry = (Map.Entry) iter.next();
            out.writeObject(entry.getKey());
            out.writeObject(entry.getValue());
        }
        out.writeObject(null);
    }
445146
@Trivial
    private void writeObject(ObjectOutputStream out) throws IOException {
        PutField fields = out.putFields();
        fields.put(FAILURE, failure);
        fields.put(PREVIOUS_RESULT, previousResult);
        out.writeFields();
    }