| /** |
| ******************************************************************************** |
| * Copyright (c) 2020, 2021 Robert Bosch GmbH. |
| * |
| * This program and the accompanying materials are made |
| * available under the terms of the Eclipse Public License 2.0 |
| * which is available at https://www.eclipse.org/legal/epl-2.0/ |
| * |
| * SPDX-License-Identifier: EPL-2.0 |
| * |
| * Contributors: |
| * Robert Bosch GmbH - initial API and implementation |
| ******************************************************************************** |
| */ |
| |
| package org.eclipse.app4mc.transformation.util; |
| |
| import java.io.IOException; |
| import java.nio.file.Files; |
| import java.nio.file.Path; |
| import java.nio.file.Paths; |
| import java.util.Collections; |
| import java.util.List; |
| import java.util.stream.Collectors; |
| import java.util.stream.Stream; |
| import java.util.zip.ZipEntry; |
| import java.util.zip.ZipOutputStream; |
| |
| import org.eclipse.app4mc.util.sessionlog.SessionLogger; |
| |
| public class FileHelper { |
| |
| // Suppress default constructor |
| private FileHelper() { |
| throw new IllegalStateException("Utility class"); |
| } |
| |
| public static void zipResult(String outputFolder, SessionLogger logger) throws IOException { |
| zipResult(outputFolder, Collections.emptyList(), logger); |
| } |
| |
| public static void zipResult(String outputFolder, List<Path> excludeDirs, SessionLogger logger) throws IOException { |
| |
| Path sourceDir = Paths.get(outputFolder); |
| List<Path> sourceFiles; |
| try (Stream<Path> filesStream = Files.walk(sourceDir)) { |
| sourceFiles = filesStream |
| .filter(path -> !Files.isDirectory(path)) |
| .filter(path -> !path.getFileName().startsWith(".")) |
| .filter(path -> !path.getFileName().endsWith("result.zip")) |
| .filter(path -> excludeDirs.stream().noneMatch(path::startsWith)) |
| .collect(Collectors.toList()); |
| } |
| |
| Path outputFile = Paths.get(outputFolder, "result.zip"); |
| if (Files.exists(outputFile)) { |
| Files.delete(outputFile); |
| } |
| Path zipFile = Files.createFile(outputFile); |
| |
| try (ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(zipFile))) { |
| for (Path path : sourceFiles) { |
| addFileToArchive(sourceDir, path, zipOutputStream, logger); |
| } |
| } catch (Exception e) { |
| logger.error("Failed to produce result zip archive", e); |
| } |
| } |
| |
| private static void addFileToArchive(Path sourceDir, Path file, ZipOutputStream zipOutputStream, SessionLogger logger) { |
| try { |
| ZipEntry zipEntry = new ZipEntry(sourceDir.relativize(file).toString()); |
| zipOutputStream.putNextEntry(zipEntry); |
| Files.copy(file, zipOutputStream); |
| zipOutputStream.closeEntry(); |
| } catch (IOException e) { |
| logger.error("Failed to include {0} to zip archive", file.getFileName(), e); |
| } |
| } |
| |
| } |