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

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

Introduction

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

Prototype

public ZipFile(String name) throws IOException 

Source Link

Document

Opens the given file for reading, assuming "UTF8".

Usage

From source file:org.jboss.as.forge.util.Files.java

public static boolean extractAppServer(final String zipPath, final File target, final boolean overwrite)
        throws IOException {
    if (target.exists() && !overwrite) {
        throw new IllegalStateException(Messages.INSTANCE.getMessage("files.not.empty.directory"));
    }/*  w  ww. ja  v a  2  s.com*/
    // Create a temporary directory
    final File tmpDir = new File(getTempDirectory(), "jboss-as-" + zipPath.hashCode());
    if (tmpDir.exists()) {
        deleteRecursively(tmpDir);
    }
    try {
        final byte buff[] = new byte[1024];
        ZipFile file = null;
        try {
            file = new ZipFile(zipPath);
            final Enumeration<ZipArchiveEntry> entries = file.getEntries();
            while (entries.hasMoreElements()) {
                final ZipArchiveEntry entry = entries.nextElement();
                // Create the extraction target
                final File extractTarget = new File(tmpDir, entry.getName());
                if (entry.isDirectory()) {
                    extractTarget.mkdirs();
                } else {
                    final File parent = new File(extractTarget.getParent());
                    parent.mkdirs();
                    final BufferedInputStream in = new BufferedInputStream(file.getInputStream(entry));
                    try {
                        final BufferedOutputStream out = new BufferedOutputStream(
                                new FileOutputStream(extractTarget));
                        try {
                            int read;
                            while ((read = in.read(buff)) != -1) {
                                out.write(buff, 0, read);
                            }
                        } finally {
                            Streams.safeClose(out);
                        }
                    } finally {
                        Streams.safeClose(in);
                    }
                    // Set the file permissions
                    if (entry.getUnixMode() > 0) {
                        setPermissions(extractTarget, FilePermissions.of(entry.getUnixMode()));
                    }
                }
            }
        } catch (IOException e) {
            throw new IOException(Messages.INSTANCE.getMessage("files.extraction.error", file), e);
        } finally {
            ZipFile.closeQuietly(file);
            // Streams.safeClose(file);
        }
        // If the target exists, remove then rename
        if (target.exists()) {
            deleteRecursively(target);
        }
        // First child should be a directory and there should only be one child
        final File[] children = tmpDir.listFiles();
        if (children != null && children.length == 1) {
            return moveDirectory(children[0], target);
        }
        return moveDirectory(tmpDir, target);

    } finally {
        deleteRecursively(tmpDir);
    }
}

From source file:org.jboss.datavirt.commons.dev.server.util.ArchiveUtils.java

/**
 * Unpacks the given archive file into the output directory.
 * @param archiveFile an archive file/*www .jav  a  2  s  . c o  m*/
 * @param toDir where to unpack the archive to
 * @throws IOException
 */
public static void unpackToWorkDir(File archiveFile, File toDir) throws IOException {
    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(archiveFile);
        Enumeration<ZipArchiveEntry> zipEntries = zipFile.getEntries();
        while (zipEntries.hasMoreElements()) {
            ZipArchiveEntry entry = zipEntries.nextElement();
            String entryName = entry.getName();
            File outFile = new File(toDir, entryName);
            if (!outFile.getParentFile().exists()) {
                if (!outFile.getParentFile().mkdirs()) {
                    throw new IOException(
                            "Failed to create parent directory: " + outFile.getParentFile().getCanonicalPath());
                }
            }

            if (entry.isDirectory()) {
                if (!outFile.mkdir()) {
                    throw new IOException("Failed to create directory: " + outFile.getCanonicalPath());
                }
            } else {
                InputStream zipStream = null;
                OutputStream outFileStream = null;

                zipStream = zipFile.getInputStream(entry);
                outFileStream = new FileOutputStream(outFile);
                try {
                    IOUtils.copy(zipStream, outFileStream);
                } finally {
                    IOUtils.closeQuietly(zipStream);
                    IOUtils.closeQuietly(outFileStream);
                }
            }
        }
    } finally {
        ZipFile.closeQuietly(zipFile);
    }
}

From source file:org.jboss.qa.jenkins.test.executor.utils.unpack.UnZipper.java

