Example usage for org.apache.commons.compress.archivers.zip ZipFile getInputStream

List of usage examples for org.apache.commons.compress.archivers.zip ZipFile getInputStream

Introduction

In this page you can find the example usage for org.apache.commons.compress.archivers.zip ZipFile getInputStream.

Prototype

public InputStream getInputStream(ZipArchiveEntry ze) throws IOException, ZipException 

Source Link

Document

Returns an InputStream for reading the contents of the given entry.

Usage

From source file:io.wcm.maven.plugins.contentpackage.unpacker.ContentUnpacker.java

private void unpackEntry(ZipFile zipFile, ZipArchiveEntry entry, File outputDirectory)
        throws IOException, MojoExecutionException {
    if (entry.isDirectory()) {
        File directory = FileUtils.getFile(outputDirectory, entry.getName());
        directory.mkdirs();//from  w  ww.ja  va2s. c o  m
    } else {
        InputStream entryStream = null;
        FileOutputStream fos = null;
        try {
            entryStream = zipFile.getInputStream(entry);
            File outputFile = FileUtils.getFile(outputDirectory, entry.getName());
            if (outputFile.exists()) {
                outputFile.delete();
            }
            File directory = outputFile.getParentFile();
            directory.mkdirs();
            fos = new FileOutputStream(outputFile);
            if (applyXmlExcludes(entry.getName())) {
                // write file with XML filtering
                try {
                    writeXmlWithExcludes(entryStream, fos);
                } catch (JDOMException ex) {
                    throw new MojoExecutionException("Unable to parse XML file: " + entry.getName(), ex);
                }
            } else {
                // write file directly without XML filtering
                IOUtils.copy(entryStream, fos);
            }
        } finally {
            IOUtils.closeQuietly(entryStream);
            IOUtils.closeQuietly(fos);
        }
    }
}

From source file:cn.vlabs.clb.server.utils.UnCompress.java

public void unzip(File file) {
    ZipFile zipfile = null;
    try {//from w w w.j  a  va2 s  .c  o m
        if (encoding == null)
            zipfile = new ZipFile(file);
        else
            zipfile = new ZipFile(file, encoding);
        Enumeration<ZipArchiveEntry> iter = zipfile.getEntries();
        while (iter.hasMoreElements()) {
            ZipArchiveEntry entry = iter.nextElement();
            if (!entry.isDirectory()) {
                InputStream entryis = null;
                try {
                    entryis = zipfile.getInputStream(entry);
                    listener.onNewEntry(new ZipEntryAdapter(entry, zipfile));
                } finally {
                    IOUtils.closeQuietly(entryis);
                }
            }
        }
    } catch (ZipException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error("file not found " + e.getMessage(), e);
    } finally {
        if (zipfile != null) {
            try {
                zipfile.close();
            } catch (IOException e) {
                log.error(e);
            }
        }
    }
}

From source file:at.spardat.xma.xdelta.test.JarDeltaJarPatcherTest.java

/**
 * Converts the given zip entry to a byte array.
 *
 * @author S3460//from ww  w  .  j  a v  a 2s.  c om
 * @param zipfile the zipfile
 * @param entry the entry
 * @return the byte[]
 * @throws Exception the exception
 */
private byte[] toBytes(ZipFile zipfile, ZipArchiveEntry entry) throws Exception {
    int entrySize = (int) entry.getSize();
    byte[] bytes = new byte[entrySize];
    InputStream entryStream = zipfile.getInputStream(entry);
    for (int erg = entryStream.read(bytes); erg < bytes.length; erg += entryStream.read(bytes, erg,
            bytes.length - erg))
        ;
    return bytes;
}

From source file:at.spardat.xma.xdelta.test.JarDeltaJarPatcherTest.java

/**
 * Tests JarDelta and JarPatcher on two identical files.
 *
 * @throws Exception the exception//w  w  w .j  a v  a  2  s  .  c  o m
 */
@Test
public void testJarPatcherIdentFile() throws Exception {
    ZipFile originalZip = makeSourceZipFile(sourceFile);
    new JarDelta().computeDelta(sourceFile.getAbsolutePath(), sourceFile.getAbsolutePath(), originalZip,
            originalZip, new ZipArchiveOutputStream(new FileOutputStream(patchFile)));
    ZipFile patch = new ZipFile(patchFile);
    ZipArchiveEntry listEntry = patch.getEntry("META-INF/file.list");
    if (listEntry == null) {
        patch.close();
        throw new IOException("Invalid patch - list entry 'META-INF/file.list' not found");
    }
    BufferedReader patchlist = new BufferedReader(new InputStreamReader(patch.getInputStream(listEntry)));
    String next = patchlist.readLine();
    String sourceName = next;
    next = patchlist.readLine();
    ZipFile source = new ZipFile(sourceFile);
    new JarPatcher(patchFile.getName(), sourceName).applyDelta(patch, source,
            new ZipArchiveOutputStream(new FileOutputStream(resultFile)), patchlist);
    compareFiles(new ZipFile(sourceFile), new ZipFile(resultFile));
}

