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.6KB

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