@Override
public void unpack(File archive, File destination) throws IOException {
    try (ZipFile zip = new ZipFile(archive)) {
        final Set<ZipArchiveEntry> entries = new HashSet<>(Collections.list(zip.getEntries()));

        if (ignoreRootFolders) {
            pathSegmentsToTrim = countRootFolders(entries);
        }//from   w w w  . j av  a  2  s  .c  o  m

        for (ZipArchiveEntry entry : entries) {
            if (entry.isDirectory()) {
                continue;
            }
            final String zipPath = trimPathSegments(entry.getName(), pathSegmentsToTrim);
            final File file = new File(destination, zipPath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs(); // Create parent folders if not exist
            }

            try (InputStream is = zip.getInputStream(entry); OutputStream fos = new FileOutputStream(file)) {
                IOUtils.copy(is, fos);
                // check for user-executable bit on entry and apply to file
                if ((entry.getUnixMode() & 0100) != 0) {
                    file.setExecutable(true);
                }
            }
            file.setLastModified(entry.getTime());
        }
    }
}

From source file:org.kuali.ole.docstore.model.bagit.BagExtractor.java

/**
 * @param bagFile/*from w ww  . j a  v  a 2s. c o  m*/
 * @return
 */
public static boolean verifyBag(File bagFile) throws IOException, FormatHelper.UnknownFormatException {

    SimpleResult result = null;
    Bag bag;
    LOG.info("synchronized verifyBagggggg " + bagFile.getAbsolutePath());
    synchronized (bf) {
        LOG.info("synchronizeddddd");
        System.out.println("yes");
        //    try {
        Bag.Format format = FormatHelper.getFormat(bagFile);
        LOG.info("format " + format);
        //gov.loc.repository.bagit.filesystem.FileSystem fileFileSystem = new FileFileSystem(bagFile);
        gov.loc.repository.bagit.filesystem.FileSystem zipFileSystem = new ZipFileSystem(bagFile);
        //LOG.info("FileFileSystem "+fileFileSystem);

        Iterator ite = zipFileSystem.getRoot().listChildren().iterator();
        while (ite.hasNext()) {
            FileSystemNode fs = (FileSystemNode) ite.next();
            ZipFile zipFile = new ZipFile(bagFile);
            Enumeration<ZipArchiveEntry> entryEnum = zipFile.getEntries();
            while (entryEnum.hasMoreElements()) {
                ZipArchiveEntry entry = entryEnum.nextElement();
                String entryFilepath = entry.getName();
                LOG.info("entryFilepath " + entryFilepath);
                if (entryFilepath.endsWith("/")) {
                    LOG.info("in if entryFilepath.endsWith");
                    entryFilepath = entryFilepath.substring(0, entryFilepath.length() - 1);
                } else {
                    //entryFilepath = entryFilepath.substring(0, entryFilepath.length()-1);
                    LOG.info("in else entryFilepath.endsWith entryFilepath " + entryFilepath);
                }
                File parentFile = new File(entryFilepath).getParentFile();

                List<String> parentPaths = new ArrayList<String>();
                while (parentFile != null) {
                    parentPaths.add((parentFile.getPath()));
                    parentFile = parentFile.getParentFile();
                }
                LOG.info("parentPaths " + parentPaths);
            }
        }

        //}
        //            catch (FormatHelper.UnknownFormatException e) {
        //                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        //            }

        bag = bf.createBag(bagFile);
        LOG.info("synchronized AFTER createBag");
    }
    result = bag.verifyValid();
    LOG.info("result " + result.getMessages());
    LOG.info("isSuccess " + result.isSuccess());
    return result.isSuccess();
}

From source file:org.larz.dom4.editor.AbstractDetailsPage.java

