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

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