Java Code Examples for org.apache.commons.compress.archivers.zip.ZipFile

The following are top voted examples for showing how to use org.apache.commons.compress.archivers.zip.ZipFile. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: embedded-rabbitmq   File: BasicExtractor.java   View source code 9 votes vote down vote up
private void extractZip(ZipFile zipFile) {
  Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
  while (entries.hasMoreElements()) {

    ZipArchiveEntry entry = entries.nextElement();
    String fileName = entry.getName();
    File outputFile = new File(config.getExtractionFolder(), fileName);

    if (entry.isDirectory()) {
      makeDirectory(outputFile);
    } else {
      createNewFile(outputFile);
      try {
        InputStream inputStream = zipFile.getInputStream(entry);
        extractFile(inputStream, outputFile, fileName);
      } catch (IOException e) {
        throw new ExtractionException("Error extracting file '" + fileName + "' "
            + "from downloaded file: " + config.getDownloadTarget(), e);
      }
    }
  }
}
 
Example 2
Project: selenium-toys   File: AbstractDownloadingWebDriverFactory.java   View source code 6 votes vote down vote up
protected static void downloadZipAndExtract(final String url, final File targetDirectory) {
  download(url, inputStream -> {
    try {
      final byte[] bytes = IOUtils.toByteArray(inputStream);
      try (final ZipFile zipFile = new ZipFile(new SeekableInMemoryByteChannel(bytes))) {
        final Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        while (entries.hasMoreElements()) {
          final ZipArchiveEntry entry = entries.nextElement();
          final File file = new File(targetDirectory, entry.getName());
          if (entry.isDirectory()) {
            file.mkdir();
            continue;
          }
          try (final OutputStream outputStream =
              new BufferedOutputStream(new FileOutputStream(file))) {
            IOUtils.copy(zipFile.getInputStream(entry), outputStream);
          }
        }
      }
    } catch (final IOException exception) {
      throw new RuntimeException(exception);
    }
  });
}
 
Example 3
Project: personium-core   File: BarFileValidateTest.java   View source code 6 votes vote down vote up
/**
 * barファイル内エントリのファイルサイズ上限値を超えた場合に例外が発生すること.
 */
@Test
public void barファイル内エントリのファイルサイズ上限値を超えた場合に例外が発生すること() {
    TestBarInstaller testBarInstaller = new TestBarInstaller();
    URL fileUrl = ClassLoader.getSystemResource("requestData/barInstall/V1_1_2_bar_minimum.bar");
    File file = new File(fileUrl.getPath());

    try {
        ZipFile zipFile = new ZipFile(file, "UTF-8");
        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        long maxBarEntryFileSize = 0;
        while (entries.hasMoreElements()) {
            ZipArchiveEntry zae = entries.nextElement();
            if (zae.isDirectory()) {
                continue;
            }
            testBarInstaller.checkBarFileEntrySize(zae, zae.getName(), maxBarEntryFileSize);
        }
        fail("Unexpected exception");
    } catch (PersoniumCoreException dce) {
        String code = PersoniumCoreException.BarInstall.BAR_FILE_ENTRY_SIZE_TOO_LARGE.getCode();
        assertEquals(code, dce.getCode());
    } catch (Exception ex) {
        fail("Unexpected exception");
    }
}
 
Example 4
Project: Mod-Tools   File: ZipContentParser.java   View source code 6 votes vote down vote up
@Override
public List<ProcessTask> handle(EntityManager manager) throws Exception {
    if (!file.exists()) {
        return todo;
    }
    try (ZipFile zip = new ZipFile(file)) {
        for (ZipArchiveEntry entry : new IteratorIterable<>(new EnumerationIterator<>(zip.getEntries()))) {
            try {
                handleSingleZipEntry(zip, entry, manager);
            } catch (IOException ex) {
                System.out.println(ex.getLocalizedMessage());
            }
        }
    }
    return todo;
}
 
Example 5
Project: gradle-golang-plugin   File: ArchiveUtils.java   View source code 6 votes vote down vote up
public static void unZip(Path file, Path target) throws IOException {
    try (final ZipFile zipFile = new ZipFile(file.toFile())) {
        final Enumeration<ZipArchiveEntry> files = zipFile.getEntriesInPhysicalOrder();
        while (files.hasMoreElements()) {
            final ZipArchiveEntry entry = files.nextElement();
            final Path entryFile = target.resolve(REMOVE_LEADING_GO_PATH_PATTERN.matcher(entry.getName()).replaceFirst("")).toAbsolutePath();
            if (entry.isDirectory()) {
                createDirectoriesIfRequired(entryFile);
            } else {
                ensureParentOf(entryFile);
                try (final InputStream is = zipFile.getInputStream(entry)) {
                    try (final OutputStream os = newOutputStream(entryFile)) {
                        copy(is, os);
                    }
                }
            }
        }
    }
}
 
