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 8.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. /*
  2. * Copyright (C) 2012-present the original author or authors.
  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.net.URI;
  25. import java.nio.charset.StandardCharsets;
  26. import java.nio.file.FileSystem;
  27. import java.nio.file.FileSystemNotFoundException;
  28. import java.nio.file.FileSystems;
  29. import java.nio.file.FileVisitResult;
  30. import java.nio.file.Files;
  31. import java.nio.file.Path;
  32. import java.nio.file.SimpleFileVisitor;
  33. import java.nio.file.attribute.BasicFileAttributes;
  34. import java.nio.file.attribute.FileTime;
  35. import java.util.ArrayList;
  36. import java.util.Collection;
  37. import java.util.Collections;
  38. import java.util.List;
  39. /**
  40. * @author Decebal Suiu
  41. */
  42. public class FileUtils {
  43. private static final Logger log = LoggerFactory.getLogger(FileUtils.class);
  44. public static List<String> readLines(Path path, boolean ignoreComments) throws IOException {
  45. File file = path.toFile();
  46. if (!file.exists() || !file.isFile()) {
  47. return new ArrayList<>();
  48. }
  49. List<String> lines = new ArrayList<>();
  50. try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
  51. String line;
  52. while ((line = reader.readLine()) != null) {
  53. if (ignoreComments && !line.startsWith("#") && !lines.contains(line)) {
  54. lines.add(line);
  55. }
  56. }
  57. }
  58. return lines;
  59. }
  60. /**
  61. * Use {@link #writeLines(Collection, Path)} instead.
  62. */
  63. @Deprecated
  64. public static void writeLines(Collection<String> lines, File file) throws IOException {
  65. writeLines(lines, file.toPath());
  66. }
  67. public static void writeLines(Collection<String> lines, Path path) throws IOException {
  68. Files.write(path, lines, StandardCharsets.UTF_8);
  69. }
  70. /**
  71. * Delete a file or recursively delete a folder, do not follow symlinks.
  72. *
  73. * @param path the file or folder to delete
  74. * @throws IOException if something goes wrong
  75. */
  76. public static void delete(Path path) throws IOException {
  77. Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
  78. @Override
  79. public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
  80. if (!attrs.isSymbolicLink()) {
  81. Files.delete(path);
  82. }
  83. return FileVisitResult.CONTINUE;
  84. }
  85. @Override
  86. public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
  87. Files.delete(dir);
  88. return FileVisitResult.CONTINUE;
  89. }
  90. });
  91. }
  92. public static List<File> getJars(Path folder) {
  93. List<File> bucket = new ArrayList<>();
  94. getJars(bucket, folder);
  95. return bucket;
  96. }
  97. private static void getJars(final List<File> bucket, Path folder) {
  98. FileFilter jarFilter = new JarFileFilter();
  99. FileFilter directoryFilter = new DirectoryFileFilter();
  100. if (Files.exists(folder) && Files.isDirectory(folder)) {
  101. File[] jars = folder.toFile().listFiles(jarFilter);
  102. for (int i = 0; (jars != null) && (i < jars.length); ++i) {
  103. bucket.add(jars[i]);
  104. }
  105. File[] directories = folder.toFile().listFiles(directoryFilter);
  106. for (int i = 0; (directories != null) && (i < directories.length); ++i) {
  107. File directory = directories[i];
  108. getJars(bucket, directory.toPath());
  109. }
  110. }
  111. }
  112. /**
  113. * Finds a path with various endings or null if not found.
  114. *
  115. * @param basePath the base name
  116. * @param endings a list of endings to search for
  117. * @return new path or null if not found
  118. */
  119. public static Path findWithEnding(Path basePath, String... endings) {
  120. for (String ending : endings) {
  121. Path newPath = basePath.resolveSibling(basePath.getFileName() + ending);
  122. if (Files.exists(newPath)) {
  123. return newPath;
  124. }
  125. }
  126. return null;
  127. }
  128. /**
  129. * Delete a file (not recursively) and ignore any errors.
  130. *
  131. * @param path the path to delete
  132. */
  133. public static void optimisticDelete(Path path) {
  134. if (path == null) {
  135. return;
  136. }
  137. try {
  138. Files.delete(path);
  139. } catch (IOException ignored) { }
  140. }
  141. /**
  142. * Unzip a zip file in a directory that has the same name as the zip file.
  143. * For example if the zip file is {@code my-plugin.zip} then the resulted directory
  144. * is {@code my-plugin}.
  145. *
  146. * @param filePath the file to evaluate
  147. * @return Path of unzipped folder or original path if this was not a zip file
  148. * @throws IOException on error
  149. */
  150. public static Path expandIfZip(Path filePath) throws IOException {
  151. if (!isZipFile(filePath)) {
  152. return filePath;
  153. }
  154. FileTime pluginZipDate = Files.getLastModifiedTime(filePath);
  155. String fileName = filePath.getFileName().toString();
  156. String directoryName = fileName.substring(0, fileName.lastIndexOf("."));
  157. Path pluginDirectory = filePath.resolveSibling(directoryName);
  158. if (!Files.exists(pluginDirectory) || pluginZipDate.compareTo(Files.getLastModifiedTime(pluginDirectory)) > 0) {
  159. // expand '.zip' file
  160. Unzip unzip = new Unzip();
  161. unzip.setSource(filePath.toFile());
  162. unzip.setDestination(pluginDirectory.toFile());
  163. unzip.extract();
  164. log.info("Expanded plugin zip '{}' in '{}'", filePath.getFileName(), pluginDirectory.getFileName());
  165. }
  166. return pluginDirectory;
  167. }
  168. /**
  169. * Return true only if path is a zip file.
  170. *
  171. * @param path to a file/dir
  172. * @return true if file with {@code .zip} ending
  173. */
  174. public static boolean isZipFile(Path path) {
  175. return Files.isRegularFile(path) && path.toString().toLowerCase().endsWith(".zip");
  176. }
  177. /**
  178. * Return true only if path is a jar file.
  179. *
  180. * @param path to a file/dir
  181. * @return true if file with {@code .jar} ending
  182. */
  183. public static boolean isJarFile(Path path) {
  184. return Files.isRegularFile(path) && path.toString().toLowerCase().endsWith(".jar");
  185. }
  186. public static Path getPath(Path path, String first, String... more) throws IOException {
  187. URI uri = path.toUri();
  188. if (isJarFile(path)) {
  189. String pathString = path.toAbsolutePath().toString();
  190. // transformation for Windows OS
  191. pathString = StringUtils.addStart(pathString.replace("\\", "/"), "/");
  192. // space is replaced with %20
  193. pathString = pathString.replaceAll(" ","%20");
  194. uri = URI.create("jar:file:" + pathString);
  195. }
  196. return getPath(uri, first, more);
  197. }
  198. public static Path getPath(URI uri, String first, String... more) throws IOException {
  199. return getFileSystem(uri).getPath(first, more);
  200. }
  201. public static Path findFile(Path directoryPath, String fileName) {
  202. File[] files = directoryPath.toFile().listFiles();
  203. if (files != null) {
  204. for (File file : files) {
  205. if (file.isFile()) {
  206. if (file.getName().equals(fileName)) {
  207. return file.toPath();
  208. }
  209. } else if (file.isDirectory()) {
  210. Path foundFile = findFile(file.toPath(), fileName);
  211. if (foundFile != null) {
  212. return foundFile;
  213. }
  214. }
  215. }
  216. }
  217. return null;
  218. }
  219. private static FileSystem getFileSystem(URI uri) throws IOException {
  220. try {
  221. return FileSystems.getFileSystem(uri);
  222. } catch (FileSystemNotFoundException e) {
  223. return FileSystems.newFileSystem(uri, Collections.<String, String>emptyMap());
  224. }
  225. }
  226. }