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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. /*
  2. * Copyright (c) 2006-2014 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. return getApplicationPath(clazz).getFileName().toString().endsWith(".jar");
  72. }
  73. /**
  74. * Returns the base location for the specified class, this is either the a jar or a folder
  75. * depending on how the application was launched.
  76. *
  77. * This can fail for a number of reasons, it is not wholly reliable.
  78. *
  79. * @param clazz Class used to locate the application
  80. *
  81. * @return A {@link Path} to application location
  82. *
  83. * @throws IllegalStateException If the application path cannot be determined for any reason
  84. */
  85. public static Path getApplicationPath(final Class<?> clazz) throws IllegalStateException {
  86. final ProtectionDomain pd;
  87. try {
  88. pd = clazz.getProtectionDomain();
  89. } catch (SecurityException ex) {
  90. throw new IllegalStateException("Unable to get protection domain", ex);
  91. }
  92. final CodeSource cs = pd.getCodeSource();
  93. if (cs == null) {
  94. throw new IllegalStateException("Unable to get the code source");
  95. }
  96. final URI uri;
  97. try {
  98. uri = cs.getLocation().toURI();
  99. } catch (URISyntaxException ex) {
  100. throw new IllegalStateException("Unable to convert location to URI", ex);
  101. }
  102. return Paths.get(uri);
  103. }
  104. /**
  105. * Recursively copies the resources specified by the given URL to the destination folder.
  106. * Existing files will be replaced.
  107. *
  108. * @param source The resource to be copied (file or folder).
  109. * @param destination The destination folder to copy the resource to.
  110. * @throws IOException If the resource couldn't be copied.
  111. */
  112. public static void copyResources(final URL source, final Path destination) throws IOException {
  113. try {
  114. final String path = source.toURI().toString();
  115. final int index = path.indexOf("!/");
  116. if (index > -1) {
  117. final String file = path.substring(0, index);
  118. final Map<String, String> env = new HashMap<>();
  119. try (final FileSystem fs = FileSystems.newFileSystem(URI.create(file), env)) {
  120. copyRecursively(fs.getPath(path.substring(index + 2)), destination,
  121. StandardCopyOption.REPLACE_EXISTING);
  122. }
  123. } else {
  124. copyRecursively(Paths.get(source.toURI()), destination,
  125. StandardCopyOption.REPLACE_EXISTING);
  126. }
  127. } catch (URISyntaxException ex) {
  128. throw new IOException("Unable to get source URI", ex);
  129. }
  130. }
  131. /**
  132. * Returns a {@link Path} for the specified bundled resource. If the app is running from a jar,
  133. * the resource will be backed by a Zip file system.
  134. *
  135. * @param resource The resource to get a path for
  136. * @return The path for the specified resource
  137. * @throws URISyntaxException If the resource could not be mapped to a path
  138. */
  139. public static Path getPathForResource(final URL resource) throws URISyntaxException {
  140. if (JAR_FILE_SYSTEM.isPresent()) {
  141. final String path = resource.toURI().toString();
  142. final int index = path.indexOf("!/");
  143. if (index > -1) {
  144. return JAR_FILE_SYSTEM.get().getPath(path.substring(index + 1));
  145. }
  146. }
  147. return Paths.get(resource.toURI());
  148. }
  149. /**
  150. * Recursively copies one path to another. Once complete, a deep copy of the source file or
  151. * folder will be present in the destination directory.
  152. *
  153. * @param source The path that should be copied.
  154. * @param destination The directory to place copied files in.
  155. * @param options Options to use when copying.
  156. * @throws IOException If any files couldn't be copied.
  157. */
  158. public static void copyRecursively(final Path source, final Path destination,
  159. final CopyOption... options) throws IOException {
  160. final Path destinationPath = destination.resolve(source.getFileName().toString());
  161. if (Files.isDirectory(source)) {
  162. Files.createDirectories(destinationPath);
  163. try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(source)) {
  164. for (Path path : directoryStream) {
  165. copyRecursively(path, destinationPath, options);
  166. }
  167. }
  168. } else {
  169. Files.copy(source, destinationPath, options);
  170. }
  171. }
  172. }