Example 6
Project: spring-boot   File: CompressExample.java   View source code 6 votes vote down vote up
/**
 * 把一个ZIP文件解压到一个指定的目录中
 * @param zipfilename ZIP文件抽象地址
 * @param outputdir 目录绝对地址
 */
public static void unZipToFolder(String zipfilename, String outputdir) throws IOException {
    File zipfile = new File(zipfilename);
    if (zipfile.exists()) {
        outputdir = outputdir + File.separator;
        FileUtils.forceMkdir(new File(outputdir));

        ZipFile zf = new ZipFile(zipfile, "UTF-8");
        Enumeration zipArchiveEntrys = zf.getEntries();
        while (zipArchiveEntrys.hasMoreElements()) {
            ZipArchiveEntry zipArchiveEntry = (ZipArchiveEntry) zipArchiveEntrys.nextElement();
            if (zipArchiveEntry.isDirectory()) {
                FileUtils.forceMkdir(new File(outputdir + zipArchiveEntry.getName() + File.separator));
            } else {
                IOUtils.copy(zf.getInputStream(zipArchiveEntry), FileUtils.openOutputStream(new File(outputdir + zipArchiveEntry.getName())));
            }
        }
    } else {
        throw new IOException("指定的解压文件不存在:\t" + zipfilename);
    }
}
 
Example 7
Project: parsec   File: ParsecInitTask.java   View source code 6 votes vote down vote up
/**
 * Extract Parsec Rdl Generator.
 *
 * @param rdlBinSuffix rdl bin suffix
 * @param generators the generator list
 * @throws IOException IOException
 */
void extractParsecRdlGenerator(final String rdlBinSuffix, final List<String> generators) throws IOException {
    final File file = fileUtils.getFileFromResource("/rdl-gen/rdl-gen.zip");

    for (String g: generators) {
        String generatorBinary = PathUtils.RDL_GEN_PARSEC_PREFIX + g;
        try (
                ZipFile zipFile = new ZipFile(file);
                InputStream inputStream = zipFile.getInputStream(
                        zipFile.getEntry(generatorBinary + "-" + rdlBinSuffix)
                )
        ) {
            fileUtils.writeResourceAsExecutable(inputStream, pathUtils.getBinPath() + "/" + generatorBinary);
        }
    }
}
 
Example 8
Project: excel-microservice   File: ExcelWriteControllerTest.java   View source code 6 votes vote down vote up
public List<String> getHashesFromZipFile(File file) throws IOException {
  List<String> hashes = new ArrayList<>();
  ZipFile zipFile = new ZipFile(file);

  byte[] buf = new byte[65536];
  Enumeration<?> entries = zipFile.getEntries();
  while (entries.hasMoreElements()) {
    ZipArchiveEntry zipArchiveEntry = (ZipArchiveEntry) entries.nextElement();
    int n;
    InputStream is = zipFile.getInputStream(zipArchiveEntry);
    ZipArchiveInputStream zis = new ZipArchiveInputStream(is);

    if (zis.canReadEntryData(zipArchiveEntry)) {
      while ((n = is.read(buf)) != -1) {
        if (n > 0) {
          hashes.add(DigestUtils.md5Hex(buf));
        }
      }
    }
    zis.close();
  }

  return hashes;
}
 
Example 9
Project: excel-microservice   File: FormulaCalculationTest.java   View source code 6 votes vote down vote up
public List<String> getHashesFromZipFile(File file) throws IOException {
  List<String> hashes = new ArrayList<>();
  ZipFile zipFile = new ZipFile(file);

  byte[] buf = new byte[65536];
  Enumeration<?> entries = zipFile.getEntries();
  while (entries.hasMoreElements()) {
    ZipArchiveEntry zipArchiveEntry = (ZipArchiveEntry) entries.nextElement();
    int n;
    InputStream is = zipFile.getInputStream(zipArchiveEntry);
    ZipArchiveInputStream zis = new ZipArchiveInputStream(is);

    if (zis.canReadEntryData(zipArchiveEntry)) {
      while ((n = is.read(buf)) != -1) {
        if (n > 0) {
          hashes.add(DigestUtils.md5Hex(buf));
        }
      }
    }
    zis.close();
  }

  return hashes;
}
 
