All Downloads are FREE. Search and download functionalities are using the official Maven repository.

global.namespace.fun.io.commons.compress.ZipFileAdapter Maven / Gradle / Ivy

There is a newer version: 2.4.1
Show newest version
/*
 * Copyright (C) 2013-2018 Schlichtherle IT Services.
 * All rights reserved. Use is subject to license terms.
 */
package global.namespace.fun.io.commons.compress;

import global.namespace.fun.io.api.ArchiveEntrySource;
import global.namespace.fun.io.api.ArchiveInput;
import global.namespace.fun.io.api.Socket;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Optional;

/**
 * Adapts a {@link ZipFile} to an {@link ArchiveInput}.
 *
 * @author Christian Schlichtherle
 */
final class ZipFileAdapter implements ArchiveInput {

    private final ZipFile zip;

    ZipFileAdapter(final ZipFile zip) { this.zip = zip; }

    @Override
    public Iterator> iterator() {
        return new Iterator>() {

            final Enumeration en = zip.getEntries();

            @Override
            public boolean hasNext() { return en.hasMoreElements(); }

            @Override
            public ArchiveEntrySource next() { return source(en.nextElement()); }
        };
    }

    @Override
    public Optional> source(String name) {
        return Optional.ofNullable(zip.getEntry(name)).map(this::source);
    }

    private ZipArchiveEntrySource source(ZipArchiveEntry entry) {
        return new ZipArchiveEntrySource() {

            @Override
            public String name() { return entry.getName(); }

            @Override
            public long size() { return entry.getSize(); }

            @Override
            public boolean isDirectory() { return entry.isDirectory(); }

            @Override
            public ZipArchiveEntry entry() { return entry; }

            @Override
            public Socket input() { return () -> zip.getInputStream(entry); }

            Socket rawInput() { return () -> zip.getRawInputStream(entry); }
        };
    }

    @Override
    public void close() throws IOException { zip.close(); }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy