Example usage for java.util.zip ZipInputStream ZipInputStream

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

Introduction

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

Prototype

public ZipInputStream(InputStream in) 

Source Link

Document

Creates a new ZIP input stream.

Usage

From source file:com.comcast.magicwand.spells.web.iexplore.IePhoenixDriver.java

private static void extract(File src, String dstDir) throws IOException {
    ZipInputStream zis = null;/*from  ww w.j ava  2  s.c  o m*/
    ZipEntry entry;

    try {
        zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(src)));

        while (null != (entry = zis.getNextEntry())) {
            File dst = Paths.get(dstDir, entry.getName()).toFile();
            FileOutputStream fos = new FileOutputStream(dst);

            try {
                IOUtils.copy(zis, fos);
                fos.close();
            } finally {
                IOUtils.closeQuietly(fos);
            }
        }

        zis.close();
    } finally {
        IOUtils.closeQuietly(zis);
    }
}

From source file:com.mindquarry.desktop.workspace.SVNTestBase.java

/**
 * Extracts the zip file <code>zipName</code> into the folder
 * <code>destinationPath</code>.
 *///from w w  w .ja  va  2s  .co  m
private void extractZip(String zipName, String destinationPath) throws IOException {
    File dest = new File(destinationPath);
    // delete if test has failed and extracted dir is still present
    FileUtils.deleteDirectory(dest);
    dest.mkdirs();

    byte[] buffer = new byte[1024];
    ZipEntry zipEntry;
    ZipInputStream zipInputStream = new ZipInputStream(
            new FileInputStream("src/test/resources/com/mindquarry/desktop/workspace/" + zipName));

    while (null != (zipEntry = zipInputStream.getNextEntry())) {

        File zippedFile = new File(destinationPath + zipEntry.getName());

        if (zipEntry.isDirectory()) {
            zippedFile.mkdirs();
        } else {
            // ensure the parent directory exists
            zippedFile.getParentFile().mkdirs();

            OutputStream fileOutStream = new FileOutputStream(zippedFile);
            transferBytes(zipInputStream, fileOutStream, buffer);
            fileOutStream.close();
        }
    }

    zipInputStream.close();
}

From source file:eu.scape_project.archiventory.container.ZipContainer.java

/**
 * Extracts a zip file specified by the zipFilePath to a directory specified by
 * destDirectory (will be created if does not exists)
 * @param containerFileName//from w ww  .  j  ava 2  s  .c o  m
 * @param destDirectory
 * @throws IOException
 */
public void unzip(String containerFileName, InputStream containerFileStream) throws IOException {
    extractDirectoryName = "/tmp/archiventory_" + RandomStringUtils.randomAlphabetic(10) + "/";
    File destDir = new File(extractDirectoryName);
    destDir.mkdir();
    String subDestDirStr = extractDirectoryName + containerFileName + "/";
    File subDestDir = new File(subDestDirStr);
    subDestDir.mkdir();
    ZipInputStream zipIn = new ZipInputStream(containerFileStream);
    ZipEntry entry = zipIn.getNextEntry();
    while (entry != null) {
        String filePath = subDestDirStr + entry.getName();
        if (!entry.isDirectory()) {
            extractFile(zipIn, filePath);
        } else {
            File dir = new File(filePath);
            dir.mkdir();
        }
        zipIn.closeEntry();
        entry = zipIn.getNextEntry();
    }
    zipIn.close();
}

From source file:com.microsoft.azure.hdinsight.util.HDInsightJobViewUtils.java

public static void unzip(String zipFilePath, String destDirectory) throws IOException {
    File destDir = new File(destDirectory);
    if (!destDir.exists()) {
        destDir.mkdir();/*from  w w  w .ja v  a 2 s . c o m*/
    }
    ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
    ZipEntry entry = zipIn.getNextEntry();
    while (entry != null) {
        String filePath = destDirectory + File.separator + entry.getName();
        if (!entry.isDirectory()) {
            extractFile(zipIn, filePath);
        } else {
            File dir = new File(filePath);
            dir.mkdir();
        }
        zipIn.closeEntry();
        entry = zipIn.getNextEntry();
    }
    zipIn.close();
}