Example 10
Project: gradle-mobile-plugin   File: ZipUtil.java   View source code 6 votes vote down vote up
private static void extract(ZipArchiveEntry zipArchiveEntry, ZipFile zipFile, File outputDir) throws IOException {
    File extractedFile = new File(outputDir, zipArchiveEntry.getName());
    FileUtils.forceMkdir(extractedFile.getParentFile());
    if (zipArchiveEntry.isUnixSymlink()) {
        if (PosixUtil.isPosixFileStore(outputDir)) {
            logger.debug("Extracting [l] "+zipArchiveEntry.getName());
            String symlinkTarget = zipFile.getUnixSymlink(zipArchiveEntry);
            Files.createSymbolicLink(extractedFile.toPath(), new File(symlinkTarget).toPath());
        } else {
            logger.debug("Skipping ! [l] "+zipArchiveEntry.getName());
        }
    } else if (zipArchiveEntry.isDirectory()) {
        logger.debug("Extracting [d] "+zipArchiveEntry.getName());
        FileUtils.forceMkdir(extractedFile);
    } else {
        logger.debug("Extracting [f] "+zipArchiveEntry.getName());
        try (
                InputStream in = zipFile.getInputStream(zipArchiveEntry);
                OutputStream out = new FileOutputStream(extractedFile)
        ) {
            IOUtils.copy(in, out);
        }
    }
    updatePermissions(extractedFile, zipArchiveEntry.getUnixMode());
}
 
Example 11
Project: gradle-mobile-plugin   File: ZipUtilTest.java   View source code 6 votes vote down vote up
private static List<String> getZipArchiveEntryNames(File sourceZip) throws IOException {
    List<String> content = new ArrayList<>();
    try (ZipFile zipFile = new ZipFile(sourceZip);) {
        List<ZipArchiveEntry> zipEntries = Collections.list(zipFile.getEntries());
        for (ZipArchiveEntry zipEntry : zipEntries) {
            if (zipEntry.isUnixSymlink()) {
                content.add("[l]"+zipEntry.getName());
            } else if (zipEntry.isDirectory()) {
                content.add("[d]"+zipEntry.getName());
            } else {
                content.add("[f]"+zipEntry.getName());
            }
        }
    }
    Collections.sort(content);
    return content;
}
 
Example 12
Project: aws-codepipeline-plugin-for-jenkins   File: ExtractionTools.java   View source code 6 votes vote down vote up
private static void extractZipFile(final File destination, final ZipFile zipFile) throws IOException {
    final Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();

    while (entries.hasMoreElements()) {
        final ZipArchiveEntry entry = entries.nextElement();
        final File entryDestination = new File(destination, entry.getName());

        if (entry.isDirectory()) {
            entryDestination.mkdirs();
        } else {
            entryDestination.getParentFile().mkdirs();
            final InputStream in = zipFile.getInputStream(entry);
            try (final OutputStream out = new FileOutputStream(entryDestination)) {
                IOUtils.copy(in, out);
                IOUtils.closeQuietly(in);
            }
        }
    }
}
 
Example 13
Project: javaxdelta   File: JarDeltaJarPatcherTest.java   View source code 6 votes vote down vote up
/**
 * Creates a zip file with random content.
 *
 * @author S3460
 * @param source the source
 * @return the zip file
 * @throws Exception the exception
 */
private ZipFile makeSourceZipFile(File source) throws Exception {
  ZipArchiveOutputStream out = new ZipArchiveOutputStream(new FileOutputStream(source));
  int size = randomSize(entryMaxSize);
  for (int i = 0; i < size; i++) {
    out.putArchiveEntry(new ZipArchiveEntry("zipentry" + i));
    int anz = randomSize(10);
    for (int j = 0; j < anz; j++) {
      byte[] bytes = getRandomBytes();
      out.write(bytes, 0, bytes.length);
    }
    out.flush();
    out.closeArchiveEntry();
  }
  //add leeres Entry
  out.putArchiveEntry(new ZipArchiveEntry("zipentry" + size));
  out.flush();
  out.closeArchiveEntry();
  out.flush();
  out.finish();
  out.close();
  return new ZipFile(source);
}
 
Example 14
Project: javaxdelta   File: JarDeltaJarPatcherTest.java   View source code 6 votes vote down vote up
/**
 * Writes a modified version of zip_Source into target.
 *
 * @author S3460
 * @param zipSource the zip source
 * @param target the target
 * @return the zip file
 * @throws Exception the exception
 */
