Example usage for org.apache.commons.compress.archivers.zip ZipArchiveEntry getName

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

Introduction

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

Prototype

public String getName() 

Source Link

Document

Get the name of the entry.

Usage

From source file:io.webfolder.cdp.ChromiumDownloader.java

private static void unpack(File archive, File destionation) throws IOException {
    try (ZipFile zip = new ZipFile(archive)) {
        Map<File, String> symLinks = new LinkedHashMap<>();
        Enumeration<ZipArchiveEntry> iterator = zip.getEntries();
        // Top directory name we are going to ignore
        String parentDirectory = iterator.nextElement().getName();
        // Iterate files & folders
        while (iterator.hasMoreElements()) {
            ZipArchiveEntry entry = iterator.nextElement();
            String name = entry.getName().substring(parentDirectory.length());
            File outputFile = new File(destionation, name);
            if (name.startsWith("interactive_ui_tests")) {
                continue;
            }/*  w  w  w  . j a  v a 2  s.c  o  m*/
            if (entry.isUnixSymlink()) {
                symLinks.put(outputFile, zip.getUnixSymlink(entry));
            } else if (!entry.isDirectory()) {
                if (!outputFile.getParentFile().isDirectory()) {
                    outputFile.getParentFile().mkdirs();
                }
                try (FileOutputStream outStream = new FileOutputStream(outputFile)) {
                    IOUtils.copy(zip.getInputStream(entry), outStream);
                }
            }
            // Set permission
            if (!entry.isUnixSymlink() && outputFile.exists())
                try {
                    Files.setPosixFilePermissions(outputFile.toPath(),
                            modeToPosixPermissions(entry.getUnixMode()));
                } catch (Exception e) {
                    // ignore
                }
        }
        for (Map.Entry<File, String> entry : symLinks.entrySet()) {
            try {
                Path source = Paths.get(entry.getKey().getAbsolutePath());
                Path target = source.getParent().resolve(entry.getValue());
                if (!source.toFile().exists())
                    Files.createSymbolicLink(source, target);
            } catch (Exception e) {
                // ignore
            }
        }
    }
}

From source file:backup.namenode.NameNodeBackupServicePlugin.java

private static ClassLoader getClassLoader(InputStream zipFileInput) throws IOException, FileNotFoundException {
    File tmpDir = new File(System.getProperty(JAVA_IO_TMPDIR), HDFS_BACKUP_STATUS);
    File dir = new File(tmpDir, TMP + System.nanoTime());
    Closer closer = Closer.create();//from w w w  .ja  v  a2s.c  o  m
    closer.register((Closeable) () -> FileUtils.deleteDirectory(dir));
    Runtime.getRuntime().addShutdownHook(new Thread(() -> IOUtils.closeQuietly(closer)));
    dir.mkdirs();

    List<File> allFiles = new ArrayList<>();
    try (ZipArchiveInputStream zinput = new ZipArchiveInputStream(zipFileInput)) {
        ZipArchiveEntry zipEntry;
        while ((zipEntry = zinput.getNextZipEntry()) != null) {
            String name = zipEntry.getName();
            File f = new File(dir, name);
            if (zipEntry.isDirectory()) {
                f.mkdirs();
            } else {
                f.getParentFile().mkdirs();
                try (FileOutputStream out = new FileOutputStream(f)) {
                    IOUtils.copy(zinput, out);
                }
                allFiles.add(f);
            }
        }
    }
    return new FileClassLoader(allFiles);
}

From source file:com.igormaznitsa.zxpoly.utils.ROMLoader.java

