Example usage for java.util.zip ZipInputStream closeEntry

List of usage examples for java.util.zip ZipInputStream closeEntry

Introduction

In this page you can find the example usage for java.util.zip ZipInputStream closeEntry.

Prototype

public void closeEntry() throws IOException 

Source Link

Document

Closes the current ZIP entry and positions the stream for reading the next entry.

Usage

From source file:org.pentaho.platform.plugin.services.importer.MetaStoreImportHandler.java

@Override
public void importFile(IPlatformImportBundle bundle) throws PlatformImportException, DomainIdNullException,
        DomainAlreadyExistsException, DomainStorageException, IOException {

    InputStream inputStream = bundle.getInputStream();
    Path path = Files.createTempDirectory(METASTORE);
    path.toFile().deleteOnExit();/*from ww  w.  j av  a2  s .c o m*/

    // get the zipped metastore from the export bundle
    ZipInputStream zis = new ZipInputStream(inputStream);
    ZipEntry entry;
    while ((entry = zis.getNextEntry()) != null) {
        try {
            String filePath = path.toString() + File.separator + entry.getName();
            if (entry.isDirectory()) {
                File dir = new File(filePath);
                dir.mkdir();
            } else {
                File file = new File(filePath);
                file.getParentFile().mkdirs();
                FileOutputStream fos = new FileOutputStream(filePath);
                IOUtils.copy(zis, fos);
                IOUtils.closeQuietly(fos);
            }
        } finally {
            zis.closeEntry();
        }
    }
    IOUtils.closeQuietly(zis);

    // get a hold of the metastore to import into
    IMetaStore metastore = getRepoMetaStore();
    if (metastore != null) {
        // copy the exported metastore to where it needs to go
        try {
            if (tmpXmlMetaStore == null) {
                tmpXmlMetaStore = new XmlMetaStore(path.toString());
            } else {
                // we are re-using an existing object, make sure the root folder is pointed at the new location on disk
                tmpXmlMetaStore.setRootFolder(path.toString() + File.separator + METASTORE);
            }
            tmpXmlMetaStore.setName(bundle.getName());

            String desc = bundle.getProperty("description") == null ? null
                    : bundle.getProperty("description").toString();

            tmpXmlMetaStore.setDescription(desc);

            MetaStoreUtil.copy(tmpXmlMetaStore, metastore, bundle.overwriteInRepository());

        } catch (MetaStoreException e) {
            log.error("Could not restore the MetaStore");
            log.debug("Error restoring the MetaStore", e);
        }
    }

}

From source file:org.apache.hadoop.hbase.util.MigrationTest.java

private void unzip(ZipInputStream zip, FileSystem dfs, Path rootDir) throws IOException {
    ZipEntry e = null;/*from   w  w  w .j a  v  a 2  s  .com*/
    while ((e = zip.getNextEntry()) != null) {
        if (e.isDirectory()) {
            dfs.mkdirs(new Path(rootDir, e.getName()));
        } else {
            FSDataOutputStream out = dfs.create(new Path(rootDir, e.getName()));
            byte[] buffer = new byte[4096];
            int len;
            do {
                len = zip.read(buffer);
                if (len > 0) {
                    out.write(buffer, 0, len);
                }
            } while (len > 0);
            out.close();
        }
        zip.closeEntry();
    }
}

From source file:org.fusesource.cloudmix.agent.jbi.JBIInstallerAgent.java

private void extractZipEntry(ZipInputStream zip, OutputStream os) throws IOException {
    final byte[] buffer = new byte[FileUtils.BUFFER_SIZE];

    try {//w  ww. ja  va  2  s  .co  m
        long total = 0;
        int n = zip.read(buffer);
        while (n != -1) {
            total += n;
            os.write(buffer, 0, n);
            n = zip.read(buffer);
        }
        LOGGER.info("Copied " + total + " bytes");
    } finally {
        zip.closeEntry();
        os.close();
    }
}

