1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.eclipse.aether.spi.io;
20
21 import java.io.BufferedInputStream;
22 import java.io.BufferedOutputStream;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.InterruptedIOException;
26 import java.io.OutputStream;
27 import java.nio.ByteBuffer;
28 import java.nio.charset.StandardCharsets;
29 import java.nio.file.AccessDeniedException;
30 import java.nio.file.AtomicMoveNotSupportedException;
31 import java.nio.file.FileSystemException;
32 import java.nio.file.Files;
33 import java.nio.file.Path;
34 import java.nio.file.StandardCopyOption;
35 import java.nio.file.attribute.FileTime;
36 import java.util.concurrent.ThreadLocalRandom;
37 import java.util.concurrent.atomic.AtomicBoolean;
38
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 import static java.util.Objects.requireNonNull;
43
44
45
46
47
48
49
50 public class PathProcessorSupport implements PathProcessor {
51 private static final Logger LOGGER = LoggerFactory.getLogger(PathProcessorSupport.class);
52
53
54
55
56
57 protected static final boolean IS_WINDOWS =
58 System.getProperty("os.name", "unknown").startsWith("Windows");
59
60
61
62
63 protected static final boolean ATOMIC_MOVE =
64 Boolean.parseBoolean(System.getProperty(PathProcessor.class.getName() + ".ATOMIC_MOVE", "true"));
65
66
67
68
69
70 protected static final int WINDOWS_MOVE_ATTEMPTS =
71 Math.max(1, Integer.getInteger(PathProcessor.class.getName() + ".WINDOWS_MOVE_ATTEMPTS", 5));
72
73
74
75
76 protected static final long WINDOWS_MOVE_RETRY_DELAY =
77 Long.getLong(PathProcessor.class.getName() + ".WINDOWS_MOVE_RETRY_DELAY", 50L);
78
79
80
81
82
83
84
85
86
87
88 protected static final boolean WINDOWS_CLASSIC_COPY_FALLBACK = Boolean.parseBoolean(
89 System.getProperty(PathProcessor.class.getName() + ".WINDOWS_CLASSIC_COPY_FALLBACK", "true"));
90
91 @Override
92 public boolean setLastModified(Path path, long value) throws IOException {
93 try {
94 Files.setLastModifiedTime(path, FileTime.fromMillis(value));
95 return true;
96 } catch (FileSystemException e) {
97
98
99 if (e instanceof AccessDeniedException) {
100 throw e;
101 }
102 return false;
103 }
104 }
105
106 @Override
107 public void write(Path target, String data) throws IOException {
108 writeFile(target, p -> Files.write(p, data.getBytes(StandardCharsets.UTF_8)), false);
109 }
110
111 @Override
112 public void write(Path target, InputStream source) throws IOException {
113 writeFile(target, p -> Files.copy(source, p, StandardCopyOption.REPLACE_EXISTING), false);
114 }
115
116 @Override
117 public void writeWithBackup(Path target, String data) throws IOException {
118 writeFile(target, p -> Files.write(p, data.getBytes(StandardCharsets.UTF_8)), true);
119 }
120
121 @Override
122 public void writeWithBackup(Path target, InputStream source) throws IOException {
123 writeFile(target, p -> Files.copy(source, p, StandardCopyOption.REPLACE_EXISTING), true);
124 }
125
126
127
128
129
130
131 @FunctionalInterface
132 public interface FileWriter {
133 void write(Path path) throws IOException;
134 }
135
136
137
138
139
140
141
142
143
144
145
146
147 public void writeFile(Path target, FileWriter writer, boolean doBackup) throws IOException {
148 requireNonNull(target, "target is null");
149 requireNonNull(writer, "writer is null");
150 Path parent = requireNonNull(target.getParent(), "target must have parent");
151
152 try (CollocatedTempFile tempFile = newTempFile(target)) {
153 writer.write(tempFile.getPath());
154 if (doBackup && Files.isRegularFile(target)) {
155 Files.copy(target, parent.resolve(target.getFileName() + ".bak"), StandardCopyOption.REPLACE_EXISTING);
156 }
157 tempFile.move();
158 }
159 }
160
161 @Override
162 public long copy(Path source, Path target, ProgressListener listener) throws IOException {
163 try (InputStream in = new BufferedInputStream(Files.newInputStream(source));
164 CollocatedTempFile tempTarget = newTempFile(target);
165 OutputStream out = new BufferedOutputStream(Files.newOutputStream(tempTarget.getPath()))) {
166 long result = copy(out, in, listener);
167 tempTarget.move();
168 return result;
169 }
170 }
171
172 private long copy(OutputStream os, InputStream is, ProgressListener listener) throws IOException {
173 long total = 0L;
174 byte[] buffer = new byte[1024 * 32];
175 while (true) {
176 int bytes = is.read(buffer);
177 if (bytes < 0) {
178 break;
179 }
180
181 os.write(buffer, 0, bytes);
182
183 total += bytes;
184
185 if (listener != null && bytes > 0) {
186 try {
187 listener.progressed(ByteBuffer.wrap(buffer, 0, bytes));
188 } catch (Exception e) {
189
190 }
191 }
192 }
193
194 return total;
195 }
196
197 @Override
198 public void move(Path source, Path target) throws IOException {
199 final StandardCopyOption[] copyOption = ATOMIC_MOVE
200 ? new StandardCopyOption[] {
201 StandardCopyOption.ATOMIC_MOVE,
202 StandardCopyOption.REPLACE_EXISTING,
203 StandardCopyOption.COPY_ATTRIBUTES
204 }
205 : new StandardCopyOption[] {StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES};
206 if (IS_WINDOWS) {
207 retryingMove(source, target, copyOption);
208 } else {
209 Files.move(source, target, copyOption);
210 }
211 Files.deleteIfExists(source);
212 }
213
214
215
216 @Override
217 public TempFile newTempFile() throws IOException {
218 Path tempFile = Files.createTempFile("resolver", "tmp");
219 return new TempFile() {
220 @Override
221 public Path getPath() {
222 return tempFile;
223 }
224
225 @Override
226 public void close() throws IOException {
227 Files.deleteIfExists(tempFile);
228 }
229 };
230 }
231
232 @Override
233 public CollocatedTempFile newTempFile(Path file) throws IOException {
234 Path parent = requireNonNull(file.getParent(), "file must have parent");
235 Files.createDirectories(parent);
236 Path tempFile = parent.resolve(file.getFileName() + "."
237 + Long.toUnsignedString(ThreadLocalRandom.current().nextLong()) + ".tmp");
238 return new CollocatedTempFile() {
239 private final AtomicBoolean wantsMove = new AtomicBoolean(false);
240 private final StandardCopyOption[] copyOption = ATOMIC_MOVE
241 ? new StandardCopyOption[] {StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING}
242 : new StandardCopyOption[] {StandardCopyOption.REPLACE_EXISTING};
243
244 @Override
245 public Path getPath() {
246 return tempFile;
247 }
248
249 @Override
250 public void move() {
251 wantsMove.set(true);
252 }
253
254 @Override
255 public void close() throws IOException {
256 if (wantsMove.get()) {
257 if (IS_WINDOWS) {
258 retryingMove(tempFile, file, copyOption);
259 } else {
260 Files.move(tempFile, file, copyOption);
261 }
262 }
263 Files.deleteIfExists(tempFile);
264 }
265 };
266 }
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286 protected void retryingMove(Path source, Path target, StandardCopyOption[] copyOptions) throws IOException {
287 FileSystemException lastException = null;
288 for (int attempt = 0; attempt < WINDOWS_MOVE_ATTEMPTS; attempt++) {
289 try {
290 fileSystemMove(source, target, copyOptions);
291 return;
292 } catch (AtomicMoveNotSupportedException e) {
293 lastException = e;
294 break;
295 } catch (FileSystemException e) {
296
297 lastException = e;
298 try {
299 Thread.sleep(WINDOWS_MOVE_RETRY_DELAY);
300 } catch (InterruptedException ie) {
301 Thread.currentThread().interrupt();
302 InterruptedIOException interrupted =
303 new InterruptedIOException("Interrupted while moving " + source + " to " + target);
304 interrupted.initCause(ie);
305 interrupted.addSuppressed(e);
306 throw interrupted;
307 }
308 }
309 }
310 if (lastException instanceof AtomicMoveNotSupportedException) {
311 Path staged = target.resolveSibling(target.getFileName() + "."
312 + Long.toUnsignedString(ThreadLocalRandom.current().nextLong()) + ".tmp");
313 try {
314 classicCopy(source, staged);
315 fileSystemMove(staged, target, copyOptions);
316 return;
317 } finally {
318 Files.deleteIfExists(staged);
319 }
320 }
321
322
323
324
325 if (isClassicCopyFallbackEnabled() && (lastException instanceof AccessDeniedException)) {
326 LOGGER.warn(
327 "Atomic rename of {} to {} failed after {} attempt(s) ({}); falling back to direct copy."
328 + " Another process may be holding the target file open."
329 + " Set -D{}.WINDOWS_CLASSIC_COPY_FALLBACK=false to disable this fallback.",
330 source,
331 target,
332 WINDOWS_MOVE_ATTEMPTS,
333 lastException.getMessage(),
334 PathProcessor.class.getName());
335 classicCopy(source, target);
336 return;
337 }
338 throw lastException;
339 }
340
341
342
343
344 protected void fileSystemMove(Path source, Path target, StandardCopyOption... copyOptions) throws IOException {
345 Files.move(source, target, copyOptions);
346 }
347
348
349
350
351
352 protected boolean isClassicCopyFallbackEnabled() {
353 return WINDOWS_CLASSIC_COPY_FALLBACK;
354 }
355
356
357
358
359
360
361
362
363
364
365 protected void classicCopy(Path source, Path target) throws IOException {
366 ByteBuffer buffer = ByteBuffer.allocate(1024 * 32);
367 byte[] array = buffer.array();
368 try (InputStream is = Files.newInputStream(source);
369 OutputStream os = Files.newOutputStream(target)) {
370 while (true) {
371 int bytes = is.read(array);
372 if (bytes < 0) {
373 break;
374 }
375 os.write(array, 0, bytes);
376 }
377 }
378 try {
379 setLastModified(target, Files.getLastModifiedTime(source).toMillis());
380 } catch (IOException e) {
381 LOGGER.debug("Could not set the last modified time of {}", target, e);
382 }
383 }
384 }