org.zeroturnaround.zip.ZipUtil Java Examples

The following examples show how to use org.zeroturnaround.zip.ZipUtil. 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: MySQLDatabaseExport.java    From olca-app with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public void run() {
	try {
		IDatabase sourceDb = config.createInstance();
		DerbyDatabase targetDb = createTemporaryDb();
		DatabaseImport io = new DatabaseImport(sourceDb, targetDb);
		io.run();
		sourceDb.close();
		targetDb.close();
		ZipUtil.pack(targetDb.getDatabaseDirectory(), zolcaFile);
		FileUtils.deleteDirectory(targetDb.getDatabaseDirectory());
		success = true;
	} catch (Exception e) {
		success = false;
		log.error("failed export MySQL database as zolca-File", e);
	}
}
 
Example #3
Source File: DbExportAction.java    From olca-app with Mozilla Public License 2.0 6 votes vote down vote up
private void realExport(IDatabaseConfiguration config, File zip, boolean active) {
	try {
		if (active)
			Database.close();
		if (config instanceof DerbyConfiguration) {
			File folder = DatabaseDir.getRootFolder(config.getName());
			ZipEntrySource[] toPack = collectFileSources(folder);
			ZipUtil.pack(toPack, zip);
		} else if (config instanceof MySQLConfiguration) {
			MySQLDatabaseExport export = new MySQLDatabaseExport((MySQLConfiguration) config, zip);
			export.run();
		}
	} catch (Exception e) {
		log.error("Export failed " + zip, e);
	}
}
 
Example #4
Source File: Main.java    From Lukkit with MIT License 6 votes vote down vote up
private void zipOperation(ZipOperation operation, CommandSender sender, String[] args) {
    if (args[1] != null) {
        HashMap<String, LukkitPlugin> plugins = new HashMap<>();
        this.iteratePlugins(p -> plugins.put(p.getName().toLowerCase(), p));

        LukkitPlugin plugin = plugins.get(args[1]);

        if (plugin != null) {
            if ((operation == ZipOperation.PACKAGE) == plugin.isDevPlugin()) {
                if (operation == ZipOperation.PACKAGE) {
                    ZipUtil.unexplode(plugin.getFile());
                    sender.sendMessage(ChatColor.GREEN + "Successfully packed " + plugin.getName());
                } else {
                    ZipUtil.explode(plugin.getFile());
                    sender.sendMessage(ChatColor.GREEN + "Successfully unpacked " + plugin.getName());
                }
            } else {
                sender.sendMessage("The specified plugin \"" + plugin.getName() + "\" is already " + ((operation == ZipOperation.PACKAGE) ? "packaged" : "unpacked") + ".");
            }
        } else {
            sender.sendMessage("The specified plugin \"" + args[1] + "\" does not exist.");
        }
    } else {
        sender.sendMessage("You didn't specify a plugin to " + ((operation == ZipOperation.PACKAGE) ? "package" : "unpack") + "!");
    }
}
 
Example #5
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 #6
Source File: DefaultPackageWriter.java    From spring-cloud-skipper with Apache License 2.0 6 votes vote down vote up
@Override
public File write(Package pkg, File targetDirectory) {
	PackageMetadata packageMetadata = pkg.getMetadata();
	File tmpDir = TempFileUtils.createTempDirectory("skipper" + packageMetadata.getName()).toFile();
	File rootPackageDir = new File(tmpDir,
			String.format("%s-%s", packageMetadata.getName(), packageMetadata.getVersion()));
	rootPackageDir.mkdir();
	writePackage(pkg, rootPackageDir);
	if (!pkg.getDependencies().isEmpty()) {
		File packagesDir = new File(rootPackageDir, "packages");
		packagesDir.mkdir();
		for (Package dependencyPkg : pkg.getDependencies()) {
			File packageDir = new File(packagesDir, dependencyPkg.getMetadata().getName());
			packageDir.mkdir();
			writePackage(dependencyPkg, packageDir);
		}
	}
	File targetZipFile = PackageFileUtils.calculatePackageZipFile(pkg.getMetadata(), targetDirectory);
	ZipUtil.pack(rootPackageDir, targetZipFile, true);
	FileSystemUtils.deleteRecursively(tmpDir);
	return targetZipFile;
}
 