From source file:be.fedict.eid.dss.document.asic.ASiCDSSDocumentService.java

@Override
public DocumentVisualization visualizeDocument(byte[] document, String language, List<MimeType> mimeTypes,
        String documentViewerServlet) throws Exception {
    ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(document));
    ZipEntry zipEntry;/*from  w w  w  .j  ava  2s  .c  o  m*/
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append("<html>");
    stringBuffer.append("<head>");
    stringBuffer.append("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">");
    stringBuffer.append("<title>Associated Signature Container</title>");
    stringBuffer.append("</head>");
    stringBuffer.append("<body>");
    stringBuffer.append("<h1>Associated Signature Container</h1>");
    while (null != (zipEntry = zipInputStream.getNextEntry())) {
        if (ASiCUtil.isSignatureZipEntry(zipEntry)) {
            continue;
        }
        String zipEntryName = zipEntry.getName();
        if ("META-INF/container.xml".equals(zipEntryName)) {
            continue;
        }
        if ("META-INF/manifest.xml".equals(zipEntryName)) {
            continue;
        }
        if ("META-INF/metadata.xml".equals(zipEntryName)) {
            continue;
        }
        if ("mimetype".equals(zipEntryName)) {
            continue;
        }
        if (zipEntryName.startsWith("META-INF/")) {
            if (zipEntryName.endsWith(".xml")) {
                if (zipEntryName.indexOf("signatures") != -1) {
                    continue;
                }
            }
        }
        stringBuffer.append("<p>" + zipEntryName + "</p>");
    }
    stringBuffer.append("</body></html>");

    return new DocumentVisualization("text/html;charset=utf-8", stringBuffer.toString().getBytes());
}

From source file:net.sf.mzmine.modules.rawdatamethods.rawdataimport.fileformats.ZipReadTask.java

/**
 * @see java.lang.Runnable#run()//from   ww w.  ja va2 s  .  co  m
 */
public void run() {

    // Update task status
    setStatus(TaskStatus.PROCESSING);
    logger.info("Started opening compressed file " + file);

    try {

        // Name of the uncompressed file
        String newName = file.getName();
        if (newName.toLowerCase().endsWith(".zip") || newName.toLowerCase().endsWith(".gz")) {
            newName = FilenameUtils.removeExtension(newName);
        }

        // Create decompressing stream
        FileInputStream fis = new FileInputStream(file);
        InputStream is;
        long decompressedSize = 0;
        switch (fileType) {
        case ZIP:
            ZipInputStream zis = new ZipInputStream(fis);
            ZipEntry entry = zis.getNextEntry();
            newName = entry.getName();
            decompressedSize = entry.getSize();
            if (decompressedSize < 0)
                decompressedSize = 0;
            is = zis;
            break;
        case GZIP:
            is = new GZIPInputStream(fis);
            decompressedSize = (long) (file.length() * 1.5); // Ballpark a
                                                             // decompressedFile
                                                             // size so the
                                                             // GUI can show
                                                             // progress
            if (decompressedSize < 0)
                decompressedSize = 0;
            break;
        default:
            setErrorMessage("Cannot decompress file type: " + fileType);
            setStatus(TaskStatus.ERROR);
            return;
        }

        tmpDir = Files.createTempDir();
        tmpFile = new File(tmpDir, newName);
        logger.finest("Decompressing to file " + tmpFile);
        tmpFile.deleteOnExit();
        tmpDir.deleteOnExit();
        FileOutputStream ous = new FileOutputStream(tmpFile);

        // Decompress the contents
        copy = new StreamCopy();
        copy.copy(is, ous, decompressedSize);

        // Close the streams
        is.close();
        ous.close();

        if (isCanceled())
            return;

        // Find the type of the decompressed file
        RawDataFileType fileType = RawDataFileTypeDetector.detectDataFileType(tmpFile);
        logger.finest("File " + tmpFile + " type detected as " + fileType);

        if (fileType == null) {
            setErrorMessage("Could not determine the file type of file " + newName);
            setStatus(TaskStatus.ERROR);
            return;
        }

        // Run the import module on the decompressed file
        RawDataFileWriter newMZmineFile = MZmineCore.createNewFile(newName);
        decompressedOpeningTask = RawDataImportModule.createOpeningTask(fileType, project, tmpFile,
                newMZmineFile);

        if (decompressedOpeningTask == null) {
            setErrorMessage("File type " + fileType + " of file " + newName + " is not supported.");
            setStatus(TaskStatus.ERROR);
            return;
        }

        // Run the underlying task
        decompressedOpeningTask.run();

        // Delete the temporary folder
        tmpFile.delete();
        tmpDir.delete();

        if (isCanceled())
            return;

    } catch (Throwable e) {
        logger.log(Level.SEVERE, "Could not open file " + file.getPath(), e);
        setErrorMessage(ExceptionUtils.exceptionToString(e));
        setStatus(TaskStatus.ERROR);
        return;
    }

    logger.info("Finished opening compressed file " + file);

    // Update task status
    setStatus(TaskStatus.FINISHED);

}

