forked from openjdk/jdk
/
IOUtils.java
361 lines (317 loc) · 12.8 KB
/
IOUtils.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
/*
* Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.incubator.jpackage.internal;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Writer;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
/**
* IOUtils
*
* A collection of static utility methods.
*/
public class IOUtils {
public static void deleteRecursive(Path directory) throws IOException {
if (!Files.exists(directory)) {
return;
}
Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attr) throws IOException {
if (Platform.getPlatform() == Platform.WINDOWS) {
Files.setAttribute(file, "dos:readonly", false);
}
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir,
BasicFileAttributes attr) throws IOException {
if (Platform.getPlatform() == Platform.WINDOWS) {
Files.setAttribute(dir, "dos:readonly", false);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException e)
throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
public static void copyRecursive(Path src, Path dest) throws IOException {
copyRecursive(src, dest, List.of());
}
public static void copyRecursive(Path src, Path dest,
final List<String> excludes) throws IOException {
Files.walkFileTree(src, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(final Path dir,
final BasicFileAttributes attrs) throws IOException {
if (excludes.contains(dir.toFile().getName())) {
return FileVisitResult.SKIP_SUBTREE;
} else {
Files.createDirectories(dest.resolve(src.relativize(dir)));
return FileVisitResult.CONTINUE;
}
}
@Override
public FileVisitResult visitFile(final Path file,
final BasicFileAttributes attrs) throws IOException {
if (!excludes.contains(file.toFile().getName())) {
Files.copy(file, dest.resolve(src.relativize(file)));
}
return FileVisitResult.CONTINUE;
}
});
}
public static void copyFile(Path sourceFile, Path destFile)
throws IOException {
Files.createDirectories(destFile.getParent());
Files.copy(sourceFile, destFile,
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES);
}
public static boolean exists(Path path) {
if (path == null) {
return false;
}
return Files.exists(path);
}
// run "launcher paramfile" in the directory where paramfile is kept
public static void run(String launcher, Path paramFile)
throws IOException {
if (IOUtils.exists(paramFile)) {
ProcessBuilder pb =
new ProcessBuilder(launcher, paramFile.getFileName().toString());
pb = pb.directory(paramFile.getParent().toFile());
exec(pb);
}
}
public static void exec(ProcessBuilder pb)
throws IOException {
exec(pb, false, null, false, Executor.INFINITE_TIMEOUT);
}
// timeout in seconds. -1 will be return if process timeouts.
public static void exec(ProcessBuilder pb, long timeout)
throws IOException {
exec(pb, false, null, false, timeout);
}
// See JDK-8236282
// Reading output from some processes (currently known "hdiutil attach")
// might hang even if process already exited. Only possible workaround found
// in "hdiutil attach" case is to redirect the output to a temp file and then
// read this file back.
public static void exec(ProcessBuilder pb, boolean writeOutputToFile)
throws IOException {
exec(pb, false, null, writeOutputToFile, Executor.INFINITE_TIMEOUT);
}
static void exec(ProcessBuilder pb, boolean testForPresenceOnly,
PrintStream consumer) throws IOException {
exec(pb, testForPresenceOnly, consumer, false, Executor.INFINITE_TIMEOUT);
}
static void exec(ProcessBuilder pb, boolean testForPresenceOnly,
PrintStream consumer, boolean writeOutputToFile, long timeout)
throws IOException {
List<String> output = new ArrayList<>();
Executor exec = Executor.of(pb).setWriteOutputToFile(writeOutputToFile)
.setTimeout(timeout).setOutputConsumer(lines -> {
lines.forEach(output::add);
if (consumer != null) {
output.forEach(consumer::println);
}
});
if (testForPresenceOnly) {
exec.execute();
} else {
exec.executeExpectSuccess();
}
}
public static int getProcessOutput(List<String> result, String... args)
throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder(args);
final Process p = pb.start();
List<String> list = new ArrayList<>();
final BufferedReader in =
new BufferedReader(new InputStreamReader(p.getInputStream()));
final BufferedReader err =
new BufferedReader(new InputStreamReader(p.getErrorStream()));
Thread t = new Thread(() -> {
try {
String line;
while ((line = in.readLine()) != null) {
list.add(line);
}
} catch (IOException ioe) {
Log.verbose(ioe);
}
try {
String line;
while ((line = err.readLine()) != null) {
Log.error(line);
}
} catch (IOException ioe) {
Log.verbose(ioe);
}
});
t.setDaemon(true);
t.start();
int ret = p.waitFor();
Log.verbose(pb.command(), list, ret);
result.clear();
result.addAll(list);
return ret;
}
static void writableOutputDir(Path outdir) throws PackagerException {
if (!Files.isDirectory(outdir)) {
try {
Files.createDirectories(outdir);
} catch (IOException ex) {
throw new PackagerException("error.cannot-create-output-dir",
outdir.toAbsolutePath().toString());
}
}
if (!Files.isWritable(outdir)) {
throw new PackagerException("error.cannot-write-to-output-dir",
outdir.toAbsolutePath().toString());
}
}
public static Path replaceSuffix(Path path, String suffix) {
Path parent = path.getParent();
String filename = path.getFileName().toString().replaceAll("\\.[^.]*$", "")
+ Optional.ofNullable(suffix).orElse("");
return parent != null ? parent.resolve(filename) : Path.of(filename);
}
public static Path addSuffix(Path path, String suffix) {
Path parent = path.getParent();
String filename = path.getFileName().toString() + suffix;
return parent != null ? parent.resolve(filename) : Path.of(filename);
}
public static String getSuffix(Path path) {
String filename = replaceSuffix(path.getFileName(), null).toString();
return path.getFileName().toString().substring(filename.length());
}
@FunctionalInterface
public static interface XmlConsumer {
void accept(XMLStreamWriter xml) throws IOException, XMLStreamException;
}
public static void createXml(Path dstFile, XmlConsumer xmlConsumer) throws
IOException {
XMLOutputFactory xmlFactory = XMLOutputFactory.newInstance();
Files.createDirectories(dstFile.getParent());
try (Writer w = Files.newBufferedWriter(dstFile)) {
// Wrap with pretty print proxy
XMLStreamWriter xml = (XMLStreamWriter) Proxy.newProxyInstance(
XMLStreamWriter.class.getClassLoader(), new Class<?>[]{
XMLStreamWriter.class}, new PrettyPrintHandler(
xmlFactory.createXMLStreamWriter(w)));
xml.writeStartDocument();
xmlConsumer.accept(xml);
xml.writeEndDocument();
xml.flush();
xml.close();
} catch (XMLStreamException ex) {
throw new IOException(ex);
} catch (IOException ex) {
throw ex;
}
}
private static class PrettyPrintHandler implements InvocationHandler {
PrettyPrintHandler(XMLStreamWriter target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws
Throwable {
switch (method.getName()) {
case "writeStartElement":
// update state of parent node
if (depth > 0) {
hasChildElement.put(depth - 1, true);
}
// reset state of current node
hasChildElement.put(depth, false);
// indent for current depth
target.writeCharacters(EOL);
target.writeCharacters(repeat(depth, INDENT));
depth++;
break;
case "writeEndElement":
depth--;
if (hasChildElement.get(depth) == true) {
target.writeCharacters(EOL);
target.writeCharacters(repeat(depth, INDENT));
}
break;
case "writeProcessingInstruction":
case "writeEmptyElement":
// update state of parent node
if (depth > 0) {
hasChildElement.put(depth - 1, true);
}
// indent for current depth
target.writeCharacters(EOL);
target.writeCharacters(repeat(depth, INDENT));
break;
default:
break;
}
method.invoke(target, args);
return null;
}
private static String repeat(int d, String s) {
StringBuilder sb = new StringBuilder();
while (d-- > 0) {
sb.append(s);
}
return sb.toString();
}
private final XMLStreamWriter target;
private int depth = 0;
private final Map<Integer, Boolean> hasChildElement = new HashMap<>();
private static final String INDENT = " ";
private static final String EOL = "\n";
}
}