Example #7
Source File: DownloadContentService.java    From zest-writer with GNU General Public License v3.0 6 votes vote down vote up
public Map<String, List<Map<File, String>>> compareOfflineAndOnline(String onlineZipPath, String offlineDirPath) {

        File existFolder = new File(offlineDirPath);
        if (!existFolder.exists()) {
            return null;
        }
        Map<String, List<Map<File,String>>> result = new HashMap<>();
        result.put("update", new ArrayList<>());
        result.put("add", new ArrayList<>());
        ZipUtil.iterate(new File(onlineZipPath), new ZipEntryCallback() {
            @Override
            public void process(InputStream in, ZipEntry zipEntry) throws IOException {
                File fileOffline = new File(existFolder,zipEntry.getName());
                if(fileOffline.exists()) { // file for merge
                    if(zipEntry.getCrc() != getCrc(fileOffline.getAbsolutePath())) {
                        result.get("update").add(inputToMapping(in, fileOffline));
                    }
                } else { // file for add
                    result.get("add").add(inputToMapping(in, fileOffline));
                }
            }
        });
        return result;
    }
 
Example #8
Source File: ArchiveService.java    From difido-reports with Apache License 2.0 6 votes vote down vote up
/**
 * Archive to ZIP the HTML reports folder of the specified execution.
 * 
 * @param metadata
 * @return Path to temporary file contains the archived HTML reports or null
 *         if problem occurred
 */
public java.nio.file.Path archiveReports(final ExecutionMetadata metadata) {
	final File source = getExecutionFolder(metadata);
	if (!source.exists()) {
		log.error("Report folder of execution " + metadata.getId() + " was not found");
		return null;
	}
	File destination = null;
	try {
		destination = File.createTempFile("execution" + metadata.getId() + "_", ".zip");
	} catch (IOException e) {
		log.error("Failed to create temp file", e);
		return null;
	}
	ZipUtil.pack(source, destination);
	log.debug("Temporary file with report of execution " + metadata.getId() + " was created in "
			+ destination.getAbsolutePath());
	final java.nio.file.Path destinationPath = destination.toPath();
	return destinationPath;
}
 
Example #9
Source File: MSDeployArtifactHandlerImpl.java    From azure-gradle-plugins with MIT License 6 votes vote down vote up
private File createZipPackage() throws Exception {
    logInfo("");
    logInfo(CREATE_ZIP_START);

    final String stageDirectoryPath = functionsTask.getDeploymentStageDirectory();
    final File stageDirectory = new File(stageDirectoryPath);
    final File zipPackage = new File(stageDirectoryPath.concat(ZIP_EXT));

    if (!stageDirectory.exists()) {
        String errorMessage = String.format(STAGE_DIR_NOT_FOUND, stageDirectoryPath);
        logError(STAGE_DIR_NOT_FOUND);
        throw new Exception(STAGE_DIR_NOT_FOUND);
    }

    ZipUtil.pack(stageDirectory, zipPackage);

    logDebug(REMOVE_LOCAL_SETTINGS);
    ZipUtil.removeEntry(zipPackage, LOCAL_SETTINGS_FILE);

    logInfo(CREATE_ZIP_DONE + stageDirectoryPath.concat(ZIP_EXT));
    return zipPackage;
}
 
Example #10
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 #11
Source File: AbstractRunMojo.java    From alfresco-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Package customized war file and install it in local maven repo.
 *
 * @param warName the name of the custom war
 * @return the customized war file artifactId, to be used by the tomcat7 plugin
 * @throws MojoExecutionException when any problem appears packaging or installing the custom war
 */
protected String packageAndInstallCustomWar(String warName) throws MojoExecutionException {
    final String warArtifactId = "${project.artifactId}-" + warName;
    final String warSourceDir = getWarOutputDir(warName);

    // Package the customized war file
    // Note. don't use the maven-war-plugin here as it will package the module files twice, once from the
    // target/classes dir and once via the JAR
    String warPath = project.getBuild().getDirectory() + "/" + warName + ".war";
    ZipUtil.pack(new File(warSourceDir), new File(warPath));

    // Install the customized war file in the local maven repo
    executeMojo(
            plugin(
                    groupId("org.apache.maven.plugins"),
                    artifactId("maven-install-plugin"),
                    version(MAVEN_INSTALL_PLUGIN_VERSION)
            ),
            goal("install-file"),
            configuration(
                    element(name("file"), warPath),
                    element(name("groupId"), "${project.groupId}"),
                    element(name("artifactId"), warArtifactId),
                    element(name("version"), "${project.version}"),
                    element(name("packaging"), "war") // Don't forget, otherwise installed as .POM
            )
            , execEnv
    );

    return warArtifactId;
}
 