public static RomData getROMFrom(final String url) throws IOException {
    final URI uri;
    try {/*  w  w  w.  j  av  a  2s.  c o  m*/
        uri = new URI(url);
    } catch (URISyntaxException ex) {
        throw new IOException("Error in URL '" + url + "\'", ex);
    }
    final String scheme = uri.getScheme();
    final String userInfo = uri.getUserInfo();
    final String name;
    final String password;
    if (userInfo != null) {
        final String[] splitted = userInfo.split("\\:");
        name = splitted[0];
        password = splitted[1];
    } else {
        name = null;
        password = null;
    }

    final byte[] loaded;
    if (scheme.startsWith("http")) {
        loaded = loadHTTPArchive(url);
    } else if (scheme.startsWith("ftp")) {
        loaded = loadFTPArchive(uri.getHost(), uri.getPath(), name, password);
    } else {
        throw new IllegalArgumentException("Unsupported scheme [" + scheme + ']');
    }

    final ZipArchiveInputStream in = new ZipArchiveInputStream(new ByteArrayInputStream(loaded));

    byte[] rom48 = null;
    byte[] rom128 = null;
    byte[] romTrDos = null;

    while (true) {
        final ZipArchiveEntry entry = in.getNextZipEntry();
        if (entry == null) {
            break;
        }

        if (entry.isDirectory()) {
            continue;
        }

        if (ROM_48.equalsIgnoreCase(entry.getName())) {
            final int size = (int) entry.getSize();
            if (size > 16384) {
                throw new IOException("ROM 48 has too big size");
            }
            rom48 = new byte[16384];
            IOUtils.readFully(in, rom48, 0, size);
        } else if (ROM_128TR.equalsIgnoreCase(entry.getName())) {
            final int size = (int) entry.getSize();
            if (size > 16384) {
                throw new IOException("ROM 128TR has too big size");
            }
            rom128 = new byte[16384];
            IOUtils.readFully(in, rom128, 0, size);
        } else if (ROM_TRDOS.equalsIgnoreCase(entry.getName())) {
            final int size = (int) entry.getSize();
            if (size > 16384) {
                throw new IOException("ROM TRDOS has too big size");
            }
            romTrDos = new byte[16384];
            IOUtils.readFully(in, romTrDos, 0, size);
        }
    }

    if (rom48 == null) {
        throw new IOException(ROM_48 + " not found");
    }
    if (rom128 == null) {
        throw new IOException(ROM_128TR + " not found");
    }
    if (romTrDos == null) {
        throw new IOException(ROM_TRDOS + " not found");
    }

    return new RomData(rom48, rom128, romTrDos);
}

From source file:fr.ens.biologie.genomique.eoulsan.modules.mapping.hadoop.ReadsMapperHadoopModule.java

/**
 * Compute the checksum of a ZIP file./*from   www . j  a  v  a 2  s .c om*/
 * @param in input stream
 * @return the checksum as a string
 * @throws IOException if an error occurs while creating the checksum
 */
private static String computeZipCheckSum(final InputStream in) throws IOException {

    ZipArchiveInputStream zais = new ZipArchiveInputStream(in);

    // Create Hash function
    final Hasher hs = Hashing.md5().newHasher();

    // Store entries in a map
    final Map<String, long[]> map = new HashMap<>();

    ZipArchiveEntry e;

    while ((e = zais.getNextZipEntry()) != null) {
        map.put(e.getName(), new long[] { e.getSize(), e.getCrc() });
    }

    zais.close();

    // Add values to hash function in an ordered manner
    for (String filename : new TreeSet<>(map.keySet())) {

        hs.putString(filename, StandardCharsets.UTF_8);
        for (long l : map.get(filename)) {
            hs.putLong(l);
        }
    }

    return hs.hash().toString();
}

From source file:com.chnoumis.commons.zip.utils.ZipUtils.java

public static List<ZipInfo> unZiptoZipInfo(InputStream is) throws ArchiveException, IOException {
    List<ZipInfo> results = new ArrayList<ZipInfo>();
    ArchiveInputStream in = null;/*from w ww .  j  a  v a 2s .  c o  m*/
    try {
        in = new ArchiveStreamFactory().createArchiveInputStream("zip", is);
        ZipArchiveEntry entry = null;
        while ((entry = (ZipArchiveEntry) in.getNextEntry()) != null) {
            ZipInfo zipInfo = new ZipInfo();
            OutputStream o = new ByteArrayOutputStream();
            try {
                IOUtils.copy(in, o);
            } finally {
                o.close();
            }
            zipInfo.setFileName(entry.getName());
            zipInfo.setFileContent(o.toString().getBytes());
            results.add(zipInfo);
        }
    } finally {
        if (in != null) {
            in.close();
        }
    }
    is.close();

    return results;
}

From source file:divconq.tool.Updater.java