From source file:at.spardat.xma.xdelta.test.JarDeltaJarPatcherTest.java

/**
 * Run jar patcher.//from   w  ww  . j  a va  2s.  co  m
 *
 * @param originalName the original name
 * @param targetName the target name
 * @param originalZip the original zip
 * @param newZip the new zip
 * @param comparefiles the comparefiles
 * @throws Exception the exception
 */
private void runJarPatcher(String originalName, String targetName, ZipFile originalZip, ZipFile newZip,
        boolean comparefiles) throws Exception {
    try (ZipArchiveOutputStream output = new ZipArchiveOutputStream(new FileOutputStream(patchFile))) {
        new JarDelta().computeDelta(originalName, targetName, originalZip, newZip, output);
    }
    ZipFile patch = new ZipFile(patchFile);
    ZipArchiveEntry listEntry = patch.getEntry("META-INF/file.list");
    if (listEntry == null) {
        patch.close();
        throw new IOException("Invalid patch - list entry 'META-INF/file.list' not found");
    }
    BufferedReader patchlist = new BufferedReader(new InputStreamReader(patch.getInputStream(listEntry)));
    String next = patchlist.readLine();
    String sourceName = next;
    next = patchlist.readLine();
    new JarPatcher(patchFile.getName(), sourceName).applyDelta(patch, new ZipFile(originalName),
            new ZipArchiveOutputStream(new FileOutputStream(resultFile)), patchlist);
    if (comparefiles) {
        compareFiles(new ZipFile(targetName), new ZipFile(resultFile));
    }
}

From source file:io.selendroid.builder.SelendroidServerBuilder.java

File createAndAddCustomizedAndroidManifestToSelendroidServer()
        throws IOException, ShellCommandException, AndroidSdkException {
    String targetPackageName = applicationUnderTest.getBasePackage();
    File tempdir = new File(FileUtils.getTempDirectoryPath() + File.separatorChar + targetPackageName
            + System.currentTimeMillis());

    if (!tempdir.exists()) {
        tempdir.mkdirs();/*from   ww w  .j  av a 2s. c  om*/
    }

    File customizedManifest = new File(tempdir, "AndroidManifest.xml");
    log.info("Adding target package '" + targetPackageName + "' to " + customizedManifest.getAbsolutePath());

    // add target package
    InputStream inputStream = getResourceAsStream(selendroidApplicationXmlTemplate);
    if (inputStream == null) {
        throw new SelendroidException("AndroidApplication.xml template file was not found.");
    }
    String content = IOUtils.toString(inputStream, Charset.defaultCharset().displayName());

    // find the first occurance of "package" and appending the targetpackagename to begining
    int i = content.toLowerCase().indexOf("package");
    int cnt = 0;
    for (; i < content.length(); i++) {
        if (content.charAt(i) == '\"') {
            cnt++;
        }
        if (cnt == 2) {
            break;
        }
    }
    content = content.substring(0, i) + "." + targetPackageName + content.substring(i);
    log.info("Final Manifest File:\n" + content);
    content = content.replaceAll(SELENDROID_TEST_APP_PACKAGE, targetPackageName);
    // Seems like this needs to be done
    if (content.contains(ICON)) {
        content = content.replaceAll(ICON, "");
    }

    OutputStream outputStream = new FileOutputStream(customizedManifest);
    IOUtils.write(content, outputStream, Charset.defaultCharset().displayName());
    IOUtils.closeQuietly(inputStream);
    IOUtils.closeQuietly(outputStream);

    // adding the xml to an empty apk
    CommandLine createManifestApk = new CommandLine(AndroidSdk.aapt());

    createManifestApk.addArgument("package", false);
    createManifestApk.addArgument("-M", false);
    createManifestApk.addArgument(customizedManifest.getAbsolutePath(), false);
    createManifestApk.addArgument("-I", false);
    createManifestApk.addArgument(AndroidSdk.androidJar(), false);
    createManifestApk.addArgument("-F", false);
    createManifestApk.addArgument(tempdir.getAbsolutePath() + File.separatorChar + "manifest.apk", false);
    createManifestApk.addArgument("-f", false);
    log.info(ShellCommand.exec(createManifestApk, 20000L));

    ZipFile manifestApk = new ZipFile(
            new File(tempdir.getAbsolutePath() + File.separatorChar + "manifest.apk"));
    ZipArchiveEntry binaryManifestXml = manifestApk.getEntry("AndroidManifest.xml");

    File finalSelendroidServerFile = new File(tempdir.getAbsolutePath() + "selendroid-server.apk");
    ZipArchiveOutputStream finalSelendroidServer = new ZipArchiveOutputStream(finalSelendroidServerFile);
    finalSelendroidServer.putArchiveEntry(binaryManifestXml);
    IOUtils.copy(manifestApk.getInputStream(binaryManifestXml), finalSelendroidServer);

    ZipFile selendroidPrebuildApk = new ZipFile(selendroidServer.getAbsolutePath());
    Enumeration<ZipArchiveEntry> entries = selendroidPrebuildApk.getEntries();
    for (; entries.hasMoreElements();) {
        ZipArchiveEntry dd = entries.nextElement();
        finalSelendroidServer.putArchiveEntry(dd);

        IOUtils.copy(selendroidPrebuildApk.getInputStream(dd), finalSelendroidServer);
    }

    finalSelendroidServer.closeArchiveEntry();
    finalSelendroidServer.close();
    manifestApk.close();
    log.info("file: " + finalSelendroidServerFile.getAbsolutePath());
    return finalSelendroidServerFile;
}