private ZipFile makeTargetZipFile(ZipFile zipSource, File target) throws Exception {
  ZipArchiveOutputStream out = new ZipArchiveOutputStream(new FileOutputStream(target));
  for (Enumeration<ZipArchiveEntry> enumer = zipSource.getEntries(); enumer.hasMoreElements();) {
    ZipArchiveEntry sourceEntry = enumer.nextElement();
    out.putArchiveEntry(new ZipArchiveEntry(sourceEntry.getName()));
    byte[] oldBytes = toBytes(zipSource, sourceEntry);
    byte[] newBytes = getRandomBytes();
    byte[] mixedBytes = mixBytes(oldBytes, newBytes);
    out.write(mixedBytes, 0, mixedBytes.length);
    out.flush();
    out.closeArchiveEntry();
  }
  out.putArchiveEntry(new ZipArchiveEntry("zipentry" + entryMaxSize + 1));
  byte[] bytes = getRandomBytes();
  out.write(bytes, 0, bytes.length);
  out.flush();
  out.closeArchiveEntry();
  out.putArchiveEntry(new ZipArchiveEntry("zipentry" + (entryMaxSize + 2)));
  out.closeArchiveEntry();
  out.flush();
  out.finish();
  out.close();
  return new ZipFile(targetFile);
}
 
Example 15
Project: javaxdelta   File: JarDeltaJarPatcherTest.java   View source code 6 votes vote down vote up
/**
 * Compares the content of two zip files. The zip files are considered equal, if
 * the content of all zip entries is equal to the content of its corresponding entry
 * in the other zip file.
 *
 * @author S3460
 * @param zipSource the zip source
 * @param resultZip the result zip
 * @throws Exception the exception
 */
private void compareFiles(ZipFile zipSource, ZipFile resultZip) throws Exception {
  boolean rc = false;
  try {
    for (Enumeration<ZipArchiveEntry> enumer = zipSource.getEntries(); enumer.hasMoreElements();) {
      ZipArchiveEntry sourceEntry = enumer.nextElement();
      ZipArchiveEntry resultEntry = resultZip.getEntry(sourceEntry.getName());
      assertNotNull("Entry nicht generiert: " + sourceEntry.getName(), resultEntry);
      byte[] oldBytes = toBytes(zipSource, sourceEntry);
      byte[] newBytes = toBytes(resultZip, resultEntry);
      rc = equal(oldBytes, newBytes);
      assertTrue("bytes the same " + sourceEntry, rc);
    }
  } finally {
    zipSource.close();
    resultZip.close();
  }
}
 
Example 16
Project: javaxdelta   File: JarDeltaJarPatcherTest.java   View source code 6 votes vote down vote up
/**
 * Run jar patcher.
 *
 * @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));
  }
}
 
Example 17
Project: javaxdelta   File: JarDeltaJarPatcherTest.java   View source code 6 votes vote down vote up
/**
 * Tests JarDelta and JarPatcher on two identical files.
 *
 * @throws Exception the exception
 */
@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));
}
 
Example 18
Project: irplus   File: DefaultCollectionImportService.java   View source code 6 votes vote down vote up
/**
 * Add the primary picture to the collection.
 * 
 * @param primaryPicture
 * @param c
 * @param repository
 * @param zip
 */
private void addPrimaryPicture(String primaryPicture, InstitutionalCollection c, Repository repository, ZipFile zip)
{
	File f = new File(primaryPicture);
   	ZipArchiveEntry entry = zip.getEntry(primaryPicture);
   	zipHelper.getZipEntry(f, entry, zip);
       IrFile picture;
	try {
		picture = repositoryService.createIrFile(repository, f, primaryPicture, "primary news picture for collection id = " 
				+ c.getId());
		c.setPrimaryPicture(picture);
	} catch (IllegalFileSystemNameException e) {
		log.error(e);
	}
   	
	if( !FileUtils.deleteQuietly(f) )
	{
		log.error("file " + f + " not deleted");
	}
}
 
Example 19
Project: irplus   File: DefaultCollectionImportService.java   View source code 6 votes vote down vote up
/**
 * Add a single picture to the collection.
 * 
 * @param picture
 * @param c
 * @param repository
 * @param zip
 */
private void addPicture(String picture, InstitutionalCollection c, Repository repository, ZipFile zip)
{
	if( picture != null )
	{
	    File f = new File(picture);
   	    ZipArchiveEntry entry = zip.getEntry(picture);
    	    zipHelper.getZipEntry(f, entry, zip);
           IrFile thePicture;
	    try {
		    thePicture = repositoryService.createIrFile(repository, f, picture, "primary news picture for collection id = " 
				+ c.getId());
				c.addPicture(thePicture);
	    } catch (IllegalFileSystemNameException e) {
		    log.error(e);
	    }
   	
		if( !FileUtils.deleteQuietly(f) )
		{
			log.error("file " + f + " not deleted");
		}
	}
}
 
Example 20
Project: OCRaptor   File: IWorkPackageParser.java   View source code 6 votes vote down vote up
public static IWORKDocumentType detectType(ZipArchiveEntry entry,
    ZipFile zip) {
  try {
    if (entry == null) {
      return null;
    }

    InputStream stream = zip.getInputStream(entry);
    try {
      return detectType(stream);
    } finally {
      stream.close();
    }
  } catch (IOException e) {
    return null;
  }
}
 