static public boolean tryUpdate() {
    @SuppressWarnings("resource")
    final Scanner scan = new Scanner(System.in);

    FuncResult<RecordStruct> ldres = Updater.loadDeployed();

    if (ldres.hasErrors()) {
        System.out.println("Error reading deployed.json file: " + ldres.getMessage());
        return false;
    }//from  ww  w  . ja  v  a 2s.c  o  m

    RecordStruct deployed = ldres.getResult();

    String ver = deployed.getFieldAsString("Version");
    String packfolder = deployed.getFieldAsString("PackageFolder");
    String packprefix = deployed.getFieldAsString("PackagePrefix");

    if (StringUtil.isEmpty(ver) || StringUtil.isEmpty(packfolder)) {
        System.out.println("Error reading deployed.json file: Missing Version or PackageFolder");
        return false;
    }

    if (StringUtil.isEmpty(packprefix))
        packprefix = "DivConq";

    System.out.println("Current Version: " + ver);

    Path packpath = Paths.get(packfolder);

    if (!Files.exists(packpath) || !Files.isDirectory(packpath)) {
        System.out.println("Error reading PackageFolder - it may not exist or is not a folder.");
        return false;
    }

    File pp = packpath.toFile();
    RecordStruct deployment = null;
    File matchpack = null;

    for (File f : pp.listFiles()) {
        if (!f.getName().startsWith(packprefix + "-") || !f.getName().endsWith("-bin.zip"))
            continue;

        System.out.println("Checking: " + f.getName());

        // if not a match before, clear this
        deployment = null;

        try {
            ZipFile zf = new ZipFile(f);

            Enumeration<ZipArchiveEntry> entries = zf.getEntries();

            while (entries.hasMoreElements()) {
                ZipArchiveEntry entry = entries.nextElement();

                if (entry.getName().equals("deployment.json")) {
                    //System.out.println("crc: " + entry.getCrc());

                    FuncResult<CompositeStruct> pres = CompositeParser.parseJson(zf.getInputStream(entry));

                    if (pres.hasErrors()) {
                        System.out.println("Error reading deployment.json file");
                        break;
                    }

                    deployment = (RecordStruct) pres.getResult();

                    break;
                }
            }

            zf.close();
        } catch (IOException x) {
            System.out.println("Error reading deployment.json file: " + x);
        }

        if (deployment != null) {
            String fndver = deployment.getFieldAsString("Version");
            String fnddependson = deployment.getFieldAsString("DependsOn");

            if (ver.equals(fnddependson)) {
                System.out.println("Found update: " + fndver);
                matchpack = f;
                break;
            }
        }
    }

    if ((matchpack == null) || (deployment == null)) {
        System.out.println("No updates found!");
        return false;
    }

    String fndver = deployment.getFieldAsString("Version");
    String umsg = deployment.getFieldAsString("UpdateMessage");

    if (StringUtil.isNotEmpty(umsg)) {
        System.out.println("========================================================================");
        System.out.println(umsg);
        System.out.println("========================================================================");
    }

    System.out.println();
    System.out.println("Do you want to install?  (y/n)");
    System.out.println();

    String p = scan.nextLine().toLowerCase();

    if (!p.equals("y"))
        return false;

    System.out.println();

    System.out.println("Intalling: " + fndver);

    Set<String> ignorepaths = new HashSet<>();

    ListStruct iplist = deployment.getFieldAsList("IgnorePaths");

    if (iplist != null) {
        for (Struct df : iplist.getItems())
            ignorepaths.add(df.toString());
    }

    ListStruct dflist = deployment.getFieldAsList("DeleteFiles");

    // deleting
    if (dflist != null) {
        for (Struct df : dflist.getItems()) {
            Path delpath = Paths.get(".", df.toString());

            if (Files.exists(delpath)) {
                System.out.println("Deleting: " + delpath.toAbsolutePath());

                try {
                    Files.delete(delpath);
                } catch (IOException x) {
                    System.out.println("Unable to Delete: " + x);
                }
            }
        }
    }

    // copying updates

    System.out.println("Checking for updated files: ");

    try {
        @SuppressWarnings("resource")
        ZipFile zf = new ZipFile(matchpack);

        Enumeration<ZipArchiveEntry> entries = zf.getEntries();

        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = entries.nextElement();

            String entryname = entry.getName().replace('\\', '/');
            boolean xfnd = false;

            for (String exculde : ignorepaths)
                if (entryname.startsWith(exculde)) {
                    xfnd = true;
                    break;
                }

            if (xfnd)
                continue;

            System.out.print(".");

            Path localpath = Paths.get(".", entryname);

            if (entry.isDirectory()) {
                if (!Files.exists(localpath))
                    Files.createDirectories(localpath);
            } else {
                boolean hashmatch = false;

                if (Files.exists(localpath)) {
                    String local = null;
                    String update = null;

                    try (InputStream lin = Files.newInputStream(localpath)) {
                        local = HashUtil.getMd5(lin);
                    }

                    try (InputStream uin = zf.getInputStream(entry)) {
                        update = HashUtil.getMd5(uin);
                    }

                    hashmatch = (StringUtil.isNotEmpty(local) && StringUtil.isNotEmpty(update)
                            && local.equals(update));
                }

                if (!hashmatch) {
                    System.out.print("[" + entryname + "]");

                    try (InputStream uin = zf.getInputStream(entry)) {
                        Files.createDirectories(localpath.getParent());

                        Files.copy(uin, localpath, StandardCopyOption.REPLACE_EXISTING);
                    } catch (Exception x) {
                        System.out.println("Error updating: " + entryname + " - " + x);
                        return false;
                    }
                }
            }
        }

        zf.close();
    } catch (IOException x) {
        System.out.println("Error reading update package: " + x);
    }

    // updating local config
    deployed.setField("Version", fndver);

    OperationResult svres = Updater.saveDeployed(deployed);

    if (svres.hasErrors()) {
        System.out.println("Intalled: " + fndver
                + " but could not update deployed.json.  Repair the file before continuing.\nError: "
                + svres.getMessage());
        return false;
    }

    System.out.println("Intalled: " + fndver);

    return true;
}

