1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.logging.log4j.core.appender.rolling.action;
19
20 import java.io.IOException;
21 import java.nio.file.FileVisitResult;
22 import java.nio.file.Files;
23 import java.nio.file.Path;
24 import java.nio.file.SimpleFileVisitor;
25 import java.nio.file.attribute.BasicFileAttributes;
26 import java.util.List;
27 import java.util.Objects;
28
29 import org.apache.logging.log4j.Logger;
30 import org.apache.logging.log4j.status.StatusLogger;
31
32
33
34
35 public class DeletingVisitor extends SimpleFileVisitor<Path> {
36 private static final Logger LOGGER = StatusLogger.getLogger();
37
38 private final Path basePath;
39 private final boolean testMode;
40 private final List<? extends PathCondition> pathConditions;
41
42
43
44
45
46
47
48
49
50
51 public DeletingVisitor(final Path basePath, final List<? extends PathCondition> pathConditions,
52 final boolean testMode) {
53 this.testMode = testMode;
54 this.basePath = Objects.requireNonNull(basePath, "basePath");
55 this.pathConditions = Objects.requireNonNull(pathConditions, "pathConditions");
56 for (final PathCondition condition : pathConditions) {
57 condition.beforeFileTreeWalk();
58 }
59 }
60
61 @Override
62 public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
63 for (final PathCondition pathFilter : pathConditions) {
64 final Path relative = basePath.relativize(file);
65 if (!pathFilter.accept(basePath, relative, attrs)) {
66 LOGGER.trace("Not deleting base={}, relative={}", basePath, relative);
67 return FileVisitResult.CONTINUE;
68 }
69 }
70 if (isTestMode()) {
71 LOGGER.info("Deleting {} (TEST MODE: file not actually deleted)", file);
72 } else {
73 delete(file);
74 }
75 return FileVisitResult.CONTINUE;
76 }
77
78
79
80
81
82
83
84 protected void delete(final Path file) throws IOException {
85 LOGGER.trace("Deleting {}", file);
86 Files.deleteIfExists(file);
87 }
88
89
90
91
92
93
94 public boolean isTestMode() {
95 return testMode;
96 }
97 }