View Javadoc
1   /*
2    * Copyright (C) 2026 B3Partners B.V.
3    *
4    * SPDX-License-Identifier: MIT
5    */
6   package org.tailormap.api.service;
7   
8   import java.io.File;
9   import java.io.IOException;
10  import java.lang.invoke.MethodHandles;
11  import java.nio.file.Files;
12  import java.nio.file.Path;
13  import java.util.stream.Stream;
14  import java.util.zip.ZipEntry;
15  import java.util.zip.ZipOutputStream;
16  import org.slf4j.Logger;
17  import org.slf4j.LoggerFactory;
18  import org.springframework.stereotype.Service;
19  
20  /** Service for zipping directories and other useful operations concerning zip files. */
21  @Service
22  public class ZipService {
23    private static final Logger logger =
24        LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
25    /**
26     * Zips the contents of a directory into a zip file.
27     *
28     * @param sourceDir the directory to zip
29     * @param zipFile the resulting zip file
30     * @throws IOException if an I/O error occurs
31     */
32    public void zipDirectory(Path sourceDir, Path zipFile) throws IOException {
33      try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(zipFile));
34          Stream<Path> pathStream = Files.walk(sourceDir)) {
35        pathStream.filter(Files::isRegularFile).forEach(path -> {
36          String entryName = sourceDir.relativize(path).toString().replace(File.separatorChar, '/');
37          try {
38            logger.trace("Adding file {} to zip {}", path, zipFile);
39            zos.putNextEntry(new ZipEntry(entryName));
40            Files.copy(path, zos);
41            zos.closeEntry();
42          } catch (IOException e) {
43            throw new RuntimeException("Failed to add file to zip: " + path, e);
44          }
45        });
46      } catch (RuntimeException e) {
47        if (e.getCause() instanceof IOException ioException) {
48          throw ioException;
49        }
50        throw e;
51      }
52    }
53  }