Java Code Examples for org.zeroturnaround.zip.ZipUtil#unpack()

The following examples show how to use org.zeroturnaround.zip.ZipUtil#unpack() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HtmlFolder.java    From olca-app with Mozilla Public License 2.0 6 votes vote down vote up
private static void extractFolder(Bundle bundle, String zipPath)
		throws Exception {
	File dir = getDir(bundle);
	if (dir.exists())
		FileUtils.deleteDirectory(dir);
	dir.mkdirs();
	writeVersion(bundle);
	InputStream zipStream = FileLocator.openStream(bundle,
			new Path(zipPath), false);
	File zipFile = new File(dir, "@temp.zip");
	try (FileOutputStream out = new FileOutputStream(zipFile)) {
		IOUtils.copy(zipStream, out);
	}
	ZipUtil.unpack(zipFile, dir);
	if (!zipFile.delete())
		zipFile.deleteOnExit();
}
 
Example 2
Source File: ResourceFolderTest.java    From selenium-grid-extensions with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldZipExternalResources_HierarchicalFolderCase() {
    ResourceFolder uploadFolder = new ResourceFolder("hierarchy");
    File file = uploadFolder.toZip();

    File tempDir = Files.createTempDir();
    ZipUtil.unpack(file, tempDir);

    verifyFilesInZip(tempDir,
            "hierarchy/level0.txt",
            "hierarchy/level1",
            "hierarchy/level1/level1.txt",
            "hierarchy/level1/level2",
            "hierarchy/level1/level2/level2.txt",
            "hierarchy/level1.1/level1.1.txt",
            "hierarchy/level1.1/level2.2",
            "hierarchy/level1.1/level2.2/level2.2.txt");
}
 
Example 3
Source File: ResourceFolderTest.java    From selenium-grid-extensions with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldZipLocalResources() {
    ResourceFolder uploadFolder = new ResourceFolder("upload");
    File file = uploadFolder.toZip();

    File tempDir = Files.createTempDir();
    ZipUtil.unpack(file, tempDir);

    verifyFilesInZip(tempDir,
            "upload",
            "upload/first.txt",
            "upload/directory",
            "upload/directory/second.txt",
            "upload/directory/dir",
            "upload/directory/dir/third.txt");
}
 
Example 4
Source File: DbImportWizard.java    From olca-app with Mozilla Public License 2.0 5 votes vote down vote up
private IDatabase connectToFolder() {
	File zipFile = config.file;
	File tempDir = new File(System.getProperty("java.io.tmpdir"));
	tempDbFolder = new File(tempDir, UUID.randomUUID().toString());
	tempDbFolder.mkdirs();
	log.trace("unpack zolca file to {}", tempDbFolder);
	ZipUtil.unpack(zipFile, tempDbFolder);
	return new DerbyDatabase(tempDbFolder);
}
 
Example 5
Source File: DockerAirGapCreator.java    From synopsys-detect with Apache License 2.0 5 votes vote down vote up
public void installDockerDependencies(final File dockerFolder) throws DetectUserFriendlyException {
    try {
        final File dockerZip = dockerInspectorInstaller.installAirGap(dockerFolder);
        ZipUtil.unpack(dockerZip, dockerFolder);
        FileUtils.deleteQuietly(dockerZip);
    } catch (final IntegrationException | IOException e) {
        throw new DetectUserFriendlyException("An error occurred installing docker inspector.", e, ExitCodeType.FAILURE_GENERAL_ERROR);
    }
}
 
Example 6
Source File: Python.java    From olca-app with Mozilla Public License 2.0 5 votes vote down vote up
/** Extract the Python library in the workspace folder. */
private static synchronized void initFolder(File pyDir) {
	try {

		// check if the Python folder is tagged with the
		// current application version
		File versionFile = new File(pyDir, ".version");
		if (versionFile.exists()) {
			byte[] bytes = Files.readAllBytes(versionFile.toPath());
			String v = new String(bytes, "utf-8");
			if (Objects.equals(v, App.getVersion()))
				return;
		}

		// replace it with the current version of the
		// packed Python (Jython) library
		if (pyDir.exists()) {
			FileUtils.deleteDirectory(pyDir);
		}
		pyDir.mkdirs();
		String pyJar = "libs/jython-standalone-2.7.2b2.jar";
		try (InputStream is = RcpActivator.getStream(pyJar)) {
			ZipUtil.unpack(is, pyDir, (entry) -> {
				if (entry.startsWith("Lib/") && entry.length() > 4) {
					return entry.substring(4);
				} else {
					return null;
				}
			});
		}
		File file = new File(pyDir, ".version");
		Files.write(file.toPath(), App.getVersion().getBytes("utf-8"));
	} catch (Exception e) {
		Logger log = LoggerFactory.getLogger(Python.class);
		log.error("failed to initialize Python folder " + pyDir, e);
	}
}
 
