diff options
| author | Michael Williamson <mike@zwobble.org> | 2016-02-21 09:44:16 +0000 |
|---|---|---|
| committer | Michael Williamson <mike@zwobble.org> | 2016-02-21 09:44:16 +0000 |
| commit | c1604e510cc831a00f6105df35c68a856f061b65 (patch) | |
| tree | 699e55b0d654ec464fe25c0b21964de3d9bbc780 /src/main/java/org/zwobble/mammoth/docx/InMemoryDocxFile.java | |
| parent | 9d5da9d5339055198aac8d0d41c3d33d97344ebd (diff) | |
Allow input streams to be read
Diffstat (limited to 'src/main/java/org/zwobble/mammoth/docx/InMemoryDocxFile.java')
| -rw-r--r-- | src/main/java/org/zwobble/mammoth/docx/InMemoryDocxFile.java | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/src/main/java/org/zwobble/mammoth/docx/InMemoryDocxFile.java b/src/main/java/org/zwobble/mammoth/docx/InMemoryDocxFile.java new file mode 100644 index 0000000..3c6d4b4 --- /dev/null +++ b/src/main/java/org/zwobble/mammoth/docx/InMemoryDocxFile.java @@ -0,0 +1,46 @@ +package org.zwobble.mammoth.docx; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; +import com.google.common.io.ByteStreams; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.Optional; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +public class InMemoryDocxFile implements DocxFile { + public static DocxFile fromStream(InputStream stream) throws IOException { + ZipInputStream zipStream = new ZipInputStream(stream); + ImmutableMap.Builder<String, byte[]> entries = ImmutableMap.builder(); + ZipEntry entry; + while ((entry = zipStream.getNextEntry()) != null) { + entries.put(entry.getName(), ByteStreams.toByteArray(zipStream)); + } + return new InMemoryDocxFile(entries.build()); + } + + public static DocxFile fromStrings(Map<String, String> entries) { + return new InMemoryDocxFile(Maps.transformValues(entries, value -> value.getBytes(StandardCharsets.UTF_8))); + } + + private final Map<String, byte[]> entries; + + public InMemoryDocxFile(Map<String, byte[]> entries) { + this.entries = entries; + } + + @Override + public Optional<InputStream> tryGetInputStream(String name) throws IOException { + return Optional.ofNullable(entries.get(name)) + .map(ByteArrayInputStream::new); + } + + @Override + public void close() throws IOException { + } +} |
