You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

FileUtils.java 6.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. /*
  2. * Copyright 2012 Decebal Suiu
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.pf4j.util;
  17. import org.slf4j.Logger;
  18. import org.slf4j.LoggerFactory;
  19. import java.io.BufferedReader;
  20. import java.io.File;
  21. import java.io.FileFilter;
  22. import java.io.FileReader;
  23. import java.io.IOException;
  24. import java.nio.charset.StandardCharsets;
  25. import java.nio.file.FileVisitResult;
  26. import java.nio.file.Files;
  27. import java.nio.file.Path;
  28. import java.nio.file.SimpleFileVisitor;
  29. import java.nio.file.attribute.BasicFileAttributes;
  30. import java.nio.file.attribute.FileTime;
  31. import java.util.ArrayList;
  32. import java.util.Collection;
  33. import java.util.List;
  34. /**
  35. * @author Decebal Suiu
  36. */
  37. public class FileUtils {
  38. private static final Logger log = LoggerFactory.getLogger(FileUtils.class);
  39. public static List<String> readLines(Path path, boolean ignoreComments) throws IOException {
  40. File file = path.toFile();
  41. if (!file.exists() || !file.isFile()) {
  42. return new ArrayList<>();
  43. }
  44. List<String> lines = new ArrayList<>();
  45. try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
  46. String line;
  47. while ((line = reader.readLine()) != null) {
  48. if (ignoreComments && !line.startsWith("#") && !lines.contains(line)) {
  49. lines.add(line);
  50. }
  51. }
  52. }
  53. return lines;
  54. }
  55. public static void writeLines(Collection<String> lines, File file) throws IOException {
  56. Files.write(file.toPath(), lines, StandardCharsets.UTF_8);
  57. }
  58. /**
  59. * Delete a file or recursively delete a folder, do not follow symlinks.
  60. *
  61. * @param path the file or folder to delete
  62. * @throws IOException if something goes wrong
  63. */
  64. public static void delete(Path path) throws IOException {
  65. Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
  66. @Override
  67. public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
  68. if (!attrs.isSymbolicLink()) {
  69. Files.delete(path);
  70. }
  71. return FileVisitResult.CONTINUE;
  72. }
  73. @Override
  74. public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
  75. Files.delete(dir);
  76. return FileVisitResult.CONTINUE;
  77. }
  78. });
  79. }
  80. public static List<File> getJars(Path folder) {
  81. List<File> bucket = new ArrayList<>();
  82. getJars(bucket, folder);
  83. return bucket;
  84. }
  85. private static void getJars(final List<File> bucket, Path folder) {
  86. FileFilter jarFilter = new JarFileFilter();
  87. FileFilter directoryFilter = new DirectoryFileFilter();
  88. if (Files.exists(folder) && Files.isDirectory(folder)) {
  89. File[] jars = folder.toFile().listFiles(jarFilter);
  90. for (int i = 0; (jars != null) && (i < jars.length); ++i) {
  91. bucket.add(jars[i]);
  92. }
  93. File[] directories = folder.toFile().listFiles(directoryFilter);
  94. for (int i = 0; (directories != null) && (i < directories.length); ++i) {
  95. File directory = directories[i];
  96. getJars(bucket, directory.toPath());
  97. }
  98. }
  99. }
  100. /**
  101. * Finds a path with various endings or null if not found.
  102. *
  103. * @param basePath the base name
  104. * @param endings a list of endings to search for
  105. * @return new path or null if not found
  106. */
  107. public static Path findWithEnding(Path basePath, String... endings) {
  108. for (String ending : endings) {
  109. Path newPath = basePath.resolveSibling(basePath.getFileName() + ending);
  110. if (Files.exists(newPath)) {
  111. return newPath;
  112. }
  113. }
  114. return null;
  115. }
  116. /**
  117. * Delete a file (not recursively) and ignore any errors.
  118. *
  119. * @param path the path to delete
  120. */
  121. public static void optimisticDelete(Path path) {
  122. if (path == null) {
  123. return;
  124. }
  125. try {
  126. Files.delete(path);
  127. } catch (IOException ignored) { }
  128. }
  129. /**
  130. * Unzip a zip file in a directory that has the same name as the zip file.
  131. * For example if the zip file is {@code my-plugin.zip} then the resulted directory
  132. * is {@code my-plugin}.
  133. *
  134. * @param filePath the file to evaluate
  135. * @return Path of unzipped folder or original path if this was not a zip file
  136. * @throws IOException on error
  137. */
  138. public static Path expandIfZip(Path filePath) throws IOException {
  139. if (!isZipFile(filePath)) {
  140. return filePath;
  141. }
  142. FileTime pluginZipDate = Files.getLastModifiedTime(filePath);
  143. String fileName = filePath.getFileName().toString();
  144. Path pluginDirectory = filePath.resolveSibling(fileName.substring(0, fileName.lastIndexOf(".")));
  145. if (!Files.exists(pluginDirectory) || pluginZipDate.compareTo(Files.getLastModifiedTime(pluginDirectory)) > 0) {
  146. // do not overwrite an old version, remove it
  147. if (Files.exists(pluginDirectory)) {
  148. FileUtils.delete(pluginDirectory);
  149. }
  150. // create root for plugin
  151. Files.createDirectories(pluginDirectory);
  152. // expand '.zip' file
  153. Unzip unzip = new Unzip();
  154. unzip.setSource(filePath.toFile());
  155. unzip.setDestination(pluginDirectory.toFile());
  156. unzip.extract();
  157. log.info("Expanded plugin zip '{}' in '{}'", filePath.getFileName(), pluginDirectory.getFileName());
  158. }
  159. return pluginDirectory;
  160. }
  161. /**
  162. * Return true only if path is a zip file.
  163. *
  164. * @param path to a file/dir
  165. * @return true if file with {@code .zip} ending
  166. */
  167. public static boolean isZipFile(Path path) {
  168. return Files.isRegularFile(path) && path.toString().toLowerCase().endsWith(".zip");
  169. }
  170. }