Example 7
Source File: ZipFileUtil.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Unzips a zipfile into the directory it resides in.
 *
 * @param file the zipfile to unzip
 * @param nameMapper the {@link NameMapper} to use when unzipping
 * @return List of Files that got extracted
 * @throws UnzipException if something went wrong
 */
private static List<File> unzip(File file, NameMapper nameMapper) {
  try {
    File parentFile = file.getParentFile();
    TrackingNameMapper trackingNameMapper = new TrackingNameMapper(parentFile, nameMapper);
    ZipUtil.unpack(file, parentFile, trackingNameMapper);
    return trackingNameMapper.getFiles();
  } catch (Exception ex) {
    throw new UnzipException(ex);
  }
}
 
Example 8
Source File: ZipFileUtil.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void unzip(InputStream is, File outputDir) {
  try {
    ZipUtil.unpack(is, outputDir);
  } catch (Exception ex) {
    throw new UnzipException(ex);
  }
}
 
Example 9
Source File: ResourceUploadRequestTest.java    From selenium-grid-extensions with Apache License 2.0 5 votes vote down vote up
private Answer verifyRequestContent() {
    return new Answer() {
        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            HttpServletRequest req = (HttpServletRequest) invocationOnMock.getArguments()[0];
            HttpServletResponse resp = (HttpServletResponse) invocationOnMock.getArguments()[1];

            File tempFile = File.createTempFile("temp_resources", ".zip");
            try (ServletInputStream inputStream = req.getInputStream();
                 OutputStream outputStream = new FileOutputStream(tempFile)) {
                IOUtils.copy(inputStream, outputStream);
            }
            File tempDir = Files.createTempDir();
            ZipUtil.unpack(tempFile, tempDir);

            File firstTxtFile = new File(tempDir, "files_for_upload/first.txt");
            File secondTxtFile = new File(tempDir, "files_for_upload/directory/second.txt");

            assertTrue(firstTxtFile.exists());
            assertTrue(secondTxtFile.exists());

            //verify content
            String firstFileContent = Files.toString(firstTxtFile, Charset.defaultCharset());
            assertThat(firstFileContent, containsString("content1"));
            String secondFileContent = Files.toString(secondTxtFile, Charset.defaultCharset());
            assertThat(secondFileContent, containsString("content2"));

            //clean temp directories
            FileUtils.deleteDirectory(tempDir);
            assertTrue("Failed to delete uploaded zip", tempFile.delete());


            //form response
            resp.getWriter().write(EXPECTED_RETURN_FOLDER);
            return null;
        }
    };
}
 
Example 10
Source File: ResourceFolderTest.java    From selenium-grid-extensions with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldZipExternalResources_FlatFolderCase() {
    ResourceFolder uploadFolder = new ResourceFolder("flat");
    File file = uploadFolder.toZip();

    File tempDir = Files.createTempDir();
    ZipUtil.unpack(file, tempDir);

    verifyFilesInZip(tempDir,
            "flat",
            "flat/flat1.txt",
            "flat/flat2.txt",
            "flat/flat3.txt");
}
 
Example 11
Source File: Unzipper.java    From bonita-ui-designer with GNU General Public License v2.0 5 votes vote down vote up
public Path unzipInTempDir(InputStream is, String tempDirPrefix) throws IOException {
    Path tempDirectory = Files.createTempDirectory(temporaryZipPath, tempDirPrefix);
    Path zipFile = writeInDir(is, tempDirectory);
    try {
        ZipUtil.unpack(zipFile.toFile(), tempDirectory.toFile());
    } catch (org.zeroturnaround.zip.ZipException e) {
        throw new ZipException(e.getMessage());
    } finally {
        FileUtils.deleteQuietly(zipFile.toFile());
    }
    return tempDirectory;
}
 
Example 12
Source File: SkipperPackageUtils.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
public static Package loadPackageFromBytes(ArgumentCaptor<UploadRequest> uploadRequestCaptor) throws IOException {
	PackageReader packageReader = new DefaultPackageReader();
	String packageName = uploadRequestCaptor.getValue().getName();
	String packageVersion = uploadRequestCaptor.getValue().getVersion();
	byte[] packageBytes = uploadRequestCaptor.getValue().getPackageFileAsBytes();
	Path targetPath = TempFileUtils.createTempDirectory("service" + packageName);
	File targetFile = new File(targetPath.toFile(), packageName + "-" + packageVersion + ".zip");
	StreamUtils.copy(packageBytes, new FileOutputStream(targetFile));
	ZipUtil.unpack(targetFile, targetPath.toFile());
	return packageReader
			.read(new File(targetPath.toFile(), packageName + "-" + packageVersion));
}
 