Example 21
Project: OCRaptor   File: ZipContainerDetector.java   View source code 6 votes vote down vote up
/**
 * OpenDocument files, along with EPub files, have a mimetype
 *  entry in the root of their Zip file. This entry contains the
 *  mimetype of the overall file, stored as a single string.  
 */
private static MediaType detectOpenDocument(ZipFile zip) {
    try {
        ZipArchiveEntry mimetype = zip.getEntry("mimetype");
        if (mimetype != null) {
            InputStream stream = zip.getInputStream(mimetype);
            try {
                return MediaType.parse(IOUtils.toString(stream, "UTF-8"));
            } finally {
                stream.close();
            }
        } else {
            return null;
        }
    } catch (IOException e) {
        return null;
    }
}
 
Example 22
Project: OCRaptor   File: ZipContainerDetector.java   View source code 6 votes vote down vote up
private static MediaType detectIWork(ZipFile zip) {
    if (zip.getEntry(IWorkPackageParser.IWORK_COMMON_ENTRY) != null) {
        // Locate the appropriate index file entry, and reads from that
        // the root element of the document. That is used to the identify
        // the correct type of the keynote container.
        for (String entryName : IWorkPackageParser.IWORK_CONTENT_ENTRIES) {
           IWORKDocumentType type = IWORKDocumentType.detectType(zip.getEntry(entryName), zip); 
           if (type != null) {
              return type.getType();
           }
        }
        
        // Not sure, fallback to the container type
        return MediaType.application("vnd.apple.iwork");
    } else {
        return null;
    }
}
 
Example 23
Project: OCRaptor   File: ZipContainerDetector.java   View source code 6 votes vote down vote up
private static MediaType detectKmz(ZipFile zip) {
    boolean kmlFound = false;

    Enumeration<ZipArchiveEntry> entries = zip.getEntries();
    while (entries.hasMoreElements()) {
        ZipArchiveEntry entry = entries.nextElement();
        String name = entry.getName();
        if (!entry.isDirectory()
                && name.indexOf('/') == -1 && name.indexOf('\\') == -1) {
            if (name.endsWith(".kml") && !kmlFound) {
                kmlFound = true;
            } else {
                return null;
            }
        }
    }

    if (kmlFound) {
        return MediaType.application("vnd.google-earth.kmz");
    } else {
        return null;
    }
}
 
Example 24
Project: OCRaptor   File: ZipContainerDetector.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static MediaType detectIpa(ZipFile zip) {
    // Note - consider generalising this logic, if another format needs many regexp matching
    Set<Pattern> tmpPatterns = (Set<Pattern>)ipaEntryPatterns.clone();
    
    Enumeration<ZipArchiveEntry> entries = zip.getEntries();
    while (entries.hasMoreElements()) {
        ZipArchiveEntry entry = entries.nextElement();
        String name = entry.getName();
        
        Iterator<Pattern> ip = tmpPatterns.iterator();
        while (ip.hasNext()) {
            if (ip.next().matcher(name).matches()) {
                ip.remove();
            }
        }
        if (tmpPatterns.isEmpty()) {
            // We've found everything we need to find
            return MediaType.application("x-itunes-ipa");
        }
    }
    
    // If we get here, not all required entries were found
    return null;
}
 
Example 25
Project: xodus   File: BackupTests.java   View source code 6 votes vote down vote up
@SuppressWarnings("ResultOfMethodCallIgnored")
public static void extractEntireZip(@NotNull final File zip, @NotNull final File restoreDir) throws IOException {
    try (ZipFile zipFile = new ZipFile(zip)) {
        final Enumeration<ZipArchiveEntry> zipEntries = zipFile.getEntries();
        while (zipEntries.hasMoreElements()) {
            final ZipArchiveEntry zipEntry = zipEntries.nextElement();
            final File entryFile = new File(restoreDir, zipEntry.getName());
            if (zipEntry.isDirectory()) {
                entryFile.mkdirs();
            } else {
                entryFile.getParentFile().mkdirs();
                try (FileOutputStream target = new FileOutputStream(entryFile)) {
                    try (InputStream in = zipFile.getInputStream(zipEntry)) {
                        IOUtil.copyStreams(in, target, IOUtil.BUFFER_ALLOCATOR);
                    }
                }
            }
        }
    }
}
 
