summaryrefslogtreecommitdiffstats
path: root/vespajlib/src/test/java/com/yahoo/compress/ArchiveStreamReaderTest.java
blob: 9a292e8b3ea7e62df4325b91dfd3fc308e2331c8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.yahoo.compress;

import com.yahoo.compress.ArchiveStreamReader.Options;
import com.yahoo.yolean.Exceptions;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.junit.jupiter.api.Test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.assertEquals;

/**
 * @author mpolden
 */
class ArchiveStreamReaderTest {

    @Test
    void reading() {
        Map<String, String> zipContents = Map.of("foo", "contents of foo",
                                                 "bar", "contents of bar",
                                                 "baz", "0".repeat(2049));
        ArchiveStreamReader reader = ArchiveStreamReader.ofZip(zip(zipContents), Options.standard());
        ArchiveStreamReader.ArchiveFile file;
        Map<String, String> extracted = new HashMap<>();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while ((file = reader.readNextTo(baos)) != null) {
            extracted.put(file.path().toString(), baos.toString(StandardCharsets.UTF_8));
            baos.reset();
        }
        assertEquals(zipContents, extracted);
    }

    private static InputStream zip(Map<String, String> entries) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipArchiveOutputStream archiveOutputStream = null;
        try {
            archiveOutputStream = new ZipArchiveOutputStream(baos);
            for (var kv : entries.entrySet()) {
                String entryName = kv.getKey();
                String contents = kv.getValue();
                ZipArchiveEntry entry = new ZipArchiveEntry(entryName);
                archiveOutputStream.putArchiveEntry(entry);
                archiveOutputStream.write(contents.getBytes(StandardCharsets.UTF_8));
                archiveOutputStream.closeArchiveEntry();
            }
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        } finally {
            if (archiveOutputStream != null) Exceptions.uncheck(archiveOutputStream::close);
        }
        return new ByteArrayInputStream(baos.toByteArray());
    }

}