Example #12
Source File: PatchSplitter.java    From OptiFabric with Mozilla Public License 2.0 5 votes vote down vote up
public static ClassCache generateClassCache(File inputFile, File classCacheOutput, byte[] inputHash) throws IOException {
	boolean extractClasses = Boolean.parseBoolean(System.getProperty("optifabric.extract", "false"));
	File classesDir = new File(classCacheOutput.getParent(), "classes");
	if(extractClasses){
		classesDir.mkdir();
	}
	ClassCache classCache = new ClassCache(inputHash);
	try (JarFile jarFile = new JarFile(inputFile)) {
		Enumeration<JarEntry> entrys = jarFile.entries();
		while (entrys.hasMoreElements()) {
			JarEntry entry = entrys.nextElement();
			if ((entry.getName().startsWith("net/minecraft/") || entry.getName().startsWith("com/mojang/")) && entry.getName().endsWith(".class")) {
				try(InputStream inputStream = jarFile.getInputStream(entry)){
					String name = entry.getName();
					byte[] bytes = IOUtils.toByteArray(inputStream);
					classCache.addClass(name, bytes);
					if(extractClasses){
						File classFile = new File(classesDir, entry.getName());
						FileUtils.writeByteArrayToFile(classFile, bytes);
					}
				}
			}
		}
	}


	//Remove all the classes that are going to be patched in, we dont want theses on the classpath
	ZipUtil.removeEntries(inputFile, classCache.getClasses().stream().toArray(String[]::new));

	System.out.println("Found " + classCache.getClasses().size() + " patched classes");
	classCache.save(classCacheOutput);
	return classCache;
}
 
Example #13
Source File: VFSZipperZIPTest.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testUnzipArchiveWithFileHierarchy() throws IOException {
    createFileHierarchy(temporaryPath);

    // Zips using third-party library that is tested and known to work as expected
    ZipUtil.pack(temporaryPath.toFile(), archivePath.toFile());

    testUnzip(outputPath);
}
 
Example #14
Source File: VFSZipperZIPTest.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
private void assertZipWithFileHierarchy(Path archivePath) {
    final int[] nbEntries = { 0 };

    // Reads ZIP content using a third-party library
    ZipUtil.iterate(archivePath.toFile(), new ZipEntryCallback() {
        @Override
        public void process(InputStream in, ZipEntry zipEntry) throws IOException {
            nbEntries[0]++;
        }
    });

    assertThat(nbEntries[0]).isEqualTo(HIERARCHY_DEPTH + 1);
}
 
Example #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
Source File: DbImportAction.java    From olca-app with Mozilla Public License 2.0 5 votes vote down vote up
private void realImport(File dbFolder, String dbName, File zip) {
	App.run(M.ImportDatabase, () -> {
		File folder = new File(dbFolder, dbName);
		folder.mkdirs();
		ZipUtil.unpack(zip, folder);
	}, () -> {
		DerbyConfiguration conf = new DerbyConfiguration();
		conf.setName(dbName);
		Database.register(conf);
		Navigator.refresh();
	});
}
 
Example #22
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 #23
Source File: ConfigChecker.java    From CombatLogX with GNU General Public License v3.0 5 votes vote down vote up
private void createBackup() {
    File pluginFolder = this.plugin.getDataFolder();
    Logger logger = this.plugin.getLogger();
    logger.info("Creating backup...");

    try {
        File pluginsFolder = pluginFolder.getParentFile();
        File backupFile = new File(pluginsFolder, "CombatLogX-backup-" + System.currentTimeMillis() + ".zip");
        ZipUtil.pack(pluginFolder, backupFile);
        deleteFiles(pluginFolder);
    } catch(Exception ex) {
        logger.log(Level.SEVERE, "An error occurred while creating a backup:", ex);
        logger.info("Failed to create backup.");
    }
}
 
Example #24
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 #25
Source File: QuarkusModelRegistry.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
public static void zip(String endpoint, String tool, String groupId, String artifactId, String version,
                       String className, String path, QuarkusModel model, File output) throws IOException {
    Url url = Urls.newFromEncoded(endpoint + "/api/download");
    Map<String, String> parameters = new HashMap<>();
    parameters.put(CODE_TOOL_PARAMETER_NAME, tool);
    parameters.put(CODE_GROUP_ID_PARAMETER_NAME, groupId);
    parameters.put(CODE_ARTIFACT_ID_PARAMETER_NAME, artifactId);
    parameters.put(CODE_VERSION_PARAMETER_NAME, version);
    parameters.put(CODE_CLASSNAME_PARAMETER_NAME, className);
    parameters.put(CODE_PATH_PARAMETER_NAME, path);
    parameters.put(CODE_EXTENSIONS_SHORT_PARAMETER_NAME, model.getCategories().stream().flatMap(category -> category.getExtensions().stream()).
            filter(extension -> extension.isSelected() || extension.isDefaultExtension()).
            map(extension -> extension.getShortId()).
            collect(Collectors.joining(".")));
    url = url.addParameters(parameters);
    RequestBuilder builder = HttpRequests.request(url.toString()).userAgent(QuarkusModelRegistry.USER_AGENT).tuner(connection -> {
        connection.setRequestProperty(CODE_QUARKUS_IO_CLIENT_NAME_HEADER_NAME, CODE_QUARKUS_IO_CLIENT_NAME_HEADER_VALUE);
        connection.setRequestProperty(CODE_QUARKUS_IO_CLIENT_CONTACT_EMAIL_HEADER_NAME, CODE_QUARKUS_IO_CLIENT_CONTACT_EMAIL_HEADER_VALUE);
    });
    try {
        if (ApplicationManager.getApplication().executeOnPooledThread(() -> builder.connect(request -> {
            ZipUtil.unpack(request.getInputStream(), output, name -> {
                int index = name.indexOf('/');
                return name.substring(index);
            });
            return true;
        })).get() == null) {
            throw new IOException();
        }
} catch (InterruptedException | ExecutionException e) {
        throw new IOException(e);
    }
}
 