Example 26
Project: AGIA   File: ZipFilesTaskletTest.java   View source code 6 votes vote down vote up
@Test
public void testEmptyBaseDirRelativeDir() throws Exception {
    String aTargetFilename = "target/Z6-input.zip";
    ZipFilesTasklet aTasklet = new ZipFilesTasklet();
    aTasklet.setSourceBaseDirectory(new FileSystemResource(""));
    FileSystemResourcesFactory aSourceFactory = new FileSystemResourcesFactory();
    aSourceFactory.setPattern("file:src/test/resources/testFiles/input.csv");
    aTasklet.setSourceFactory(aSourceFactory );
    ExpressionResourceFactory aDestinationFactory = new ExpressionResourceFactory();
    aDestinationFactory.setExpression(aTargetFilename);
    aTasklet.setDestinationFactory(aDestinationFactory );
    
    assertEquals(RepeatStatus.FINISHED, aTasklet.execute(null, null));
    
    assertTrue(new File(aTargetFilename).exists());
    ZipFile aZipFile = new ZipFile(new File(aTargetFilename));
    Enumeration<ZipArchiveEntry> aEntries = aZipFile.getEntries();
    assertTrue(aEntries.hasMoreElements());
    assertEquals("src/test/resources/testFiles/input.csv", aEntries.nextElement().getName());
    assertFalse(aEntries.hasMoreElements());
    aZipFile.close();
}
 
Example 27
Project: jeffaschenk-commons   File: ArchiveUtility.java   View source code 6 votes vote down vote up
/**
 * Private Helper Method to Perform Extract of Compressed File with the Zip.
 *
 * @param zipFile
 * @param entry
 * @param outputDirectory
 * @throws java.io.IOException
 */
private static void extractZipEntry(ZipFile zipFile, ZipArchiveEntry entry, File outputDirectory)
        throws IOException {

    BufferedInputStream content = new BufferedInputStream(zipFile.getInputStream(entry), 16384);
    FileOutputStream fileOutputStream = new FileOutputStream(new File(outputDirectory + File.separator + entry.getName()));
    try {
        final byte[] buffer = new byte[16384];
        int n = 0;
        while (-1 != (n = content.read(buffer))) {
            fileOutputStream.write(buffer, 0, n);
        }

    } finally {
        content.close();
        fileOutputStream.flush();
        fileOutputStream.close();
    }
}
 
Example 28
Project: openmrs-module-owa   File: DefaultAppManager.java   View source code 6 votes vote down vote up
private void unzip(File file, String dest) throws IOException {
	try (ZipFile zip = new ZipFile(file)) {
		Enumeration<? extends ZipArchiveEntry> entries = zip.getEntries();
		while (entries.hasMoreElements()) {
			ZipArchiveEntry entry = entries.nextElement();
			File entryDestination = new File(dest, entry.getName());
			if (entry.isDirectory()) {
				entryDestination.mkdirs();
			} else {
				if (!entryDestination.getParentFile().exists()) {
					entryDestination.getParentFile().mkdirs();
				}
				try (InputStream in = zip.getInputStream(entry);
					OutputStream out = new FileOutputStream(entryDestination)) {
					IOUtils.copy(in, out);
				}
			}
		}
	}
}
 
Example 29
Project: buck-cutom   File: ProjectFilesystemTest.java   View source code 6 votes vote down vote up
@Test
public void testCreateZipPreservesExecutablePermissions() throws IOException {

  // Create a empty executable file.
  File exe = tmp.newFile("test.exe");
  exe.setExecutable(true);

  // Archive it into a zipfile using `ProjectFileSystem.createZip`.
  File zipFile = new File(tmp.getRoot().toPath().toString() + "/test.zip");
  filesystem.createZip(ImmutableList.of(exe.toPath()), zipFile);

  // Now unpack the archive (using apache's common-compress, as it preserves
  // executable permissions) and verify that the archive entry has executable
  // permissions.
  try (ZipFile zip = new ZipFile(zipFile)) {
    Enumeration<ZipArchiveEntry> entries = zip.getEntries();
    assertTrue(entries.hasMoreElements());
    ZipArchiveEntry entry = entries.nextElement();
    Set<PosixFilePermission> permissions =
        MorePosixFilePermissions.fromMode(entry.getExternalAttributes() >> 16);
    assertTrue(permissions.contains(PosixFilePermission.OWNER_EXECUTE));
    assertFalse(entries.hasMoreElements());
  }

}
 
Example 30
Project: eosgi-maven-plugin   File: FileManager.java   View source code 6 votes vote down vote up
private void unpackEntry(final File destFile, final ZipFile zipFile, final ZipArchiveEntry entry)
    throws IOException, ZipException {
  if (entry.isDirectory()) {
    touchedFiles.add(destFile);
    destFile.mkdirs();
  } else if (!isSameFile(destFile, entry.getSize(),
      entry.getLastModifiedDate().getTime())) {
    File parentFolder = destFile.getParentFile();
    parentFolder.mkdirs();
    InputStream inputStream = zipFile.getInputStream(entry);
    overCopyFile(Channels.newChannel(inputStream), entry.getSize(),
        entry.getLastModifiedDate().getTime(), destFile);
    FileManager.setPermissionsOnFile(destFile, entry);
  } else {
    touchedFiles.add(destFile);
  }
}
 
