aboutsummaryrefslogtreecommitdiffstats
path: root/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/ZipBuilder.java
blob: 17d347bda17456d0319f19f32ae059bf71cb828f (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
63
64
65
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.deployment;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.function.Predicate;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * Utility class to build zipped content by adding already zipped byte content or
 * adding new unzipped entries.
 *
 * @author freva
 */
public class ZipBuilder implements AutoCloseable {

    private final ByteArrayOutputStream byteArrayOutputStream;
    private final ZipOutputStream zipOutputStream;

    public ZipBuilder(int initialSize) {
        byteArrayOutputStream = new ByteArrayOutputStream(initialSize);
        zipOutputStream = new ZipOutputStream(byteArrayOutputStream);
    }

    public void add(byte[] zippedContent, Predicate<String> filter) {
        try (ZipInputStream zin = new ZipInputStream(new ByteArrayInputStream(zippedContent))) {
            for (ZipEntry entry = zin.getNextEntry(); entry != null; entry = zin.getNextEntry()) {
                if ( ! filter.test(entry.getName())) continue;
                zipOutputStream.putNextEntry(new ZipEntry(entry.getName()));
                zin.transferTo(zipOutputStream);
                zipOutputStream.closeEntry();
            }
        } catch (IOException e) {
            throw new UncheckedIOException("Failed to add zipped content", e);
        }
    }

    public void add(String entryName, byte[] content) {
        try {
            zipOutputStream.putNextEntry(new ZipEntry(entryName));
            zipOutputStream.write(content);
            zipOutputStream.closeEntry();
        } catch (IOException e) {
            throw new UncheckedIOException("Failed to add entry " + entryName, e);
        }
    }

    /** @return zipped byte array */
    public byte[] toByteArray() {
        return byteArrayOutputStream.toByteArray();
    }

    @Override
    public void close() {
        try {
            zipOutputStream.close();
        } catch (IOException e) {
            throw new UncheckedIOException("Failed to close zip output stream", e);
        }
    }
}