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:adams.core.io.ZipUtils.java

/**
 * Lists the files stored in the ZIP file.
 *
 * @param input   the ZIP file to obtain the file list from
 * @param listDirs   whether to include directories in the list
 * @return      the stored files/*from w ww.  j  a v a 2  s.c o  m*/
 */
public static List<File> listFiles(File input, boolean listDirs) {
    List<File> result;
    ZipFile zipfile;
    Enumeration<ZipArchiveEntry> enm;
    ZipArchiveEntry entry;

    result = new ArrayList<>();
    zipfile = null;
    try {
        zipfile = new ZipFile(input.getAbsoluteFile());
        enm = zipfile.getEntries();
        while (enm.hasMoreElements()) {
            entry = enm.nextElement();

            // extract
            if (entry.isDirectory()) {
                if (listDirs)
                    result.add(new File(entry.getName()));
            } else {
                result.add(new File(entry.getName()));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (zipfile != null) {
            try {
                zipfile.close();
            } catch (Exception e) {
                // ignored
            }
        }
    }

    return result;
}

From source file:io.github.runassudo.gtfs.ZipStreamGTFSCSV.java

public ZipStreamGTFSCSV(ZipArchiveInputStream zipStream, ZipArchiveEntry zipEntry) {
    super(zipEntry.getName());
    this.zipStream = zipStream;
    this.zipEntry = zipEntry;
}

From source file:at.treedb.jslib.JsLib.java

/**
 * Loads an external JavaScript library.
 * //from   w  w  w.  j  av a2  s  . co  m
 * @param dao
 *            {@code DAOiface} (data access object)
 * @param name
 *            library name
 * @param version
 *            optional library version. If this parameter is null the
 *            library with the highest version number will be loaded
 * @return {@code JsLib} object
 * @throws Exception
 */
@SuppressWarnings("resource")
public static synchronized JsLib load(DAOiface dao, String name, String version) throws Exception {
    initJsLib(dao);
    if (jsLibs == null) {
        return null;
    }
    JsLib lib = null;
    synchronized (lockObj) {
        HashMap<Version, JsLib> v = jsLibs.get(name);
        if (v == null) {
            return null;
        }

        if (version != null) {
            lib = v.get(new Version(version));
        } else {
            Version[] array = v.keySet().toArray(new Version[v.size()]);
            Arrays.sort(array);
            // return the library with the highest version number
            lib = v.get(array[array.length - 1]);
        }
    }
    if (lib != null) {
        if (!lib.isExtracted) {
            // load binary archive data
            lib.callbackAfterLoad(dao);
            // detect zip of 7z archive
            MimeType mtype = ContentInfo.getContentInfo(lib.data);
            int totalSize = 0;
            HashMap<String, byte[]> dataMap = null;
            String libName = "jsLib" + lib.getHistId();
            String classPath = lib.getName() + "/java/classes/";
            if (mtype != null) {
                // ZIP archive
                if (mtype.equals(MimeType.ZIP)) {
                    dataMap = new HashMap<String, byte[]>();
                    lib.zipInput = new ZipArchiveInputStream(new ByteArrayInputStream(lib.data));
                    do {
                        ZipArchiveEntry entry = lib.zipInput.getNextZipEntry();
                        if (entry == null) {
                            break;
                        }
                        if (entry.isDirectory()) {
                            continue;
                        }
                        int size = (int) entry.getSize();
                        totalSize += size;
                        byte[] data = new byte[size];
                        lib.zipInput.read(data, 0, size);
                        dataMap.put(entry.getName(), data);
                        if (entry.getName().contains(classPath)) {
                            lib.javaFiles.add(entry.getName());
                        }
                    } while (true);
                    lib.zipInput.close();
                    lib.isExtracted = true;
                    // 7-zip archive
                } else if (mtype.equals(MimeType._7Z)) {
                    dataMap = new HashMap<String, byte[]>();
                    File tempFile = FileStorage.getInstance().createTempFile(libName, ".7z");
                    tempFile.deleteOnExit();
                    Stream.writeByteStream(tempFile, lib.data);
                    lib.sevenZFile = new SevenZFile(tempFile);
                    do {
                        SevenZArchiveEntry entry = lib.sevenZFile.getNextEntry();
                        if (entry == null) {
                            break;
                        }
                        if (entry.isDirectory()) {
                            continue;
                        }
                        int size = (int) entry.getSize();
                        totalSize += size;
                        byte[] data = new byte[size];
                        lib.sevenZFile.read(data, 0, size);
                        dataMap.put(entry.getName(), data);
                        if (entry.getName().contains(classPath)) {
                            lib.javaFiles.add(entry.getName());
                        }

                    } while (true);
                    lib.sevenZFile.close();
                    lib.isExtracted = true;
                }
            }
            if (!lib.isExtracted) {
                throw new Exception("JsLib.load(): No JavaScript archive extracted!");
            }
            // create a buffer for the archive
            byte[] buf = new byte[totalSize];
            int offset = 0;
            // enumerate the archive entries
            for (String n : dataMap.keySet()) {
                byte[] d = dataMap.get(n);
                System.arraycopy(d, 0, buf, offset, d.length);
                lib.archiveMap.put(n, new ArchiveEntry(offset, d.length));
                offset += d.length;
            }
            // create a temporary file containing the extracted archive
            File tempFile = FileStorage.getInstance().createTempFile(libName, ".dump");
            lib.dumpFile = tempFile;
            tempFile.deleteOnExit();
            Stream.writeByteStream(tempFile, buf);
            FileInputStream inFile = new FileInputStream(tempFile);
            // closed by the GC
            lib.inChannel = inFile.getChannel();
            // discard the archive data - free the memory
            lib.data = null;
            dataMap = null;
        }
    }
    return lib;
}

From source file:com.openkm.misc.ZipTest.java

public void testApache() throws IOException, ArchiveException {
    log.debug("testApache()");
    File zip = File.createTempFile("apache_", ".zip");

    // Create zip
    FileOutputStream fos = new FileOutputStream(zip);
    ArchiveOutputStream aos = new ArchiveStreamFactory().createArchiveOutputStream("zip", fos);
    aos.putArchiveEntry(new ZipArchiveEntry("coeta"));
    aos.closeArchiveEntry();/*from   w  ww .  j  a  va2  s. c o  m*/
    aos.close();

    // Read zip
    FileInputStream fis = new FileInputStream(zip);
    ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream("zip", fis);
    ZipArchiveEntry zae = (ZipArchiveEntry) ais.getNextEntry();
    assertEquals(zae.getName(), "coeta");
    ais.close();
}

From source file:de.crowdcode.movmvn.core.Unzipper.java

/**
 * Unzip a file./*from ww w  .ja  v a 2 s. c om*/
 * 
 * @param archiveFile
 *            to be unzipped
 * @param outPath
 *            the place to put the result
 * @throws IOException
 *             exception
 * @throws ZipException
 *             exception
 */
public void unzipFileToDir(final File archiveFile, final File outPath) throws IOException, ZipException {
    ZipFile zipFile = new ZipFile(archiveFile);
    Enumeration<ZipArchiveEntry> e = zipFile.getEntries();
    while (e.hasMoreElements()) {
        ZipArchiveEntry entry = e.nextElement();
        File file = new File(outPath, entry.getName());
        if (entry.isDirectory()) {
            FileUtils.forceMkdir(file);
        } else {
            InputStream is = zipFile.getInputStream(entry);
            FileOutputStream os = FileUtils.openOutputStream(file);
            try {
                IOUtils.copy(is, os);
            } finally {
                os.close();
                is.close();
            }
            file.setLastModified(entry.getTime());
        }
    }
}

From source file:com.liferay.blade.cli.command.InstallExtensionCommandTest.java

private static void _testJarsDiff(File warFile1, File warFile2) throws IOException {
    DifferenceCalculator differenceCalculator = new DifferenceCalculator(warFile1, warFile2);

    differenceCalculator.setFilenameRegexToIgnore(Collections.singleton(".*META-INF.*"));
    differenceCalculator.setIgnoreTimestamps(true);

    Differences differences = differenceCalculator.getDifferences();

    if (!differences.hasDifferences()) {
        return;// ww w.jav  a 2 s.c  om
    }

    StringBuilder message = new StringBuilder();

    message.append("WAR ");
    message.append(warFile1);
    message.append(" and ");
    message.append(warFile2);
    message.append(" do not match:");
    message.append(System.lineSeparator());

    boolean realChange;

    Map<String, ZipArchiveEntry> added = differences.getAdded();
    Map<String, ZipArchiveEntry[]> changed = differences.getChanged();
    Map<String, ZipArchiveEntry> removed = differences.getRemoved();

    if (added.isEmpty() && !changed.isEmpty() && removed.isEmpty()) {
        realChange = false;

        ZipFile zipFile1 = null;
        ZipFile zipFile2 = null;

        try {
            zipFile1 = new ZipFile(warFile1);
            zipFile2 = new ZipFile(warFile2);

            for (Map.Entry<String, ZipArchiveEntry[]> entry : changed.entrySet()) {
                ZipArchiveEntry[] zipArchiveEntries = entry.getValue();

                ZipArchiveEntry zipArchiveEntry1 = zipArchiveEntries[0];
                ZipArchiveEntry zipArchiveEntry2 = zipArchiveEntries[0];

                if (zipArchiveEntry1.isDirectory() && zipArchiveEntry2.isDirectory()
                        && (zipArchiveEntry1.getSize() == zipArchiveEntry2.getSize())
                        && (zipArchiveEntry1.getCompressedSize() <= 2)
                        && (zipArchiveEntry2.getCompressedSize() <= 2)) {

                    // Skip zipdiff bug

                    continue;
                }

                try (InputStream inputStream1 = zipFile1
                        .getInputStream(zipFile1.getEntry(zipArchiveEntry1.getName()));
                        InputStream inputStream2 = zipFile2
                                .getInputStream(zipFile2.getEntry(zipArchiveEntry2.getName()))) {

                    List<String> lines1 = StringTestUtil.readLines(inputStream1);
                    List<String> lines2 = StringTestUtil.readLines(inputStream2);

                    message.append(System.lineSeparator());

                    message.append("--- ");
                    message.append(zipArchiveEntry1.getName());
                    message.append(System.lineSeparator());

                    message.append("+++ ");
                    message.append(zipArchiveEntry2.getName());
                    message.append(System.lineSeparator());

                    Patch<String> diff = DiffUtils.diff(lines1, lines2);

                    for (Delta<String> delta : diff.getDeltas()) {
                        message.append('\t');
                        message.append(delta.getOriginal());
                        message.append(System.lineSeparator());

                        message.append('\t');
                        message.append(delta.getRevised());
                        message.append(System.lineSeparator());
                    }
                }

                realChange = true;

                break;
            }
        } finally {
            ZipFile.closeQuietly(zipFile1);
            ZipFile.closeQuietly(zipFile2);
        }
    } else {
        realChange = true;
    }

    Assert.assertFalse(message.toString(), realChange);
}

From source file:de.flapdoodle.embedmongo.extract.ZipExtractor.java

@Override
public void extract(RuntimeConfig runtime, File source, File destination, Pattern file) throws IOException {
    IProgressListener progressListener = runtime.getProgressListener();
    String progressLabel = "Extract " + source;
    progressListener.start(progressLabel);

    FileInputStream fin = new FileInputStream(source);
    BufferedInputStream in = new BufferedInputStream(fin);

    ZipArchiveInputStream zipIn = new ZipArchiveInputStream(in);
    try {/*  w  w  w .j  ava 2 s  . co  m*/
        ZipArchiveEntry entry;
        while ((entry = zipIn.getNextZipEntry()) != null) {
            if (file.matcher(entry.getName()).matches()) {
                //               System.out.println("File: " + entry.getName());
                if (zipIn.canReadEntryData(entry)) {
                    //                  System.out.println("Can Read: " + entry.getName());
                    long size = entry.getSize();
                    Files.write(zipIn, size, destination);
                    destination.setExecutable(true);
                    //                  System.out.println("DONE");
                    progressListener.done(progressLabel);
                }
                break;

            } else {
                //               System.out.println("SKIP File: " + entry.getName());
            }
        }

    } finally {
        zipIn.close();
    }

}

From source file:com.github.wolfdogs.kemono.util.resource.zip.ZipDirResource.java

public ZipDirResource(File file) throws IOException {
    this.zipFile = new ZipFile(file);

    initialize();//from w ww  .  j  a  v a2  s  . c o m

    Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
    while (entries.hasMoreElements()) {
        ZipArchiveEntry zipArchiveEntry = entries.nextElement();
        String entryPath = zipArchiveEntry.getName();

        createResource(entryPath, zipArchiveEntry);
    }
}

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

@Test
public void testShouldBeAbleToCreateCustomizedAndroidApplicationXML() throws Exception {
    SelendroidServerBuilder builder = getDefaultBuilder();
    builder.init(new DefaultAndroidApp(new File(APK_FILE)));
    builder.cleanUpPrebuildServer();/*  www  . j  av  a2  s  .c  om*/
    File file = builder.createAndAddCustomizedAndroidManifestToSelendroidServer();
    ZipFile zipFile = new ZipFile(file);
    ZipArchiveEntry entry = zipFile.getEntry("AndroidManifest.xml");
    Assert.assertEquals(entry.getName(), "AndroidManifest.xml");
    Assert.assertTrue("Expecting non empty AndroidManifest.xml file", entry.getSize() > 700);

    // Verify that apk is not yet signed
    CommandLine cmd = new CommandLine(AndroidSdk.aapt());
    cmd.addArgument("list", false);
    cmd.addArgument(builder.getSelendroidServer().getAbsolutePath(), false);

    String output = ShellCommand.exec(cmd);

    assertResultDoesNotContainFile(output, "META-INF/CERT.RSA");
    assertResultDoesNotContainFile(output, "META-INF/CERT.SF");
}

From source file:com.google.cloud.tools.managedcloudsdk.install.ZipExtractorProvider.java

@Override
public void extract(Path archive, Path destination, ProgressListener progressListener) throws IOException {

    progressListener.start("Extracting archive: " + archive.getFileName(), ProgressListener.UNKNOWN);

    String canonicalDestination = destination.toFile().getCanonicalPath();

    // Use ZipFile instead of ZipArchiveInputStream so that we can obtain file permissions
    // on unix-like systems via getUnixMode(). ZipArchiveInputStream doesn't have access to
    // all the zip file data and will return "0" for any call to getUnixMode().
    try (ZipFile zipFile = new ZipFile(archive.toFile())) {
        // TextProgressBar progressBar = textBarFactory.newProgressBar(messageListener, count);
        Enumeration<ZipArchiveEntry> zipEntries = zipFile.getEntries();
        while (zipEntries.hasMoreElements()) {
            ZipArchiveEntry entry = zipEntries.nextElement();
            Path entryTarget = destination.resolve(entry.getName());

            String canonicalTarget = entryTarget.toFile().getCanonicalPath();
            if (!canonicalTarget.startsWith(canonicalDestination + File.separator)) {
                throw new IOException("Blocked unzipping files outside destination: " + entry.getName());
            }//from www  . j  a  va  2 s.c  o  m

            progressListener.update(1);
            logger.fine(entryTarget.toString());

            if (entry.isDirectory()) {
                if (!Files.exists(entryTarget)) {
                    Files.createDirectories(entryTarget);
                }
            } else {
                if (!Files.exists(entryTarget.getParent())) {
                    Files.createDirectories(entryTarget.getParent());
                }
                try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(entryTarget))) {
                    try (InputStream in = zipFile.getInputStream(entry)) {
                        IOUtils.copy(in, out);
                        PosixFileAttributeView attributeView = Files.getFileAttributeView(entryTarget,
                                PosixFileAttributeView.class);
                        if (attributeView != null) {
                            attributeView
                                    .setPermissions(PosixUtil.getPosixFilePermissions(entry.getUnixMode()));
                        }
                    }
                }
            }
        }
    }
    progressListener.done();
}