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

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