From source file:org.niord.core.batch.BatchSetService.java

/** Called to start a batch set execution from a zipped batch set archive **/
@SuppressWarnings("all")
public void extractAndExecuteBatchSetArchive(InputStream inputStream, StringBuilder txt) throws Exception {

    // Create a temporary destination folder
    String tempArchiveRepoPath = repositoryService.getNewTempDir().getPath();
    Path folder = repositoryService.getRepoRoot().resolve(tempArchiveRepoPath);
    Files.createDirectories(folder);

    // Unzip the archive
    log.info("Unzipping batch set zip archive to folder " + folder);
    //get the zip file content
    ZipInputStream zis = new ZipInputStream(inputStream);
    ZipEntry entry = zis.getNextEntry();
    while (entry != null) {
        File entryDestination = new File(folder.toFile(), entry.getName());
        if (entry.isDirectory()) {
            entryDestination.mkdirs();/*from  ww w . jav  a  2  s.co m*/
        } else {
            entryDestination.getParentFile().mkdirs();
            try (OutputStream out = new FileOutputStream(entryDestination)) {
                IOUtils.copy(zis, out);
            }
        }
        entry = zis.getNextEntry();
    }
    zis.closeEntry();

    // Execute the batch set
    BatchSetSpecification batchSetSpec = readBatchSetFromFolder(folder);
    executeBatchSet(batchSetSpec, txt);
}

From source file:org.jahia.utils.zip.JahiaArchiveFileHandler.java

/**
 * Extract an entry in a gived folder. If this entry is a directory,
 * all its contents are extracted too.//from www  .jav a 2 s.c  o m
 *
 * @param entryName, the name of an entry in the jar
 * @param destPath,  the path to the destination folder
 */
public void extractEntry(String entryName, String destPath) throws JahiaException {

    try {

        ZipEntry entry = m_JarFile.getEntry(entryName);

        if (entry == null) {
            StringBuilder strBuf = new StringBuilder(1024);
            strBuf.append(" extractEntry(), cannot find entry ");
            strBuf.append(entryName);
            strBuf.append(" in the jar file ");

            throw new JahiaException(CLASS_NAME, strBuf.toString(), JahiaException.SERVICE_ERROR,
                    JahiaException.ERROR_SEVERITY);

        }

        File destDir = new File(destPath);
        if (destDir == null || !destDir.isDirectory() || !destDir.canWrite()) {

            logger.error(" cannot access to the destination dir " + destPath);

            throw new JahiaException(CLASS_NAME, " cannot access to the destination dir ",
                    JahiaException.SERVICE_ERROR, JahiaException.ERROR_SEVERITY);
        }

        String path = null;

        FileInputStream fis = new FileInputStream(m_FilePath);
        BufferedInputStream bis = new BufferedInputStream(fis);
        ZipInputStream zis = new ZipInputStream(bis);
        ZipFile zf = new ZipFile(m_FilePath);
        ZipEntry ze = null;
        String zeName = null;

        while ((ze = zis.getNextEntry()) != null && !ze.getName().equalsIgnoreCase(entryName)) {
            // loop until the requested entry
            zis.closeEntry();
        }

        try {
            if (ze != null) {
                if (ze.isDirectory()) {

                    while (ze != null) {
                        zeName = ze.getName();
                        path = destPath + File.separator + genPathFile(zeName);
                        File fo = new File(path);
                        if (ze.isDirectory()) {
                            fo.mkdirs();
                        } else {

                            FileOutputStream outs = new FileOutputStream(fo);
                            copyStream(zis, outs);
                            //outs.flush();
                            //outs.close();
                        }
                        zis.closeEntry();
                        ze = zis.getNextEntry();

                    }
                } else {

                    zeName = ze.getName();
                    path = destPath + File.separator + genPathFile(zeName);

                    File fo = new File(path);
                    FileOutputStream outs = new FileOutputStream(fo);
                    copyStream(zis, outs);
                    //outs.flush();
                    //outs.close();
                }
            }
        } finally {
            // Important !!!
            zf.close();
            fis.close();
            zis.close();
            bis.close();
        }

    } catch (IOException ioe) {

        logger.error(" fail unzipping " + ioe.getMessage(), ioe);

        throw new JahiaException(CLASS_NAME, "faile processing unzip", JahiaException.SERVICE_ERROR,
                JahiaException.ERROR_SEVERITY, ioe);

    }

}

