de.fhg.iais.cortex.services.ingest.ZipStreamAipBinaries.java Source code

Java tutorial

Introduction

Here is the source code for de.fhg.iais.cortex.services.ingest.ZipStreamAipBinaries.java

Source

package de.fhg.iais.cortex.services.ingest;

/******************************************************************************
 * Copyright 2011 (c) Fraunhofer IAIS Netmedia  http://www.iais.fraunhofer.de *
 * ************************************************************************** *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may    *
 * not use this file except in compliance with the License.                   *
 * You may obtain a copy of the License at                                    *
 * http://www.apache.org/licenses/LICENSE-2.0                                 *
 * Unless required by applicable law or agreed to in writing,                 *
 * software distributed under the License is distributed on an "AS IS" BASIS, *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *
 * See the License for the specific language governing permissions and        *
 * limitations under the License.                                             *
 ******************************************************************************/

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.CloseShieldInputStream;

import de.fhg.iais.commons.stream.INamedBinaryStream;
import de.fhg.iais.commons.stream.NamedBinaryStream;
import de.fhg.iais.cortex.model.aip.util.IAipBinaries;

public class ZipStreamAipBinaries implements IAipBinaries, Closeable {

    private final ZipInputStream zipInputStream;
    private boolean isRead = false;

    public ZipStreamAipBinaries(InputStream inputStreamInZipFormat) {
        this.zipInputStream = new ZipInputStream(inputStreamInZipFormat);
    }

    public INamedBinaryStream takeBinary() throws IOException {
        ZipEntry zipEntry;
        do {
            zipEntry = this.zipInputStream.getNextEntry();

            if (zipEntry == null) {
                return null;
            }
        } while (zipEntry.isDirectory());

        InputStream stream = new CloseShieldInputStream(this.zipInputStream);
        return new NamedBinaryStream(zipEntry.getName(), stream);
    }

    @Override
    public void setBeforeFirstBinary() {
        if (this.isRead) {
            throw new IllegalStateException("ZipStreamAipBinaries can be only read once");
        }
    }

    @Override
    public INamedBinaryStream nextBinary() throws IOException {
        this.isRead = true;
        return takeBinary();
    }

    public void close() {
        IOUtils.closeQuietly(zipInputStream);
    }
}