From source file:com.intuit.autumn.utils.PropertyFactory.java

private static Properties readZip(final Class base, final URL jar, final String property,
        final Properties properties) {
    try (ZipInputStream zip = new ZipInputStream(jar.openStream())) {
        for (ZipEntry ze = zip.getNextEntry(); ze != null; ze = zip.getNextEntry()) {
            if (ze.getName().equals(property)) {
                properties.load(zip);/*  ww  w .j  a  v a2s  . co m*/

                break;
            }
        }
    } catch (IOException e) {
        LOGGER.warn("unable to read jar: {}, property: {}, class: {}, cause: {}",
                new Object[] { jar, property, base.getSimpleName(), e.getMessage() }, e);
    }

    return properties;
}

From source file:com.liferay.sync.engine.document.library.handler.DownloadFilesHandler.java

@Override
protected void doHandleResponse(HttpResponse httpResponse) throws Exception {

    long syncAccountId = getSyncAccountId();

    final Session session = SessionManager.getSession(syncAccountId);

    Header header = httpResponse.getFirstHeader("Sync-JWT");

    if (header != null) {
        session.addHeader("Sync-JWT", header.getValue());
    }//w w  w  .j av a  2  s  .  c o m

    Map<String, DownloadFileHandler> handlers = (Map<String, DownloadFileHandler>) getParameterValue(
            "handlers");

    InputStream inputStream = null;

    try {
        HttpEntity httpEntity = httpResponse.getEntity();

        inputStream = new CountingInputStream(httpEntity.getContent()) {

            @Override
            protected synchronized void afterRead(int n) {
                session.incrementDownloadedBytes(n);

                super.afterRead(n);
            }

        };

        inputStream = new RateLimitedInputStream(inputStream, syncAccountId);

        ZipInputStream zipInputStream = new ZipInputStream(inputStream);

        ZipEntry zipEntry = null;

        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            String zipEntryName = zipEntry.getName();

            if (zipEntryName.equals("errors.json")) {
                JsonNode rootJsonNode = JSONUtil.readTree(new CloseShieldInputStream(zipInputStream));

                Iterator<Map.Entry<String, JsonNode>> fields = rootJsonNode.fields();

                while (fields.hasNext()) {
                    Map.Entry<String, JsonNode> field = fields.next();

                    Handler<Void> handler = handlers.remove(field.getKey());

                    JsonNode valueJsonNode = field.getValue();

                    JsonNode exceptionJsonNode = valueJsonNode.get("exception");

                    handler.handlePortalException(exceptionJsonNode.textValue());
                }

                break;
            }

            DownloadFileHandler downloadFileHandler = handlers.get(zipEntryName);

            if (downloadFileHandler == null) {
                continue;
            }

            SyncFile syncFile = (SyncFile) downloadFileHandler.getParameterValue("syncFile");

            if (downloadFileHandler.isUnsynced(syncFile)) {
                handlers.remove(zipEntryName);

                continue;
            }

            if (_logger.isTraceEnabled()) {
                _logger.trace("Handling response {} file path {}", DownloadFileHandler.class.getSimpleName(),
                        syncFile.getFilePathName());
            }

            try {
                downloadFileHandler.copyFile(syncFile, Paths.get(syncFile.getFilePathName()),
                        new CloseShieldInputStream(zipInputStream), false);
            } catch (Exception e) {
                if (!isEventCancelled()) {
                    _logger.error(e.getMessage(), e);

                    downloadFileHandler.removeEvent();

                    FileEventUtil.downloadFile(getSyncAccountId(), syncFile, false);
                }
            } finally {
                handlers.remove(zipEntryName);

                downloadFileHandler.removeEvent();
            }
        }
    } catch (Exception e) {
        if (!isEventCancelled()) {
            _logger.error(e.getMessage(), e);

            retryEvent();
        }
    } finally {
        StreamUtil.cleanUp(inputStream);
    }
}