From source file:org.n52.movingcode.runtime.codepackage.ZippedPackage.java

@Override
public boolean containsFileInWorkspace(String relativePath) {
    if (relativePath.startsWith("./") || relativePath.startsWith(".\\")) {
        relativePath = relativePath.substring(2);
    }// ww  w .  jav a2 s .  c o  m
    if (relativePath.startsWith("/") || relativePath.startsWith("\\")) {
        relativePath = relativePath.substring(1);
    }

    // zipFile and zip url MUST not be null at the same time
    assert (!((zipFile == null) && (zipURL == null)));
    String archiveName = null;

    String wsName = getDescription().getPackageDescription().getWorkspace().getWorkspaceRoot();
    if (wsName.startsWith("./") || wsName.startsWith(".\\")) {
        wsName = wsName.substring(2);
    }

    String searchEntry = wsName + "/" + relativePath;

    boolean retval = false;
    try {

        ZipInputStream zis = null;
        if (zipFile != null) {
            zis = new ZipInputStream(new FileInputStream(zipFile));
            archiveName = zipFile.getAbsolutePath();
        } else if (zipURL != null) {
            zis = new ZipInputStream(zipURL.openConnection().getInputStream());
            archiveName = zipURL.toString();
        }

        ZipEntry entry;

        while ((entry = zis.getNextEntry()) != null) {
            if (samePath(entry.getName(), searchEntry)) {
                retval = true;
                zis.closeEntry();
                break;
            } else {
                zis.closeEntry();
            }
        }

        zis.close();

    } catch (ZipException e) {
        logger.error("Error! Could read from archive: " + archiveName);
    } catch (IOException e) {
        logger.error("Error! Could not open archive: " + archiveName);
    }

    return retval;
}

From source file:org.geowebcache.sqlite.OperationsRest.java

private File unzip(ZipInputStream zipInputStream, ZipEntry zipEntry, File workingDirectory) throws Exception {
    // output directory for our zip file content
    File outputDirectory = new File(workingDirectory, UUID.randomUUID().toString());
    outputDirectory.mkdir();/*from   w ww.j  a  v a2s .  c o  m*/
    // unzipping all zip file entries
    while (zipEntry != null) {
        File outputFile = new File(outputDirectory, zipEntry.getName());
        if (zipEntry.isDirectory()) {
            // this entry is a directory, so we only need to create the directory
            outputFile.mkdir();
        } else {
            // is a file we need to extract is content
            extractFile(zipInputStream, outputFile);
        }
        zipInputStream.closeEntry();
        zipEntry = zipInputStream.getNextEntry();
    }
    return outputDirectory;
}

From source file:org.eclipse.swordfish.p2.internal.deploy.server.RepositoryManager.java

private final File unzip(String iu, InputStream repoZipStream) throws IOException {
    File tempDir = new File(System.getProperty("java.io.tmpdir"), iu + "_" + new java.util.Random().nextInt());
    tempDir.mkdir();//from   w  w w. j  a v a2 s .com
    tempDir.deleteOnExit();

    ZipInputStream zin = new ZipInputStream(repoZipStream);
    ZipEntry ze = null;
    int extracted = 0;

    while ((ze = zin.getNextEntry()) != null) {
        File outFile = new File(tempDir.getCanonicalPath(), ze.getName());

        if (ze.isDirectory()) {
            if (!outFile.exists()) {
                outFile.mkdir();
                outFile.deleteOnExit();
                extracted++;
            }
        } else {
            FileOutputStream fout = new FileOutputStream(outFile);
            outFile.deleteOnExit();

            for (int c = zin.read(); c != -1; c = zin.read()) {
                fout.write(c);
            }
            fout.close();
            extracted++;
        }

        zin.closeEntry();
    }

    zin.close();

    if (extracted == 0) {
        throw new IOException("Empty or invalid archive.");
    }
    return tempDir;
}