protected Image getSpriteFromZip(final String sprite, String zipName) {
    try {//from   w ww  . ja  v  a  2 s.  c o m
        Path path = new Path("$nl$/lib/" + zipName + ".zip");
        URL url = FileLocator.find(Activator.getDefault().getBundle(), path, null);
        String dbPath = FileLocator.toFileURL(url).getPath();
        ZipFile zipFile = new ZipFile(new File(dbPath));
        InputStream imageStream = zipFile.getInputStream(zipFile.getEntry(sprite));
        Image image = null;
        if (spriteMap.get(sprite) != null) {
            image = spriteMap.get(sprite);
        } else {
            if (imageStream != null) {
                image = new Image(null, new ImageData(imageStream));
                spriteMap.put(sprite, image);
            }
        }
        return image;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.larz.dom4.editor.MonsterDetailsPage.java

private Image getSpriteFromZip(final String sprite) {
    ImageLoader loader1 = new ImageLoader() {
        @Override/*ww w. ja  v a  2 s. c o m*/
        public InputStream getStream() throws IOException {
            Path path = new Path("$nl$/lib/sprites.zip");
            URL url = FileLocator.find(Activator.getDefault().getBundle(), path, null);
            String dbPath = FileLocator.toFileURL(url).getPath();
            ZipFile zipFile = new ZipFile(new File(dbPath));
            return zipFile.getInputStream(zipFile.getEntry(sprite));
        }
    };
    Image image = null;
    try {
        if (spriteMap.get(sprite) != null) {
            image = spriteMap.get(sprite);
        } else {
            image = new Image(null, ImageConverter.convertToSWT(ImageConverter.cropImage(loader1.loadImage())));
            spriteMap.put(sprite, image);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return image;
}

From source file:org.moe.cli.manager.PrebuildCocoaPodsManager.java

public IExecutor processCocoapods(String source, SpecObject spec, String packageName, String[] javaSource,
        String outputJar) throws IOException, CompressorException, ArchiveException,
        InvalidParameterSpecException, InterruptedException, URISyntaxException, UnsupportedTypeException {
    File tmpFolder = NatJFileUtils.getNewTempDirectory();
    File download = new File(tmpFolder, "download/");
    if (!download.exists()) {
        download.mkdirs();//w ww .ja  v a  2 s.  c o  m
    }

    int nameIdx = source.lastIndexOf("/");
    File outFile = new File(download, source.substring(nameIdx + 1));

    GrabUtils.download(new URI(source), outFile);

    int extIdx = outFile.getName().lastIndexOf(".");
    String folderUnzip = outFile.getName().substring(0, extIdx);
    File destination = new File(download, folderUnzip);
    if (!destination.exists()) {
        destination.mkdirs();
    }

    String type = spec.getSource().get("type");
    if (outFile.getName().endsWith(".zip") || (type != null && type.equals("zip"))) {
        ZipFile apachZip = new ZipFile(outFile);
        ArchiveUtils.unzipArchive(apachZip, destination);
    } else if (outFile.getName().endsWith("tar.bzip2") || outFile.getName().endsWith("tar.gz")
            || outFile.getName().endsWith("tar.bz2") || type.equals("tgz")) {
        InputStream inputC = null;

        int extArchIdx = outFile.getName().lastIndexOf(".");
        String ext = outFile.getName().substring(extArchIdx + 1);
        if (ext.equals("tar")) {
            inputC = new FileInputStream(outFile);
        } else if (ext.equals("bzip2") || ext.equals("gz") || ext.equals("bz2")) {
            InputStream fin = new FileInputStream(outFile);

            String compressorType = null;
            if (ext.equals("bzip2") || ext.equals("bz2")) {
                compressorType = CompressorStreamFactory.BZIP2;
            } else if (ext.equals("gz") || type.equals("tgz")) {
                compressorType = CompressorStreamFactory.GZIP;
            }
            inputC = new CompressorStreamFactory().createCompressorInputStream(compressorType, fin);
        } else {
            throw new InvalidParameterException("Unsupported archive type");
        }

        ArchiveInputStream input = new ArchiveStreamFactory().createArchiveInputStream(ArchiveStreamFactory.TAR,
                inputC);
        ArchiveUtils.untarArchive(input, destination);
    }

    //update destination for git repo
    if (spec.getSource().containsKey("git")) {
        String git = spec.getSource().get("git");
        String tag = spec.getSource().get("tag");

        int gitNameIdx = git.lastIndexOf("/");
        String gitName = git.substring(gitNameIdx + 1);
        if (gitName.endsWith(".git")) {
            gitName = gitName.substring(0, gitName.length() - 4);
        }

        if (!Character.isDigit(tag.charAt(0)) && Character.isDigit(tag.charAt(1))) {
            tag = tag.substring(1);
        }

        String zipSubfolder = String.format("%s-%s", gitName, tag);
        destination = new File(destination, zipSubfolder);
    }

    List<String> commandList = spec.getPreparedCommands();
    for (String command : commandList) {
        if (command != null && !command.isEmpty()) {
            executePrepareCommands(destination, command);
        }
    }

    IExecutor executor = null;

    //find all bundles
    Set<String> bundleContent = new HashSet<String>();
    List<String> resources = spec.getResources();
    if (resources != null && resources.size() > 0) {
        for (String bundle : resources) {
            Set<String> bundleWildCard = getBundleResources(bundle, destination);
            bundleContent.addAll(bundleWildCard);
        }
    }
    String[] bundleRes = bundleContent.toArray(new String[0]);

    //get additional linker flags
    String ldFlags = spec.getLdFlags();

    //create 
    Set<String> headersContent = new HashSet<String>();
    List<String> headerList = spec.getSourceFiles();
    if (headerList != null && headerList.size() > 0) {
        for (String header : headerList) {
            int recursivIdx = header.indexOf("**");

            if (recursivIdx >= 0) {
                File headerFile = new File(destination, header.substring(0, recursivIdx));
                headersContent.add(headerFile.getPath());
            } else {
                Set<String> bundleWildCard = getBundleResources(header, destination);
                headersContent.addAll(bundleWildCard);
            }
        }
    }

    if (spec.getVendoredFrameworks() != null && spec.getVendoredFrameworks().size() > 0) {
        List<File> frameworkList = new ArrayList<>();
        Set<String> frameworkContent = new HashSet<String>();
        for (String vFramework : spec.getVendoredFrameworks()) {
            Set<String> frName = getBundleResources(vFramework, destination);
            if (frName.size() != 1)
                throw new RuntimeException(
                        "Something wrong with this code. Refactor it! And the same with libraries");
            File frameworkFile = new File(frName.toArray(new String[0])[0]);
            if (frameworkFile.exists()) {
                frameworkList.add(frameworkFile);
                frameworkContent.add(frameworkFile.getPath());

                int frameworkNameIdx = frameworkFile.getName().lastIndexOf(".");
                if (frameworkNameIdx >= 0) {
                    ldFlags = ldFlags + "-framework " + frameworkFile.getName().substring(0, frameworkNameIdx)
                            + ";";
                }
            }
        }

        if (headersContent.isEmpty()) {
            for (File framework : frameworkList) {
                File headerFile = new File(framework, "Headers");
                headersContent.add(headerFile.getPath());
            }
        }

        executor = new ThirdPartyFrameworkLinkExecutor(packageName, frameworkContent.toArray(new String[0]),
                javaSource, headersContent.toArray(new String[0]), bundleRes, outputJar, ldFlags);
    } else if (spec.getVendoredLibraries() != null && spec.getVendoredLibraries().size() > 0) {
        Set<String> libContent = new HashSet<String>();

        for (String lib : spec.getVendoredLibraries()) {
            Set<String> libName = getBundleResources(lib, destination);
            if (libName.size() != 1)
                throw new RuntimeException(
                        "Something wrong with this code. Refactor it! And the same with libraries");

            File library = new File(libName.toArray(new String[0])[0]);
            if (library.exists()) {
                libContent.add(library.getPath());

                int libNameIdx = library.getName().lastIndexOf(".");
                if (libNameIdx >= 0) {
                    String libShortName = library.getName().substring(0, libNameIdx);
                    ldFlags = ldFlags + "-l"
                            + (libShortName.startsWith("lib") ? libShortName.substring(3) : libShortName) + ";";
                }
            }
        }

        executor = new ThirdPartyLibraryLinkExecutor(packageName, libContent.toArray(new String[0]), javaSource,
                headersContent.toArray(new String[0]), bundleRes, outputJar, ldFlags);
    }
    return executor;
}

From source file:org.obm.sync.ObmSyncArchiveUtils.java

private static File[] replaceServiceJar(File[] asFile) {
    return FluentIterable.from(Arrays.asList(asFile)).transform(new Function<File, File>() {

        @Override/*from   w w  w  .j av  a  2 s. com*/
        public File apply(File input) {
            if (input.getName().contains("services-module")) {
                ZipFile servicesZip = null;
                try {
                    File outputFile = File.createTempFile("services-module", ".jar");
                    servicesZip = new ZipFile(input);

                    ChangeSet changeSet = new ChangeSet();
                    changeSet.add(new JarArchiveEntry("META-INF/MANIFEST.MF"),
                            ClassLoader.getSystemClassLoader().getResourceAsStream("MANIFEST.MF"));
                    ChangeSetPerformer changeSetPerformer = new ChangeSetPerformer(changeSet);
                    JarArchiveOutputStream jarArchiveOutputStream = new JarArchiveOutputStream(
                            new FileOutputStream(outputFile));
                    changeSetPerformer.perform(servicesZip, jarArchiveOutputStream);
                    return outputFile;
                } catch (IOException e) {
                    Throwables.propagate(e);
                } finally {
                    try {
                        if (servicesZip != null) {
                            servicesZip.close();
                        }
                    } catch (IOException e) {
                        Throwables.propagate(e);
                    }
                }
            }
            return input;
        }
    }).toArray(File.class);
}

From source file:org.openjump.core.ui.plugin.file.open.OpenFileWizardState.java

public void setupFileLoaders(File[] files, FileLayerLoader fileLayerLoader) {
    Set<File> fileSet = new TreeSet<File>(Arrays.asList(files));
    multiLoaderFiles.clear();//www  .  j a  v  a 2s.c  om
    // explicit loader chosen
    if (fileLayerLoader != null) {
        fileLoaderMap.clear();
        for (File file : fileSet) {
            setFileLoader(file.toURI(), fileLayerLoader);
        }
    } else {
        // Remove old entries in fileloadermap
        fileLoaderMap.clear();
        //      for (Iterator<Entry<URI, FileLayerLoader>> iterator = fileLoaderMap.entrySet()
        //        .iterator(); iterator.hasNext();) {
        //        Entry<URI, FileLayerLoader> entry = iterator.next();
        //        URI fileUri = entry.getKey();
        //        File file;

        //        if (fileUri.getScheme().equals("zip")) {
        //          file = UriUtil.getZipFile(fileUri);
        //        } else {
        //          file = new File(fileUri);
        //        }
        //        
        //        if (!fileSet.contains(file)) {
        //          FileLayerLoader loader = entry.getValue();
        //          fileLoaderFiles.get(loader);
        //          Set<URI> loaderFiles = fileLoaderFiles.get(loader);
        //          if (loaderFiles != null) {
        //            loaderFiles.remove(fileUri);
        //          }
        //          iterator.remove();
        //        }
        //      }

        // manually add compressed files here
        for (File file : files) {
            // zip files
            if (CompressedFile.isZip(file.getName())) {
                try {
                    ZipFile zipFile = new ZipFile(file);
                    URI fileUri = file.toURI();
                    Enumeration entries = zipFile.getEntries();
                    while (entries.hasMoreElements()) {
                        ZipArchiveEntry entry = (ZipArchiveEntry) entries.nextElement();
                        if (!entry.isDirectory()) {
                            URI entryUri = UriUtil.createZipUri(file, entry.getName());
                            String entryExt = UriUtil.getFileExtension(entryUri);
                            //System.out.println(entryUri+"<->"+entryExt);
                            addFile(entryExt, entryUri);
                        }
                    }
                } catch (Exception e) {
                    errorHandler.handleThrowable(e);
                }
            }
            // tar[.gz,.bz...] (un)compressed archive files
            else if (CompressedFile.isTar(file.getName())) {
                try {
                    InputStream is = CompressedFile.openFile(file.getAbsolutePath(), null);
                    TarArchiveEntry entry;
                    TarArchiveInputStream tis = new TarArchiveInputStream(is);
                    while ((entry = tis.getNextTarEntry()) != null) {
                        if (!entry.isDirectory()) {
                            URI entryUri = UriUtil.createZipUri(file, entry.getName());

                            String entryExt = UriUtil.getFileExtension(entryUri);
                            addFile(entryExt, entryUri);
                        }
                    }
                    tis.close();
                } catch (Exception e) {
                    errorHandler.handleThrowable(e);
                }
            }
            // 7zip compressed files
            else if (CompressedFile.isSevenZ(file.getName())) {
                try {
                    //System.out.println(file.getName());
                    SevenZFile sevenZFile = new SevenZFile(file);
                    SevenZArchiveEntry entry;
                    while ((entry = sevenZFile.getNextEntry()) != null) {
                        if (!entry.isDirectory()) {
                            URI entryUri = UriUtil.createZipUri(file, entry.getName());

                            String entryExt = UriUtil.getFileExtension(entryUri);
                            addFile(entryExt, entryUri);
                        }
                    }
                    sevenZFile.close();
                } catch (IOException e) {
                    errorHandler.handleThrowable(e);
                }
            }
            // compressed files
            else if (CompressedFile.hasCompressedFileExtension(file.getName())) {
                String[] parts = file.getName().split("\\.");
                if (parts.length > 2)
                    addFile(parts[parts.length - 2], file.toURI());
            }
            // anything else is a plain data file
            else {
                URI fileUri = file.toURI();
                addFile(FileUtil.getExtension(file), fileUri);
            }
        }
    }
}

From source file:org.opentestsystem.authoring.testitembank.service.impl.ApipZipInputFileExtractorService.java

@Override
public final ApipZipFileContent extractData(final File zippedFile) {
    final ApipZipFileContent zipContent = new ApipZipFileContent();
    try {//from  w  ww  .  j ava 2  s.com
        final ZipFile zip = new ZipFile(zippedFile);
        final HashMap<String, ZipArchiveEntry> mappedEntries = getMappedZipFileEntries(zip);
        final ApipManifest manifest = extractManifest(zip, mappedEntries);
        zipContent.setManifest(manifest);
        zipContent.setItemMetadata(getApipItemMetadata(zip, mappedEntries, manifest));
        zipContent.setItemContentMap(getItemZipMap(manifest, zip, mappedEntries));
        zip.close();
    } catch (final IOException e) {
        throw new TestItemBankException("zip.io.error", e);
    }

    return zipContent;
}