From source file:com.marklogic.contentpump.ArchiveRecordReader.java

protected void initStream(InputSplit inSplit) throws IOException {
    setFile(((FileSplit) inSplit).getPath());
    int index = file.toUri().getPath().lastIndexOf(EXTENSION);
    String subStr = file.toUri().getPath().substring(0, index);
    index = subStr.lastIndexOf('-');
    String typeStr = subStr.substring(index + 1, subStr.length());
    type = ContentType.valueOf(typeStr);
    value = new DatabaseDocumentWithMeta();
    FSDataInputStream fileIn = fs.open(file);
    zipIn = new ZipInputStream(fileIn);
}

From source file:com.thoughtworks.go.plugin.infra.FelixGoPluginOSGiFrameworkIntegrationTest.java

@Before
public void setUp() throws Exception {
    registry = new DefaultPluginRegistry();
    systemEnvironment = new SystemEnvironment();
    pluginOSGiFramework = new FelixGoPluginOSGiFramework(registry, systemEnvironment) {
        @Override/* w  w  w  . ja va 2s .co  m*/
        protected HashMap<String, String> generateOSGiFrameworkConfig() {
            HashMap<String, String> config = super.generateOSGiFrameworkConfig();
            config.put(FelixConstants.RESOLVER_PARALLELISM, "1");
            return config;
        }
    };
    pluginOSGiFramework.start();

    try (ZipInputStream zippedOSGiBundleFile = new ZipInputStream(
            FileUtils.openInputStream(pathOfFileInDefaultFiles("descriptor-aware-test-plugin.osgi.jar")))) {
        descriptorBundleDir = explodeBundleIntoDirectory(zippedOSGiBundleFile, "descriptor-plugin-bundle-dir");
    }

    try (ZipInputStream zippedOSGiBundleFile = new ZipInputStream(FileUtils.openInputStream(
            pathOfFileInDefaultFiles("error-generating-descriptor-aware-test-plugin.osgi.jar")))) {
        errorGeneratingDescriptorBundleDir = explodeBundleIntoDirectory(zippedOSGiBundleFile,
                "error-generating-descriptor-plugin-bundle-dir");
    }

    try (ZipInputStream zippedOSGiBundleFile = new ZipInputStream(FileUtils
            .openInputStream(pathOfFileInDefaultFiles("exception-throwing-at-load-plugin.osgi.jar")))) {
        exceptionThrowingAtLoadDescriptorBundleDir = explodeBundleIntoDirectory(zippedOSGiBundleFile,
                "exception-throwing-at-load-plugin-bundle-dir");
    }

    try (ZipInputStream zippedOSGiBundleFile = new ZipInputStream(FileUtils
            .openInputStream(pathOfFileInDefaultFiles("valid-plugin-with-multiple-extensions.osgi.jar")))) {
        validMultipleExtensionPluginBundleDir = explodeBundleIntoDirectory(zippedOSGiBundleFile,
                "valid-plugin-with-multiple-extensions");
    }
    try (ZipInputStream zippedOSGiBundleFile = new ZipInputStream(FileUtils.openInputStream(
            pathOfFileInDefaultFiles("dumb.plugin.that.responds.with.classloader.name.osgi.jar")))) {
        pluginToTestClassloadPluginBundleDir = explodeBundleIntoDirectory(zippedOSGiBundleFile,
                "plugin-to-test-classloader");
    }
}