1 package org.openecomp.core.tools.util;
3 import com.google.common.io.ByteStreams;
4 import org.openecomp.sdc.logging.api.Logger;
5 import org.openecomp.sdc.logging.api.LoggerFactory;
8 import java.nio.file.Files;
9 import java.nio.file.Path;
10 import java.nio.file.Paths;
11 import java.util.zip.ZipEntry;
12 import java.util.zip.ZipException;
13 import java.util.zip.ZipInputStream;
14 import java.util.zip.ZipOutputStream;
16 public class ZipUtils {
18 private static final Logger logger = LoggerFactory.getLogger(ZipUtils.class);
21 // prevent instantiation
24 public static void createZip(String zipFileName, Path dir) throws IOException {
25 File dirObj = dir.toFile();
26 Path zippedFile = Files.createFile(Paths.get(zipFileName));
28 FileOutputStream fileOutputStream = new FileOutputStream(File.separator + zippedFile.toFile());
29 BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
30 ZipOutputStream out = new ZipOutputStream(bos)) {
31 File[] files = dirObj.listFiles();
32 for (File file : files) {
33 out.putNextEntry(new ZipEntry(file.getName()));
34 Files.copy(Paths.get(file.getPath()), out);
37 Utils.printMessage(logger, "Zip file was created " + zipFileName);
41 public static void unzip(Path zipFile, Path outputFolder) throws IOException {
42 if (zipFile == null || outputFolder == null) {
45 createDirectoryIfNotExists(outputFolder);
47 try (FileInputStream fileInputStream = new FileInputStream(zipFile.toFile());
48 ZipInputStream stream = new ZipInputStream(fileInputStream)) {
51 while ((entry = stream.getNextEntry()) != null) {
52 assertEntryNotVulnerable(entry);
53 String fileName = entry.getName();
54 File newFile = new File(outputFolder.toString() + File.separator + fileName);
55 if (entry.isDirectory()) {
56 createDirectoryIfNotExists(newFile.toPath());
58 persistFile(stream, newFile);
65 private static void persistFile(ZipInputStream stream, File newFile) throws IOException {
66 new File(newFile.getParent()).mkdirs();
67 try (FileOutputStream outputStream = new FileOutputStream(newFile)) {
68 ByteStreams.copy(stream, outputStream);
72 private static void createDirectoryIfNotExists(Path path) throws IOException {
73 if (!path.toFile().exists()) {
74 Files.createDirectories(path);
78 private static void assertEntryNotVulnerable(ZipEntry entry) throws ZipException {
79 if (entry.getName().contains("../")) {
80 throw new ZipException("Path traversal attempt discovered.");