From source file:com.fjn.helper.common.io.file.zip.zip.ZipArchiveHelper.java

/**
 * zip//from ww  w .j  a va  2 s .  co m
 *
 * @param zipFile
 * @param targetDirPath
 */
public static void upZip(File zipFile, String targetDirPath, String filenameEncoding) {
    if (!zipFile.exists())
        return;
    File targetDir = FileUtil.ensureDirExists(targetDirPath);
    ZipFile zipfile = null;
    try {
        zipfile = new ZipFile(zipFile, filenameEncoding);

        ZipArchiveEntry zipEntry = null;
        InputStream fileIn = null;
        Enumeration<? extends ZipArchiveEntry> enumer = zipfile.getEntries();// zipfile.entries();
        while (enumer.hasMoreElements()) {
            zipEntry = enumer.nextElement();
            if (zipEntry.isDirectory()) {
                FileUtil.ensureChildDirExists(targetDir, zipEntry.getName());
            } else {
                logger.info("unzip file" + zipEntry.getName());
                fileIn = zipfile.getInputStream(zipEntry);
                File file2 = FileUtil.ensureFileExists(targetDirPath, zipEntry.getName());
                FileUtil.copyInputStreamToFile(fileIn, file2);
                fileIn.close();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (zipfile != null) {
            try {
                zipfile.close();
            } catch (IOException e) {
                // ignore it
            }
        }
    }

    logger.info("?");
}

From source file:com.android.repository.util.InstallerUtil.java

/**
 * Unzips the given zipped input stream into the given directory.
 *
 * @param in           The (zipped) input stream.
 * @param out          The directory into which to expand the files. Must exist.
 * @param fop          The {@link FileOp} to use for file operations.
 * @param expectedSize Compressed size of the stream.
 * @param progress     Currently only used for logging.
 * @throws IOException If we're unable to read or write.
 *//*from   w  w  w  .java  2 s  .  c o  m*/
public static void unzip(@NonNull File in, @NonNull File out, @NonNull FileOp fop, long expectedSize,
        @NonNull ProgressIndicator progress) throws IOException {
    if (!fop.exists(out) || !fop.isDirectory(out)) {
        throw new IllegalArgumentException("out must exist and be a directory.");
    }
    // ZipFile requires an actual (not mock) file, so make sure we have a real one.
    in = fop.ensureRealFile(in);

    progress.setText("Unzipping...");
    ZipFile zipFile = new ZipFile(in);
    try {
        Enumeration entries = zipFile.getEntries();
        progress.setFraction(0);
        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = (ZipArchiveEntry) entries.nextElement();
            String name = entry.getName();
            File entryFile = new File(out, name);
            progress.setSecondaryText(name);
            if (entry.isUnixSymlink()) {
                ByteArrayOutputStream targetByteStream = new ByteArrayOutputStream();
                readZipEntry(zipFile, entry, targetByteStream, expectedSize, progress);
                Path linkPath = fop.toPath(entryFile);
                Path linkTarget = fop.toPath(new File(targetByteStream.toString()));
                Files.createSymbolicLink(linkPath, linkTarget);
            } else if (entry.isDirectory()) {
                if (!fop.exists(entryFile)) {
                    if (!fop.mkdirs(entryFile)) {
                        progress.logWarning("failed to mkdirs " + entryFile);
                    }
                }
            } else {
                if (!fop.exists(entryFile)) {
                    File parent = entryFile.getParentFile();
                    if (parent != null && !fop.exists(parent)) {
                        fop.mkdirs(parent);
                    }
                    if (!fop.createNewFile(entryFile)) {
                        throw new IOException("Failed to create file " + entryFile);
                    }
                }

                OutputStream unzippedOutput = fop.newFileOutputStream(entryFile);
                if (readZipEntry(zipFile, entry, unzippedOutput, expectedSize, progress)) {
                    return;
                }
                if (!fop.isWindows()) {
                    // get the mode and test if it contains the executable bit
                    int mode = entry.getUnixMode();
                    //noinspection OctalInteger
                    if ((mode & 0111) != 0) {
                        try {
                            fop.setExecutablePermission(entryFile);
                        } catch (IOException ignore) {
                        }
                    }
                }
            }
        }
    } finally {
        ZipFile.closeQuietly(zipFile);
    }
}

From source file:com.mirth.connect.util.ArchiveUtils.java

/**
 * Extracts folders/files from a zip archive using zip-optimized code from commons-compress.
 *///from w  ww  .j a va  2  s . co  m
private static void extractZipArchive(File archiveFile, File destinationFolder) throws CompressException {
    ZipFile zipFile = null;

    try {
        zipFile = new ZipFile(archiveFile);
        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        ZipArchiveEntry entry = null;
        byte[] buffer = new byte[BUFFER_SIZE];

        for (; entries.hasMoreElements(); entry = entries.nextElement()) {
            File outputFile = new File(
                    destinationFolder.getAbsolutePath() + IOUtils.DIR_SEPARATOR + entry.getName());

            if (entry.isDirectory()) {
                FileUtils.forceMkdir(outputFile);
            } else {
                InputStream inputStream = zipFile.getInputStream(entry);
                OutputStream outputStream = FileUtils.openOutputStream(outputFile);

                try {
                    IOUtils.copyLarge(inputStream, outputStream, buffer);
                } finally {
                    IOUtils.closeQuietly(inputStream);
                    IOUtils.closeQuietly(outputStream);
                }
            }
        }
    } catch (Exception e) {
        throw new CompressException(e);
    } finally {
        ZipFile.closeQuietly(zipFile);
    }
}

From source file:com.taobao.android.utils.ZipUtils.java

/**
 * zip?//  w  w w. j  ava  2  s  . co m
 *
 * @param zipFile
 * @param path
 * @param destFolder
 * @throws IOException
 */
public static File extractZipFileToFolder(File zipFile, String path, File destFolder) {
    ZipFile zip;
    File destFile = null;
    try {
        zip = new ZipFile(zipFile);
        ZipArchiveEntry zipArchiveEntry = zip.getEntry(path);
        if (null != zipArchiveEntry) {
            String name = zipArchiveEntry.getName();
            name = FilenameUtils.getName(name);
            destFile = new File(destFolder, name);
            destFolder.mkdirs();
            destFile.createNewFile();
            InputStream is = zip.getInputStream(zipArchiveEntry);
            FileOutputStream fos = new FileOutputStream(destFile);
            int length = 0;
            byte[] b = new byte[1024];
            while ((length = is.read(b, 0, 1024)) != -1) {
                fos.write(b, 0, length);
            }
            is.close();
            fos.close();
        }
        if (null != zip)
            ZipFile.closeQuietly(zip);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return destFile;
}