From source file:io.selendroid.standalone.builder.SelendroidServerBuilder.java

File createAndAddCustomizedAndroidManifestToSelendroidServer()
        throws IOException, ShellCommandException, AndroidSdkException {
    String targetPackageName = applicationUnderTest.getBasePackage();

    File tmpDir = Files.createTempDir();
    if (deleteTmpFiles()) {
        tmpDir.deleteOnExit();//from w w w.j  a v  a 2 s.  c om
    }

    File customizedManifest = new File(tmpDir, "AndroidManifest.xml");
    if (deleteTmpFiles()) {
        customizedManifest.deleteOnExit();
    }
    log.info("Adding target package '" + targetPackageName + "' to " + customizedManifest.getAbsolutePath());

    // add target package
    InputStream inputStream = getResourceAsStream(selendroidApplicationXmlTemplate);
    if (inputStream == null) {
        throw new SelendroidException("AndroidApplication.xml template file was not found.");
    }
    String content = IOUtils.toString(inputStream, Charset.defaultCharset().displayName());

    // find the first occurance of "package" and appending the targetpackagename to begining
    int i = content.toLowerCase().indexOf("package");
    int cnt = 0;
    for (; i < content.length(); i++) {
        if (content.charAt(i) == '\"') {
            cnt++;
        }
        if (cnt == 2) {
            break;
        }
    }
    content = content.substring(0, i) + "." + targetPackageName + content.substring(i);
    log.info("Final Manifest File:\n" + content);
    content = content.replaceAll(SELENDROID_TEST_APP_PACKAGE, targetPackageName);
    // Seems like this needs to be done
    if (content.contains(ICON)) {
        content = content.replaceAll(ICON, "");
    }

    OutputStream outputStream = new FileOutputStream(customizedManifest);
    IOUtils.write(content, outputStream, Charset.defaultCharset().displayName());
    IOUtils.closeQuietly(inputStream);
    IOUtils.closeQuietly(outputStream);

    // adding the xml to an empty apk
    CommandLine createManifestApk = new CommandLine(AndroidSdk.aapt());

    File manifestApkFile = File.createTempFile("manifest", ".apk");
    if (deleteTmpFiles()) {
        manifestApkFile.deleteOnExit();
    }

    createManifestApk.addArgument("package", false);
    createManifestApk.addArgument("-M", false);
    createManifestApk.addArgument(customizedManifest.getAbsolutePath(), false);
    createManifestApk.addArgument("-I", false);
    createManifestApk.addArgument(AndroidSdk.androidJar(), false);
    createManifestApk.addArgument("-F", false);
    createManifestApk.addArgument(manifestApkFile.getAbsolutePath(), false);
    createManifestApk.addArgument("-f", false);
    log.info(ShellCommand.exec(createManifestApk, 20000L));

    ZipFile manifestApk = new ZipFile(manifestApkFile);
    ZipArchiveEntry binaryManifestXml = manifestApk.getEntry("AndroidManifest.xml");

    File finalSelendroidServerFile = File.createTempFile("selendroid-server", ".apk");
    if (deleteTmpFiles()) {
        finalSelendroidServerFile.deleteOnExit();
    }

    ZipArchiveOutputStream finalSelendroidServer = new ZipArchiveOutputStream(finalSelendroidServerFile);
    finalSelendroidServer.putArchiveEntry(binaryManifestXml);
    IOUtils.copy(manifestApk.getInputStream(binaryManifestXml), finalSelendroidServer);

    ZipFile selendroidPrebuildApk = new ZipFile(selendroidServer.getAbsolutePath());
    Enumeration<ZipArchiveEntry> entries = selendroidPrebuildApk.getEntries();
    for (; entries.hasMoreElements();) {
        ZipArchiveEntry dd = entries.nextElement();
        finalSelendroidServer.putArchiveEntry(dd);

        IOUtils.copy(selendroidPrebuildApk.getInputStream(dd), finalSelendroidServer);
    }

    finalSelendroidServer.closeArchiveEntry();
    finalSelendroidServer.close();
    manifestApk.close();
    log.info("file: " + finalSelendroidServerFile.getAbsolutePath());
    return finalSelendroidServerFile;
}