Example 31
Project: eosgi-maven-plugin   File: FileManager.java   View source code 6 votes vote down vote up
/**
 * Unpacks a ZIP file to the destination directory.
 *
 * @throws MojoExecutionException
 *           if something goes wrong during unpacking the files.
 */
public void unpackZipFile(final File file, final File destinationDirectory,
    final String... exclusions) {

  Set<String> exclusionSet = new HashSet<>(Arrays.asList(exclusions));

  try (ZipFile zipFile = new ZipFile(file)) {
    Enumeration<? extends ZipArchiveEntry> entries = zipFile.getEntries();
    while (entries.hasMoreElements()) {
      ZipArchiveEntry entry = entries.nextElement();
      String name = entry.getName();

      if (!exclusionSet.contains(name)) {
        File destFile = new File(destinationDirectory, entry.getName());
        unpackEntry(destFile, zipFile, entry);
      }
    }
  } catch (IOException e) {
    throw new UncheckedIOException("Could not uncompress distribution package file "
        + file.getAbsolutePath() + " to target folder " + destinationDirectory.getAbsolutePath(),
        e);
  }
}
 
Example 32
Project: buck   File: Unzip.java   View source code 6 votes vote down vote up
private void extractFile(
    ImmutableList.Builder<Path> filesWritten,
    ZipFile zip,
    DirectoryCreator creator,
    Path target,
    ZipArchiveEntry entry)
    throws IOException {
  ProjectFilesystem filesystem = creator.getFilesystem();
  if (filesystem.isFile(target, LinkOption.NOFOLLOW_LINKS)) { // NOPMD for clarity
    // pass
  } else if (filesystem.exists(target, LinkOption.NOFOLLOW_LINKS)) {
    filesystem.deleteRecursivelyIfExists(target);
  } else if (target.getParent() != null) {
    creator.forcefullyCreateDirs(target.getParent());
  }
  filesWritten.add(target);
  writeZipContents(zip, entry, filesystem, target);
}
 
Example 33
Project: buck   File: ZipRuleIntegrationTest.java   View source code 6 votes vote down vote up
@Test
public void shouldZipSources() throws IOException {
  ProjectWorkspace workspace =
      TestDataHelper.createProjectWorkspaceForScenario(this, "zip-rule", tmp);
  workspace.setUp();

  Path zip = workspace.buildAndReturnOutput("//example:ziptastic");

  // Make sure we have the right files and attributes.
  try (ZipFile zipFile = new ZipFile(zip.toFile())) {
    ZipArchiveEntry cake = zipFile.getEntry("cake.txt");
    assertThat(cake, Matchers.notNullValue());
    assertFalse(cake.isUnixSymlink());
    assertFalse(cake.isDirectory());

    ZipArchiveEntry beans = zipFile.getEntry("beans/");
    assertThat(beans, Matchers.notNullValue());
    assertFalse(beans.isUnixSymlink());
    assertTrue(beans.isDirectory());

    ZipArchiveEntry cheesy = zipFile.getEntry("beans/cheesy.txt");
    assertThat(cheesy, Matchers.notNullValue());
    assertFalse(cheesy.isUnixSymlink());
    assertFalse(cheesy.isDirectory());
  }
}
 
Example 34
Project: buck   File: ZipRuleIntegrationTest.java   View source code 6 votes vote down vote up
@Test
public void shouldFlattenZipsIfRequested() throws Exception {
  ProjectWorkspace workspace =
      TestDataHelper.createProjectWorkspaceForScenario(this, "zip-flatten", tmp);
  workspace.setUp();
  // Warm the cache
  Path zip = workspace.buildAndReturnOutput("//example:flatten");

  try (ZipFile zipFile = new ZipFile(zip.toFile())) {
    ZipArchiveEntry cake = zipFile.getEntry("cake.txt");
    assertThat(cake, Matchers.notNullValue());

    ZipArchiveEntry beans = zipFile.getEntry("beans.txt");
    assertThat(beans, Matchers.notNullValue());
  }
}
 
