1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.mycore.datamodel.niofs.utils;
20
21 import java.io.IOException;
22 import java.nio.file.FileVisitResult;
23 import java.nio.file.Files;
24 import java.nio.file.Path;
25 import java.nio.file.SimpleFileVisitor;
26 import java.nio.file.attribute.BasicFileAttributes;
27 import java.util.HashMap;
28 import java.util.Map;
29 import java.util.regex.Matcher;
30 import java.util.regex.Pattern;
31 import java.util.regex.PatternSyntaxException;
32
33 import org.apache.logging.log4j.LogManager;
34 import org.apache.logging.log4j.Logger;
35 import org.mycore.datamodel.niofs.MCRPath;
36
37 public class MCRDerivateUtil {
38
39 private static final Logger LOGGER = LogManager.getLogger();
40
41
42
43
44
45
46
47
48
49
50
51 public static Map<String, String> renameFiles(String derivate, String pattern, String replacement)
52 throws IOException {
53 MCRPath derivateRoot = MCRPath.getPath(derivate, "/");
54 Pattern patternObj = Pattern.compile(pattern);
55 Map<String, String> resultMap = new HashMap<>();
56 Files.walkFileTree(derivateRoot, new SimpleFileVisitor<Path>() {
57 @Override
58 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
59 throws IOException {
60 Matcher matcher = patternObj.matcher(file.getFileName().toString());
61 if (matcher.matches()) {
62 LOGGER.debug("The file {} matches the pattern {}", file, pattern);
63 String newFilename;
64 try {
65 newFilename = matcher.replaceAll(replacement);
66 } catch (IndexOutOfBoundsException e) {
67 LOGGER.error("The file {} can't be renamed to {}. To many groups!", file, replacement, e);
68 return FileVisitResult.CONTINUE;
69 } catch (IllegalArgumentException e) {
70 LOGGER.error("The new name '{}' contains illegal characters!", replacement, e);
71 return FileVisitResult.CONTINUE;
72 }
73 Files.move(file, file.resolveSibling(newFilename));
74 LOGGER.info("The file {} was renamed to {}", file, newFilename);
75 resultMap.put(file.getFileName().toString(), newFilename);
76 }
77 return FileVisitResult.CONTINUE;
78 }
79 });
80 return resultMap;
81 }
82
83
84
85
86
87
88
89
90
91
92 public static String testRenameFile(String filename, String pattern, String replacement) {
93 String newFilename = "";
94 try {
95 Pattern patternObj = Pattern.compile(pattern);
96 Matcher matcher = patternObj.matcher(filename);
97 newFilename = matcher.replaceAll(replacement);
98 LOGGER.info("The file {} will be renamed to {}", filename, newFilename);
99 } catch (PatternSyntaxException e) {
100 LOGGER.error("The pattern '{}' contains errors!", pattern, e);
101 } catch (IndexOutOfBoundsException e) {
102 LOGGER.error("The file {} can't be renamed to {}. To many groups!", filename, replacement, e);
103 } catch (IllegalArgumentException e) {
104 LOGGER.error("The new name '{}' contains illegal characters!", replacement, e);
105 }
106 return newFilename;
107 }
108
109 }