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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. /*
  2. * Copyright (c) 2006-2017 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
  5. * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
  6. * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
  7. * permit persons to whom the Software is furnished to do so, subject to the following conditions:
  8. *
  9. * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
  10. * Software.
  11. *
  12. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  13. * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
  14. * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  15. * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  16. */
  17. package com.dmdirc.util.io;
  18. import java.io.IOException;
  19. import java.net.URI;
  20. import java.net.URISyntaxException;
  21. import java.net.URL;
  22. import java.nio.file.CopyOption;
  23. import java.nio.file.DirectoryStream;
  24. import java.nio.file.FileSystem;
  25. import java.nio.file.FileSystems;
  26. import java.nio.file.Files;
  27. import java.nio.file.Path;
  28. import java.nio.file.Paths;
  29. import java.nio.file.StandardCopyOption;
  30. import java.security.CodeSource;
  31. import java.security.ProtectionDomain;
  32. import java.util.HashMap;
  33. import java.util.Map;
  34. import java.util.Optional;
  35. /**
  36. * Utility class to deal with files.
  37. */
  38. public final class FileUtils {
  39. private static final Optional<FileSystem> JAR_FILE_SYSTEM = getJarFileSystem();
  40. private FileUtils() {
  41. // Shouldn't be instansiated.
  42. }
  43. private static Optional<FileSystem> getJarFileSystem() {
  44. if (isRunningFromJar(FileUtils.class)) {
  45. try {
  46. final FileSystem fs = FileSystems.newFileSystem(
  47. getApplicationPath(FileUtils.class), null);
  48. return Optional.of(fs);
  49. } catch (IOException ex) {
  50. return Optional.empty();
  51. }
  52. } else {
  53. return Optional.empty();
  54. }
  55. }
  56. /**
  57. * Checks whether this application has been run from a jar or not.
  58. *
  59. * @param clazz Class used to locate the application
  60. *
  61. * @return true if the application was launched from a jar, false otherwise
  62. *
  63. * @throws IllegalStateException If the application path cannot be determined for any reason
  64. */
  65. public static boolean isRunningFromJar(final Class<?> clazz) throws IllegalStateException {
  66. // If we're running from any kind of regular file, assume it's a jar.
  67. return Files.isRegularFile(getApplicationPath(clazz));
  68. }
  69. /**
  70. * Returns the base location for the specified class, this is either the a jar or a folder
  71. * depending on how the application was launched.
  72. *
  73. * This can fail for a number of reasons, it is not wholly reliable.
  74. *
  75. * @param clazz Class used to locate the application
  76. *
  77. * @return A {@link Path} to application location
  78. *
  79. * @throws IllegalStateException If the application path cannot be determined for any reason
  80. */
  81. public static Path getApplicationPath(final Class<?> clazz) throws IllegalStateException {
  82. final ProtectionDomain pd;
  83. try {
  84. pd = clazz.getProtectionDomain();
  85. } catch (SecurityException ex) {
  86. throw new IllegalStateException("Unable to get protection domain", ex);
  87. }
  88. final CodeSource cs = pd.getCodeSource();
  89. if (cs == null) {
  90. throw new IllegalStateException("Unable to get the code source");
  91. }
  92. final URI uri;
  93. try {
  94. uri = cs.getLocation().toURI();
  95. } catch (URISyntaxException ex) {
  96. throw new IllegalStateException("Unable to convert location to URI", ex);
  97. }
  98. return Paths.get(uri);
  99. }
  100. /**
  101. * Recursively copies the resources specified by the given URL to the destination folder.
  102. * Existing files will be replaced.
  103. *
  104. * @param source The resource to be copied (file or folder).
  105. * @param destination The destination folder to copy the resource to.
  106. * @throws IOException If the resource couldn't be copied.
  107. */
  108. public static void copyResourcesContents(final URL source, final Path destination)
  109. throws IOException {
  110. doCopyResources(source, destination, true);
  111. }
  112. /**
  113. * Recursively copies the resources specified by the given URL to the destination folder.
  114. * Existing files will be replaced.
  115. *
  116. * @param source The resource to be copied (file or folder).
  117. * @param destination The destination folder to copy the resource to.
  118. * @throws IOException If the resource couldn't be copied.
  119. */
  120. public static void copyResources(final URL source, final Path destination) throws IOException {
  121. doCopyResources(source, destination, false);
  122. }
  123. private static void doCopyResources(final URL source, final Path destination,
  124. final boolean contents) throws IOException {
  125. try {
  126. final String path = source.toURI().toString();
  127. final int index = path.indexOf("!/");
  128. if (index > -1) {
  129. final String file = path.substring(0, index);
  130. final Map<String, String> env = new HashMap<>();
  131. try (final FileSystem fs = FileSystems.newFileSystem(URI.create(file), env)) {
  132. doCopyRecursively(fs.getPath(path.substring(index + 2)), destination, contents,
  133. StandardCopyOption.REPLACE_EXISTING);
  134. }
  135. } else {
  136. doCopyRecursively(Paths.get(source.toURI()), destination, contents,
  137. StandardCopyOption.REPLACE_EXISTING);
  138. }
  139. } catch (URISyntaxException ex) {
  140. throw new IOException("Unable to get source URI", ex);
  141. }
  142. }
  143. /**
  144. * Returns a {@link Path} for the specified bundled resource. If the app is running from a jar,
  145. * the resource will be backed by a Zip file system.
  146. *
  147. * @param resource The resource to get a path for
  148. * @return The path for the specified resource
  149. * @throws URISyntaxException If the resource could not be mapped to a path
  150. * @deprecated This doesn't and can't work reliably in all cases, and should be avoided.
  151. */
  152. @Deprecated
  153. public static Path getPathForResource(final URL resource) throws URISyntaxException {
  154. if (JAR_FILE_SYSTEM.isPresent()) {
  155. final String path = resource.toURI().toString();
  156. final int index = path.indexOf("!/");
  157. if (index > -1) {
  158. return JAR_FILE_SYSTEM.get().getPath(path.substring(index + 1));
  159. }
  160. // If we're running inside an OSGI framework then the classloader returns bundleresource:// URIs.
  161. // We don't have a filesystem handler for those, so instead map them on to the jar file system.
  162. // [This is hacky and horrible. It assumes that we only have one bundle, and that this class
  163. // is located in the same bundle as all of its callers.]
  164. if (path.startsWith("bundleresource://")) {
  165. return JAR_FILE_SYSTEM.get().getPath(path.substring(path.indexOf("/", 19)));
  166. }
  167. }
  168. return Paths.get(resource.toURI());
  169. }
  170. /**
  171. * Recursively copies the contents of one path to another. Once complete, a deep copy of the
  172. * source file or folder will be present in the destination directory.
  173. *
  174. * @param source The path that should be copied.
  175. * @param destination The directory to place copied files in.
  176. * @param options Options to use when copying.
  177. * @throws IOException If any files couldn't be copied.
  178. */
  179. public static void copyRecursivelyContents(final Path source, final Path destination,
  180. final CopyOption... options) throws IOException {
  181. doCopyRecursively(source, destination, true, options);
  182. }
  183. /**
  184. * Recursively copies one path to another. Once complete, a deep copy of the source file or
  185. * folder will be present in the destination directory.
  186. *
  187. * @param source The path that should be copied.
  188. * @param destination The directory to place copied files in.
  189. * @param options Options to use when copying.
  190. * @throws IOException If any files couldn't be copied.
  191. */
  192. public static void copyRecursively(final Path source, final Path destination,
  193. final CopyOption... options) throws IOException {
  194. doCopyRecursively(source, destination, false, options);
  195. }
  196. private static void doCopyRecursively(final Path source, final Path destination,
  197. final boolean contents, final CopyOption... options) throws IOException {
  198. final Path destinationPath;
  199. if (contents) {
  200. destinationPath = destination;
  201. } else {
  202. destinationPath = destination.resolve(source.getFileName().toString());
  203. }
  204. if (Files.isDirectory(source)) {
  205. Files.createDirectories(destinationPath);
  206. try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(source)) {
  207. for (Path path : directoryStream) {
  208. copyRecursively(path, destinationPath, options);
  209. }
  210. }
  211. } else {
  212. Files.copy(source, destinationPath, options);
  213. }
  214. }
  215. }