Example 13
Source File: GithubHttp.java    From zest-writer with GNU General Public License v3.0 5 votes vote down vote up
public static File unzipOnlineContent(String zipFilePath, String destFolder) {
    String dirname = Paths.get(zipFilePath).getFileName().toString();
    dirname = dirname.substring(0, dirname.length() - 4);
    // create output directory is not exists
    File folder = new File(destFolder + File.separator + dirname);
    log.debug("Tentative de dezippage de " + zipFilePath + " dans " + folder.getAbsolutePath());
    if (!folder.exists()) {
        folder.mkdir();
        log.info("Dézippage dans " + folder.getAbsolutePath() + " réalisé avec succès");
    } else {
        log.debug("Le répertoire dans lequel vous souhaitez dezipper existe déjà ");
    }
    ZipUtil.unpack(new File(zipFilePath), folder);
    return folder;
}
 
Example 14
Source File: ZdsHttp.java    From zest-writer with GNU General Public License v3.0 5 votes vote down vote up
public static File unzipOnlineContent(String zipFilePath, String destFolder) {
    String dirname = Paths.get(zipFilePath).getFileName().toString();
    dirname = dirname.substring(0, dirname.length() - 4);
    // create output directory is not exists
    File folder = new File(destFolder + File.separator + dirname);
    log.debug("Tentative de dezippage de " + zipFilePath + " dans " + folder.getAbsolutePath());
    if (!folder.exists()) {
        folder.mkdir();
        log.info("Dézippage dans " + folder.getAbsolutePath() + " réalisé avec succès");
    } else {
        log.debug("Le répertoire dans lequel vous souhaitez dezipper existe déjà ");
    }
    ZipUtil.unpack(new File(zipFilePath), folder);
    return folder;
}
 
Example 15
Source File: PackageService.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
private Package deserializePackageFromDatabase(PackageMetadata packageMetadata) {
	// package file was uploaded to a local DB hosted repository
	Path tmpDirPath = null;
	try {
		tmpDirPath = TempFileUtils.createTempDirectory("skipper");
		File targetPath = new File(tmpDirPath + File.separator + packageMetadata.getName());
		targetPath.mkdirs();
		File targetFile = PackageFileUtils.calculatePackageZipFile(packageMetadata, targetPath);
		try {
			StreamUtils.copy(packageMetadata.getPackageFile().getPackageBytes(), new FileOutputStream(targetFile));
		}
		catch (IOException e) {
			throw new SkipperException(
					"Could not copy package file for " + packageMetadata.getName() + "-"
							+ packageMetadata.getVersion() +
							" from database to target file " + targetFile,
					e);
		}
		ZipUtil.unpack(targetFile, targetPath);
		Package pkgToReturn = this.packageReader.read(new File(targetPath, packageMetadata.getName() + "-" +
				packageMetadata.getVersion()));
		pkgToReturn.setMetadata(packageMetadata);
		return pkgToReturn;
	}
	finally {
		if (tmpDirPath != null && !FileSystemUtils.deleteRecursively(tmpDirPath.toFile())) {
			logger.warn("Temporary directory can not be deleted: " + tmpDirPath);
		}
	}
}
 
Example 16
Source File: ZipperTest.java    From bonita-ui-designer with GNU General Public License v2.0 4 votes vote down vote up
private Path unzip(ByteArrayOutputStream out) throws IOException {
    InputStream byteArrayInputStream = new ByteArrayInputStream(out.toByteArray());
    tmpDir = Files.createTempDirectory("testZip");
    ZipUtil.unpack(byteArrayInputStream, tmpDir.toFile());
    return tmpDir;
}
 
Example 17
Source File: Initializer.java    From griffin with Apache License 2.0 4 votes vote down vote up
private void unzipStructure(Path path) throws IOException {
    ZipUtil.unpack(new File(zipp + File.separator + "scaffold.zip"), path.toFile());
}
 