Example 35
Project: buck   File: ZipRuleIntegrationTest.java   View source code 6 votes vote down vote up
@Test
public void shouldNotMergeSourceJarsIfRequested() throws Exception {
  ProjectWorkspace workspace =
      TestDataHelper.createProjectWorkspaceForScenario(this, "zip-merge", tmp);
  workspace.setUp();

  Path zip = workspace.buildAndReturnOutput("//example:no-merge");

  // Gather expected file names
  Path sourceJar = workspace.buildAndReturnOutput("//example:cake#src");
  Path actualJar = workspace.buildAndReturnOutput("//example:cake");

  try (ZipFile zipFile = new ZipFile(zip.toFile())) {
    ZipArchiveEntry item = zipFile.getEntry(sourceJar.getFileName().toString());
    assertThat(item, Matchers.notNullValue());

    item = zipFile.getEntry(actualJar.getFileName().toString());
    assertThat(item, Matchers.notNullValue());

    item = zipFile.getEntry("cake.txt");
    assertThat(item, Matchers.notNullValue());
  }
}
 
Example 36
Project: buck   File: DefaultProjectFilesystemTest.java   View source code 6 votes vote down vote up
@Test
public void testCreateZipPreservesExecutablePermissions() throws IOException {

  // Create a empty executable file.
  Path exe = tmp.newFile("test.exe");
  MoreFiles.makeExecutable(exe);

  // Archive it into a zipfile using `Zip.create`.
  Path zipFile = tmp.getRoot().resolve("test.zip");
  Zip.create(filesystem, ImmutableList.of(exe), zipFile);

  // Now unpack the archive (using apache's common-compress, as it preserves
  // executable permissions) and verify that the archive entry has executable
  // permissions.
  try (ZipFile zip = new ZipFile(zipFile.toFile())) {
    Enumeration<ZipArchiveEntry> entries = zip.getEntries();
    assertTrue(entries.hasMoreElements());
    ZipArchiveEntry entry = entries.nextElement();
    Set<PosixFilePermission> permissions =
        MorePosixFilePermissions.fromMode(entry.getExternalAttributes() >> 16);
    assertTrue(permissions.contains(PosixFilePermission.OWNER_EXECUTE));
    assertFalse(entries.hasMoreElements());
  }
}
 
Example 37
Project: maps4cim   File: Compression.java   View source code 6 votes vote down vote up
/**
 * Reads the first file entry in a zip file and returns it's contents
 * as uncompressed byte-array
 * @param zipFile the zip file to read from
 * @return the first file entry (uncompressed)
 * @throws IOException if there is an error accessing the zip file
 */
public static byte[] readFirstZipEntry(File zipFile) throws IOException {
    // open zip
    ZipFile zf = new ZipFile(zipFile);
    Enumeration<ZipArchiveEntry> entries = zf.getEntries();

    // read first entry to byte[]
    ZipArchiveEntry entry = entries.nextElement();
    InputStream is = zf.getInputStream(entry);
    byte[] raw = ByteStreams.toByteArray(is);

    // close all streams and return byte[]
    is.close();
    zf.close();
    return raw;
}
 
Example 38
Project: maps4cim   File: Compression.java   View source code 6 votes vote down vote up
/**
 * Reads the first file entry in a zip file and writes it in uncompressed
 * form to the desired file.
 * @param zipFile the zip file to read from
 * @param dest the file to write the first zip file entry to
 * @return same as destination
 * @throws IOException if there is an error accessing the zip file or the
 * destination file
 */
public static File readFirstZipEntry(File zipFile, File dest) throws IOException {
    // open zip and get first entry
    ZipFile zf = new ZipFile(zipFile);
    Enumeration<ZipArchiveEntry> entries = zf.getEntries();
    ZipArchiveEntry entry = entries.nextElement();

    // write to file
    InputStream in = zf.getInputStream(entry);
    OutputStream out = new FileOutputStream(dest);
    ByteStreams.copy(in, out);

    // close all streams and return the new file
    in.close();
    out.close();
    zf.close();
    return dest;
}
 
Example 39
Project: selendroid   File: SelendroidServerBuilderTest.java   View source code 6 votes vote down vote up
@Test
public void testShouldBeAbleToCreateCustomizedAndroidApplicationXML() throws Exception {
  SelendroidServerBuilder builder = getDefaultBuilder();
  builder.init(new DefaultAndroidApp(new File(APK_FILE)));
  builder.cleanUpPrebuildServer();
  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");
}
 
Example 40
Project: alfresco-repository   File: ACPImportPackageHandler.java   View source code 5 votes vote down vote up
public void startImport()
{
    log("Importing from zip file " + file.getAbsolutePath());
    try
    {
        // NOTE: This encoding allows us to workaround bug...
        //       http://bugs.sun.com/bugdatabase/view_bug.do;:WuuT?bug_id=4820807
        zipFile = new ZipFile(file, "UTF-8");
    }
    catch(IOException e)
    {
        throw new ImporterException("Failed to read zip file due to " + e.getMessage(), e);
    }
}