1 /*
2  * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 package jdk.jpackage.internal;
26 
27 import java.io.IOException;
28 import java.nio.file.Files;
29 import java.nio.file.Path;
30 import java.util.ArrayList;
31 import java.util.Collection;
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.function.BiFunction;
36 import java.util.stream.Collectors;
37 import java.util.stream.Stream;
38 
39 
40 /**
41  * Group of paths.
42  * Each path in the group is assigned a unique id.
43  */
44 final class PathGroup {
PathGroup(Map<Object, Path> paths)45     PathGroup(Map<Object, Path> paths) {
46         entries = new HashMap<>(paths);
47     }
48 
getPath(Object id)49     Path getPath(Object id) {
50         if (id == null) {
51             throw new NullPointerException();
52         }
53         return entries.get(id);
54     }
55 
setPath(Object id, Path path)56     void setPath(Object id, Path path) {
57         if (path != null) {
58             entries.put(id, path);
59         } else {
60             entries.remove(id);
61         }
62     }
63 
64     /**
65      * All configured entries.
66      */
paths()67     List<Path> paths() {
68         return entries.values().stream().collect(Collectors.toList());
69     }
70 
71     /**
72      * Root entries.
73      */
roots()74     List<Path> roots() {
75         // Sort by the number of path components in ascending order.
76         List<Map.Entry<Path, Path>> sorted = normalizedPaths().stream().sorted(
77                 (a, b) -> a.getKey().getNameCount() - b.getKey().getNameCount()).collect(
78                         Collectors.toList());
79 
80         // Returns `true` if `a` is a parent of `b`
81         BiFunction<Map.Entry<Path, Path>, Map.Entry<Path, Path>, Boolean> isParentOrSelf = (a, b) -> {
82             return a == b || b.getKey().startsWith(a.getKey());
83         };
84 
85         return sorted.stream().filter(
86                 v -> v == sorted.stream().sequential().filter(
87                         v2 -> isParentOrSelf.apply(v2, v)).findFirst().get()).map(
88                         v -> v.getValue()).collect(Collectors.toList());
89     }
90 
sizeInBytes()91     long sizeInBytes() throws IOException {
92         long reply = 0;
93         for (Path dir : roots().stream().filter(f -> Files.isDirectory(f)).collect(
94                 Collectors.toList())) {
95             try (Stream<Path> stream = Files.walk(dir)) {
96                 reply += stream.filter(p -> Files.isRegularFile(p)).mapToLong(
97                         f -> f.toFile().length()).sum();
98             }
99         }
100         return reply;
101     }
102 
resolveAt(Path root)103     PathGroup resolveAt(Path root) {
104         return new PathGroup(entries.entrySet().stream().collect(
105                 Collectors.toMap(e -> e.getKey(),
106                         e -> root.resolve(e.getValue()))));
107     }
108 
copy(PathGroup dst)109     void copy(PathGroup dst) throws IOException {
110         copy(this, dst, null, false);
111     }
112 
move(PathGroup dst)113     void move(PathGroup dst) throws IOException {
114         copy(this, dst, null, true);
115     }
116 
transform(PathGroup dst, TransformHandler handler)117     void transform(PathGroup dst, TransformHandler handler) throws IOException {
118         copy(this, dst, handler, false);
119     }
120 
121     static interface Facade<T> {
pathGroup()122         PathGroup pathGroup();
123 
paths()124         default Collection<Path> paths() {
125             return pathGroup().paths();
126         }
127 
roots()128         default List<Path> roots() {
129             return pathGroup().roots();
130         }
131 
sizeInBytes()132         default long sizeInBytes() throws IOException {
133             return pathGroup().sizeInBytes();
134         }
135 
resolveAt(Path root)136         T resolveAt(Path root);
137 
copy(Facade<T> dst)138         default void copy(Facade<T> dst) throws IOException {
139             pathGroup().copy(dst.pathGroup());
140         }
141 
move(Facade<T> dst)142         default void move(Facade<T> dst) throws IOException {
143             pathGroup().move(dst.pathGroup());
144         }
145 
transform(Facade<T> dst, TransformHandler handler)146         default void transform(Facade<T> dst, TransformHandler handler) throws
147                 IOException {
148             pathGroup().transform(dst.pathGroup(), handler);
149         }
150     }
151 
152     static interface TransformHandler {
copyFile(Path src, Path dst)153         public void copyFile(Path src, Path dst) throws IOException;
createDirectory(Path dir)154         public void createDirectory(Path dir) throws IOException;
155     }
156 
copy(PathGroup src, PathGroup dst, TransformHandler handler, boolean move)157     private static void copy(PathGroup src, PathGroup dst,
158             TransformHandler handler, boolean move) throws IOException {
159         List<Map.Entry<Path, Path>> copyItems = new ArrayList<>();
160         List<Path> excludeItems = new ArrayList<>();
161 
162         for (var id: src.entries.keySet()) {
163             Path srcPath = src.entries.get(id);
164             if (dst.entries.containsKey(id)) {
165                 copyItems.add(Map.entry(srcPath, dst.entries.get(id)));
166             } else {
167                 excludeItems.add(srcPath);
168             }
169         }
170 
171         copy(move, copyItems, excludeItems, handler);
172     }
173 
copy(boolean move, List<Map.Entry<Path, Path>> entries, List<Path> excludePaths, TransformHandler handler)174     private static void copy(boolean move, List<Map.Entry<Path, Path>> entries,
175             List<Path> excludePaths, TransformHandler handler) throws
176             IOException {
177 
178         if (handler == null) {
179             handler = new TransformHandler() {
180                 @Override
181                 public void copyFile(Path src, Path dst) throws IOException {
182                     Files.createDirectories(IOUtils.getParent(dst));
183                     if (move) {
184                         Files.move(src, dst);
185                     } else {
186                         Files.copy(src, dst);
187                     }
188                 }
189 
190                 @Override
191                 public void createDirectory(Path dir) throws IOException {
192                     Files.createDirectories(dir);
193                 }
194             };
195         }
196 
197         // destination -> source file mapping
198         Map<Path, Path> actions = new HashMap<>();
199         for (var action: entries) {
200             Path src = action.getKey();
201             Path dst = action.getValue();
202             if (Files.isDirectory(src)) {
203                try (Stream<Path> stream = Files.walk(src)) {
204                    stream.sequential().forEach(path -> actions.put(dst.resolve(
205                             src.relativize(path)).normalize(), path));
206                }
207             } else {
208                 actions.put(dst.normalize(), src);
209             }
210         }
211 
212         for (var action : actions.entrySet()) {
213             Path dst = action.getKey();
214             Path src = action.getValue();
215 
216             if (excludePaths.stream().anyMatch(src::startsWith)) {
217                 continue;
218             }
219 
220             if (src.equals(dst) || !src.toFile().exists()) {
221                 continue;
222             }
223 
224             if (Files.isDirectory(src)) {
225                 handler.createDirectory(dst);
226             } else {
227                 handler.copyFile(src, dst);
228             }
229         }
230 
231         if (move) {
232             // Delete source dirs.
233             for (var entry: entries) {
234                 Path srcFile = entry.getKey();
235                 if (Files.isDirectory(srcFile)) {
236                     IOUtils.deleteRecursive(srcFile);
237                 }
238             }
239         }
240     }
241 
normalizedPath(Path v)242     private static Map.Entry<Path, Path> normalizedPath(Path v) {
243         final Path normalized;
244         if (!v.isAbsolute()) {
245             normalized = Path.of("./").resolve(v.normalize());
246         } else {
247             normalized = v.normalize();
248         }
249 
250         return Map.entry(normalized, v);
251     }
252 
normalizedPaths()253     private List<Map.Entry<Path, Path>> normalizedPaths() {
254         return entries.values().stream().map(PathGroup::normalizedPath).collect(
255                 Collectors.toList());
256     }
257 
258     private final Map<Object, Path> entries;
259 }
260