From source file:autoupdater.FileDAO.java

/**
 * Unzips a zip archive.//from ww  w  .j  a  v  a 2  s. c  om
 *
 * @param zip the zipfile to unzip
 * @param fileLocationOnDiskToDownloadTo the folder to unzip in
 * @return true if successful
 * @throws IOException
 */
public boolean unzipFile(ZipFile zip, File fileLocationOnDiskToDownloadTo) throws IOException {
    FileOutputStream dest = null;
    InputStream inStream = null;
    Enumeration<ZipArchiveEntry> zipFileEnum = zip.getEntries();
    while (zipFileEnum.hasMoreElements()) {
        ZipArchiveEntry entry = zipFileEnum.nextElement();
        File destFile = new File(fileLocationOnDiskToDownloadTo, entry.getName());
        if (!destFile.getParentFile().exists()) {
            if (!destFile.getParentFile().mkdirs()) {
                throw new IOException("could not create the folders to unzip in");
            }
        }
        if (!entry.isDirectory()) {
            try {
                dest = new FileOutputStream(destFile);
                inStream = zip.getInputStream(entry);
                IOUtils.copyLarge(inStream, dest);
            } finally {
                if (dest != null) {
                    dest.close();
                }
                if (inStream != null) {
                    inStream.close();
                }
            }
        } else {
            if (!destFile.exists()) {
                if (!destFile.mkdirs()) {
                    throw new IOException("could not create folders to unzip file");
                }
            }
        }
    }
    zip.close();
    return true;
}

From source file:at.spardat.xma.xdelta.JarDelta.java

/**
 * Find best source.//  w ww  . j ava  2s  . c  o  m
 *
 * @param source the source
 * @param target the target
 * @param targetEntry the target entry
 * @return the zip archive entry
 * @throws IOException Signals that an I/O exception has occurred.
 */
public ZipArchiveEntry findBestSource(ZipFile source, ZipFile target, ZipArchiveEntry targetEntry)
        throws IOException {
    ArrayList<ZipArchiveEntry> ret = new ArrayList<>();
    for (ZipArchiveEntry next : source.getEntries(targetEntry.getName())) {
        if (next.getCrc() == targetEntry.getCrc())
            return next;
        ret.add(next);
    }
    if (ret.size() == 0)
        return null;
    if (ret.size() == 1 || targetEntry.isDirectory())
        return ret.get(0);
    //More than one and no matching crc --- need to calculate xdeltas and pick the  shortest
    ZipArchiveEntry retEntry = null;
    for (ZipArchiveEntry sourceEntry : ret) {
        try (ByteArrayOutputStream outbytes = new ByteArrayOutputStream()) {
            Delta d = new Delta();
            DiffWriter diffWriter = new GDiffWriter(new DataOutputStream(outbytes));
            int sourceSize = (int) sourceEntry.getSize();
            byte[] sourceBytes = new byte[sourceSize];
            try (InputStream sourceStream = source.getInputStream(sourceEntry)) {
                for (int erg = sourceStream.read(sourceBytes); erg < sourceBytes.length; erg += sourceStream
                        .read(sourceBytes, erg, sourceBytes.length - erg))
                    ;
            }
            d.compute(sourceBytes, target.getInputStream(targetEntry), diffWriter);
            byte[] nextDiff = outbytes.toByteArray();
            if (calculatedDelta == null || calculatedDelta.length > nextDiff.length) {
                retEntry = sourceEntry;
                calculatedDelta = nextDiff;
            }
        }
    }
    return retEntry;
}