Example #26
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 #27
Source File: PackageWriterTests.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws IOException {
	PackageWriter packageWriter = new DefaultPackageWriter();
	Package pkgtoWrite = createSimplePackage();
	Path tempPath = Files.createTempDirectory("tests");
	File outputDirectory = tempPath.toFile();

	File zipFile = packageWriter.write(pkgtoWrite, outputDirectory);
	assertThat(zipFile).exists();
	assertThat(zipFile.getName()).isEqualTo("myapp-1.0.0.zip");
	final AtomicInteger processedEntries = new AtomicInteger(3);
	ZipUtil.iterate(zipFile, new ZipEntryCallback() {
		@Override
		public void process(InputStream inputStream, ZipEntry zipEntry) throws IOException {
			if (zipEntry.getName().equals("myapp-1.0.0/package.yml")) {
				assertExpectedContents(inputStream, "package.yml");
				processedEntries.decrementAndGet();
			}
			if (zipEntry.getName().equals("myapp-1.0.0/values.yml")) {
				assertExpectedContents(inputStream, "values.yml");
				processedEntries.decrementAndGet();
			}
			if (zipEntry.getName().equals("myapp-1.0.0/templates/myapp.yml")) {
				assertExpectedContents(inputStream, "generic-template.yml");
				processedEntries.decrementAndGet();
			}
		}
	});
	// make sure we asserted all fields
	assertThat(processedEntries.get()).isEqualTo(0);
}
 
Example #28
Source File: ZipArtifactHandlerImpl.java    From azure-gradle-plugins with MIT License 5 votes vote down vote up
protected File getZipFile() {
    final String stagingDirectoryPath = getDeploymentStagingDirectoryPath();
    final File zipFile = new File(stagingDirectoryPath + ".zip");
    final File stagingDirectory = new File(stagingDirectoryPath);

    ZipUtil.pack(stagingDirectory, zipFile);
    return zipFile;
}
 
Example #29
Source File: UploadContentService.java    From zest-writer with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Task<Void> createTask() {
    return new Task<Void>() {
        @Override
        protected Void call() throws Exception {
            if (MainApp.getZdsutils().isAuthenticated() && result.isPresent()) {
                String targetId = result.get().getValue().getId();
                String targetSlug = result.get().getValue().getSlug();

                String pathDir = content.getFilePath ();
                updateMessage(Configuration.getBundle().getString("ui.task.zip.label")+" : "+targetSlug+" "+Configuration.getBundle().getString("ui.task.pending.label")+" ...");
                ZipUtil.pack(new File(pathDir), new File(pathDir + ".zip"));
                updateMessage(Configuration.getBundle().getString("ui.task.import.label")+" : "+targetSlug+" "+Configuration.getBundle().getString("ui.task.pending.label")+" ...");
                if(result.get().getValue().getType() == null) {
                    if(!MainApp.getZdsutils().importNewContent(pathDir+ ".zip", result.get().getKey())) {
                        throw new IOException();
                    }
                } else {
                    if(!MainApp.getZdsutils().importContent(pathDir + ".zip", targetId, targetSlug, result.get().getKey())) {
                        throw new IOException();
                    }
                }

                updateMessage(Configuration.getBundle().getString("ui.task.content.sync")+" ...");
                try {
                    MainApp.getZdsutils().getContentListOnline().clear();
                    MainApp.getZdsutils().initInfoOnlineContent("tutorial");
                    MainApp.getZdsutils().initInfoOnlineContent("article");
                } catch (IOException e) {
                    logger.error("Echec de téléchargement des metadonnés des contenus en ligne", e);
                }
            }
            return null;
        }
    };
}
 
Example #30
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;
}