From source file:org.exoplatform.services.cms.impl.Utils.java

/**
 * get data from the version history file
 *
 * @param importHistorySourceStream// w w w .j  ava  2  s  .  c  o  m
 * @return
 * @throws Exception
 */
public static Map<String, String> getMapImportHistory(InputStream importHistorySourceStream) throws Exception {
    ZipInputStream zipInputStream = new ZipInputStream(importHistorySourceStream);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    byte[] data = new byte[1024];
    ZipEntry entry = zipInputStream.getNextEntry();
    Map<String, String> mapHistoryValue = new HashMap<String, String>();
    while (entry != null) {
        int available = -1;
        if (entry.getName().equals(MAPPING_FILE)) {
            while ((available = zipInputStream.read(data, 0, 1024)) > -1) {
                out.write(data, 0, available);
            }
            InputStream inputStream = new ByteArrayInputStream(out.toByteArray());
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            String strLine;
            // Read File Line By Line
            while ((strLine = br.readLine()) != null) {
                // Put the history information into list
                if (strLine.indexOf("=") > -1) {
                    mapHistoryValue.put(strLine.split("=")[0], strLine.split("=")[1]);
                }
            }
            // Close the input stream
            inputStream.close();
            zipInputStream.closeEntry();
            break;
        }
        entry = zipInputStream.getNextEntry();
    }
    out.close();
    zipInputStream.close();
    return mapHistoryValue;
}

From source file:util.FileArchiver.java

/**
 * Extract the given input zip contents into the specified output directory.
 *
 * @param inputZip  The input zip file [if prefix is ResourceFile.HDFS_PREFIX, path in HDFS]
 * @param outputDir  The output path to extract zip contents to. [if prefix is ResourceFile.HDFS_PREFIX, path in HDFS]
 * @throws IOException//from  w  w w . j a v a2 s. c  o m
 */
public void extract(String inputZip, String outputDir) throws IOException {
    FileSystem localFS = FileSystem.getLocal(conf);
    FileSystem hdfs = FileSystem.get(conf);

    FileSystem outFS = localFS;
    if (ResourceFile.isHDFSFile(outputDir)) {
        outFS = hdfs;
        outputDir = ResourceFile.hdfsFileName(outputDir);
        LOG.info("Will extract to HDFS directory");
    }

    Path outputPath = new Path(outputDir);
    outFS.mkdirs(outputPath);

    InputStream is = ResourceFile.getInputStream(inputZip);
    if (is == null)
        throw new IOException("Unable to open input stream for zip (" + inputZip + ")");

    // Loop over zip entries and create output file for each
    OutputStream os = null;
    ZipInputStream zis = null;
    ZipEntry zipEntry = null;
    try {
        zis = new ZipInputStream(is);
        while ((zipEntry = zis.getNextEntry()) != null) {
            Path destPath = new Path(outputPath, zipEntry.getName());
            os = outFS.create(destPath, true);

            byte[] data = read(zipEntry.getName(), zis);
            os.write(data);
            os.flush();

            LOG.info("Extracted entry (" + zipEntry.getName() + ") to (" + destPath.getName() + ")");

            // Cleanup handles
            zis.closeEntry();
            IOUtils.closeQuietly(os);
        }
        zis.close();
    } catch (IOException e) {

    } finally {
        IOUtils.closeQuietly(zis);
        IOUtils.closeQuietly(os);
        IOUtils.closeQuietly(is);
    }
}