Example 18
Source File: Packr.java    From packr with Apache License 2.0 4 votes vote down vote up
private void copyAndMinimizeJRE(PackrOutput output, PackrConfig config) throws IOException {

		boolean extractToCache = config.cacheJre != null;
		boolean skipExtractToCache = false;

		// check if JRE extraction (and minimize) can be skipped
		if (extractToCache && config.cacheJre.exists()) {
			if (config.cacheJre.isDirectory()) {
				// check if the cache directory is empty
				String[] files = config.cacheJre.list();
				skipExtractToCache = files != null && files.length > 0;
			} else {
				throw new IOException(config.cacheJre + " must be a directory");
			}
		}

		// path to extract JRE to (cache, or target folder)
		File jreStoragePath = extractToCache ? config.cacheJre : output.resourcesFolder;

		if (skipExtractToCache) {
			System.out.println("Using cached JRE in '" + config.cacheJre + "' ...");
		} else {
			// path to extract JRE from (folder, zip or remote)
			boolean fetchFromRemote = config.jdk.startsWith("http://") || config.jdk.startsWith("https://");
			File jdkFile = fetchFromRemote ? new File(jreStoragePath, "jdk.zip") : new File(config.jdk);

			// download from remote
			if (fetchFromRemote) {
				System.out.println("Downloading JDK from '" + config.jdk + "' ...");
				try (InputStream remote = new URL(config.jdk).openStream()) {
					try (OutputStream outJdk = new FileOutputStream(jdkFile)) {
						IOUtils.copy(remote, outJdk);
					}
				}
			}

			// unpack JDK zip (or copy if it's a folder)
			System.out.println("Unpacking JRE ...");
			File tmp = new File(jreStoragePath, "tmp");
			if (tmp.exists()) {
				PackrFileUtils.deleteDirectory(tmp);
			}
			PackrFileUtils.mkdirs(tmp);

			if (jdkFile.isDirectory()) {
				PackrFileUtils.copyDirectory(jdkFile, tmp);
			} else {
				ZipUtil.unpack(jdkFile, tmp);
			}

			// copy the JRE sub folder
			File jre = searchJre(tmp);
			if (jre == null) {
				throw new IOException("Couldn't find JRE in JDK, see '" + tmp.getAbsolutePath() + "'");
			}

			PackrFileUtils.copyDirectory(jre, new File(jreStoragePath, "jre"));
			PackrFileUtils.deleteDirectory(tmp);

			if (fetchFromRemote) {
				PackrFileUtils.delete(jdkFile);
			}

			// run minimize
			PackrReduce.minimizeJre(jreStoragePath, config);
		}

		if (extractToCache) {
			// if cache is used, copy again here; if the JRE is cached already,
			// this is the only copy done (and everything above is skipped)
			PackrFileUtils.copyDirectory(jreStoragePath, output.resourcesFolder);
		}
	}
 
Example 19
Source File: ArchiveUtil.java    From elasticsearch-maven-plugin with Apache License 2.0 4 votes vote down vote up
public static void extractZip(File archiveFile, File targetDir) {
	ZipUtil.unpack(archiveFile, targetDir);
}
 
Example 20
Source File: PackageService.java    From spring-cloud-skipper with Apache License 2.0 4 votes vote down vote up
@Transactional
public PackageMetadata upload(UploadRequest uploadRequest) {
	validateUploadRequest(uploadRequest);
	Repository localRepositoryToUpload = getRepositoryToUpload(uploadRequest.getRepoName());
	Path packageDirPath = null;
	try {
		packageDirPath = TempFileUtils.createTempDirectory("skipperUpload");
		File packageDir = new File(packageDirPath + File.separator + uploadRequest.getName());
		packageDir.mkdir();
		Path packageFile = Paths
				.get(packageDir.getPath() + File.separator + uploadRequest.getName() + "-"
						+ uploadRequest.getVersion() + "." + uploadRequest.getExtension());
		Assert.isTrue(packageDir.exists(), "Package directory doesn't exist.");
		Files.write(packageFile, uploadRequest.getPackageFileAsBytes());
		ZipUtil.unpack(packageFile.toFile(), packageDir);
		String unzippedPath = packageDir.getAbsolutePath() + File.separator + uploadRequest.getName()
				+ "-" + uploadRequest.getVersion();
		File unpackagedFile = new File(unzippedPath);
		Assert.isTrue(unpackagedFile.exists(), "Package is expected to be unpacked, but it doesn't exist");
		Package packageToUpload = this.packageReader.read(unpackagedFile);
		PackageMetadata packageMetadata = packageToUpload.getMetadata();
		if (!packageMetadata.getName().equals(uploadRequest.getName())
				|| !packageMetadata.getVersion().equals(uploadRequest.getVersion())) {
			throw new SkipperException(String.format("Package definition in the request [%s:%s] " +
							"differs from one inside the package.yml [%s:%s]",
					uploadRequest.getName(), uploadRequest.getVersion(),
					packageMetadata.getName(), packageMetadata.getVersion()));
		}
		if (localRepositoryToUpload != null) {
			packageMetadata.setRepositoryId(localRepositoryToUpload.getId());
			packageMetadata.setRepositoryName(localRepositoryToUpload.getName());
		}
		packageMetadata.setPackageFile(new PackageFile((uploadRequest.getPackageFileAsBytes())));
		return this.packageMetadataRepository.save(packageMetadata);
	}
	catch (IOException e) {
		throw new SkipperException("Failed to upload the package.", e);
	}
	finally {
		if (packageDirPath != null && !FileSystemUtils.deleteRecursively(packageDirPath.toFile())) {
			logger.warn("Temporary directory can not be deleted: " + packageDirPath);
		}
	}
}