From source file:de.catma.ui.repository.wizard.FileTypePanel.java

private ArrayList<SourceDocumentResult> makeSourceDocumentResultsFromInputFile(TechInfoSet inputTechInfoSet)
        throws MalformedURLException, IOException {

    ArrayList<SourceDocumentResult> output = new ArrayList<SourceDocumentResult>();

    FileType inputFileType = FileType.getFileType(inputTechInfoSet.getMimeType());

    if (inputFileType != FileType.ZIP) {
        SourceDocumentResult outputSourceDocumentResult = new SourceDocumentResult();

        String sourceDocumentID = repository.getIdFromURI(inputTechInfoSet.getURI());
        outputSourceDocumentResult.setSourceDocumentID(sourceDocumentID);

        SourceDocumentInfo outputSourceDocumentInfo = outputSourceDocumentResult.getSourceDocumentInfo();
        outputSourceDocumentInfo.setTechInfoSet(new TechInfoSet(inputTechInfoSet));
        outputSourceDocumentInfo.setContentInfoSet(new ContentInfoSet());

        outputSourceDocumentInfo.getTechInfoSet().setFileType(inputFileType);

        output.add(outputSourceDocumentResult);
    } else { //TODO: put this somewhere sensible
        URI uri = inputTechInfoSet.getURI();
        ZipFile zipFile = new ZipFile(uri.getPath());
        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();

        String tempDir = ((CatmaApplication) UI.getCurrent()).getTempDirectory();
        IDGenerator idGenerator = new IDGenerator();

        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = entries.nextElement();
            String fileName = FilenameUtils.getName(entry.getName());
            String fileId = idGenerator.generate();

            File entryDestination = new File(tempDir, fileId);
            if (entryDestination.exists()) {
                entryDestination.delete();
            }//  w ww.ja  v  a 2 s  .c  om

            entryDestination.getParentFile().mkdirs();
            if (entry.isDirectory()) {
                entryDestination.mkdirs();
            } else {
                BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(entryDestination));
                IOUtils.copy(bis, bos);
                IOUtils.closeQuietly(bis);
                IOUtils.closeQuietly(bos);

                SourceDocumentResult outputSourceDocumentResult = new SourceDocumentResult();
                URI newURI = entryDestination.toURI();

                String repositoryId = repository.getIdFromURI(newURI); // we need to do this as a catma:// is appended

                outputSourceDocumentResult.setSourceDocumentID(repositoryId);

                SourceDocumentInfo outputSourceDocumentInfo = outputSourceDocumentResult
                        .getSourceDocumentInfo();
                TechInfoSet newTechInfoSet = new TechInfoSet(fileName, null, newURI); // TODO: MimeType detection ?
                FileType newFileType = FileType.getFileTypeFromName(fileName);
                newTechInfoSet.setFileType(newFileType);

                outputSourceDocumentInfo.setTechInfoSet(newTechInfoSet);
                outputSourceDocumentInfo.setContentInfoSet(new ContentInfoSet());

                output.add(outputSourceDocumentResult);
            }
        }

        ZipFile.closeQuietly(zipFile);
    }

    for (SourceDocumentResult sdr : output) {
        TechInfoSet sdrTechInfoSet = sdr.getSourceDocumentInfo().getTechInfoSet();
        String sdrSourceDocumentId = sdr.getSourceDocumentID();

        ProtocolHandler protocolHandler = getProtocolHandlerForUri(sdrTechInfoSet.getURI(), sdrSourceDocumentId,
                sdrTechInfoSet.getMimeType());
        String mimeType = protocolHandler.getMimeType();

        sdrTechInfoSet.setMimeType(mimeType);
        FileType sdrFileType = FileType.getFileType(mimeType);
        sdrTechInfoSet.setFileType(sdrFileType);

        if (sdrFileType.isCharsetSupported()) {
            Charset charset = Charset.forName(protocolHandler.getEncoding());
            sdrTechInfoSet.setCharset(charset);
        } else {
            sdrTechInfoSet.setFileOSType(FileOSType.INDEPENDENT);
        }

        loadSourceDocumentAndContent(sdr);
    }

    return output;
}