View Javadoc
1   /*
2    * This file is part of ***  M y C o R e  ***
3    * See http://www.mycore.de/ for details.
4    *
5    * MyCoRe is free software: you can redistribute it and/or modify
6    * it under the terms of the GNU General Public License as published by
7    * the Free Software Foundation, either version 3 of the License, or
8    * (at your option) any later version.
9    *
10   * MyCoRe is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   * GNU General Public License for more details.
14   *
15   * You should have received a copy of the GNU General Public License
16   * along with MyCoRe.  If not, see <http://www.gnu.org/licenses/>.
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       * Renames multiple files in one Derivate with the given pattern. You can try out your pattern with the method
43       * {@link #testRenameFile(String, String, String) testRenameFile}.
44       *
45       * @param derivate the Derivate ID as String
46       * @param pattern the RegEx pattern to find the wanted files
47       * @param replacement the new name for the files
48       * @return a Hashmap with the old name and the new name
49       * @throws IOException
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       * Tests the rename pattern on one file, so you can try the rename befor renaming all files. This method does not
85       * change any files.
86       *
87       * @param filename a filename to try the pattern on
88       * @param pattern the RegEx pattern to find the wanted files
89       * @param replacement the new name for the files
90       * @return the new filename
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 }