1 /*
   2  * Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.nio.file;
  27 
  28 import java.nio.file.spi.FileSystemProvider;
  29 import java.net.URI;
  30 import java.io.IOException;
  31 import java.security.AccessController;
  32 import java.security.PrivilegedAction;
  33 import java.lang.reflect.Constructor;
  34 import java.util.Collections;
  35 import java.util.Map;
  36 import java.util.ServiceConfigurationError;
  37 import java.util.ServiceLoader;
  38 
  39 import jdk.internal.misc.VM;
  40 import sun.nio.fs.DefaultFileSystemProvider;
  41 
  42 /**
  43  * Factory methods for file systems. This class defines the {@link #getDefault
  44  * getDefault} method to get the default file system and factory methods to
  45  * construct other types of file systems.
  46  *
  47  * <p> The first invocation of any of the methods defined by this class causes
  48  * the default {@link FileSystemProvider provider} to be loaded. The default
  49  * provider, identified by the URI scheme "file", creates the {@link FileSystem}
  50  * that provides access to the file systems accessible to the Java virtual
  51  * machine. If the process of loading or initializing the default provider fails
  52  * then an unspecified error is thrown.
  53  *
  54  * <p> The first invocation of the {@link FileSystemProvider#installedProviders()
  55  * installedProviders} method, by way of invoking any of the {@code
  56  * newFileSystem} methods defined by this class, locates and loads all
  57  * installed file system providers. Installed providers are loaded using the
  58  * service-provider loading facility defined by the {@link ServiceLoader} class.
  59  * Installed providers are loaded using the system class loader. If the
  60  * system class loader cannot be found then the platform class loader is used.
  61  * Providers are typically installed by placing them in a JAR file on the
  62  * application class path, the JAR file contains a
  63  * provider-configuration file named {@code java.nio.file.spi.FileSystemProvider}
  64  * in the resource directory {@code META-INF/services}, and the file lists one or
  65  * more fully-qualified names of concrete subclass of {@link FileSystemProvider}
  66  * that have a zero argument constructor.
  67  * The ordering that installed providers are located is implementation specific.
  68  * If a provider is instantiated and its {@link FileSystemProvider#getScheme()
  69  * getScheme} returns the same URI scheme of a provider that was previously
  70  * instantiated then the most recently instantiated duplicate is discarded. URI
  71  * schemes are compared without regard to case. During construction a provider
  72  * may safely access files associated with the default provider but care needs
  73  * to be taken to avoid circular loading of other installed providers. If
  74  * circular loading of installed providers is detected then an unspecified error
  75  * is thrown.
  76  *
  77  * <p> This class also defines factory methods that allow a {@link ClassLoader}
  78  * to be specified when locating a provider. As with installed providers, the
  79  * provider classes are identified by placing the provider configuration file
  80  * in the resource directory {@code META-INF/services}.
  81  *
  82  * <p> If a thread initiates the loading of the installed file system providers
  83  * and another thread invokes a method that also attempts to load the providers
  84  * then the method will block until the loading completes.
  85  *
  86  * @since 1.7
  87  */
  88 
  89 public final class FileSystems {
  90     private FileSystems() { }
  91 
  92     // lazy initialization of default file system
  93     private static class DefaultFileSystemHolder {
  94         static final FileSystem defaultFileSystem = defaultFileSystem();
  95 
  96         // returns default file system
  97         private static FileSystem defaultFileSystem() {
  98             // load default provider
  99             FileSystemProvider provider = AccessController
 100                 .doPrivileged(new PrivilegedAction<>() {
 101                     public FileSystemProvider run() {
 102                         return getDefaultProvider();
 103                     }
 104                 });
 105 
 106             // return file system
 107             return provider.getFileSystem(URI.create("file:///"));
 108         }
 109 
 110         // returns default provider
 111         private static FileSystemProvider getDefaultProvider() {
 112             // start with the platform's default file system provider
 113             FileSystemProvider provider = DefaultFileSystemProvider.instance();
 114 
 115             // if the property java.nio.file.spi.DefaultFileSystemProvider is
 116             // set then its value is the name of the default provider (or a list)
 117             String prop = "java.nio.file.spi.DefaultFileSystemProvider";
 118             String propValue = System.getProperty(prop);
 119             if (propValue != null) {
 120                 for (String cn: propValue.split(",")) {
 121                     try {
 122                         Class<?> c = Class
 123                             .forName(cn, true, ClassLoader.getSystemClassLoader());
 124                         Constructor<?> ctor = c
 125                             .getDeclaredConstructor(FileSystemProvider.class);
 126                         provider = (FileSystemProvider)ctor.newInstance(provider);
 127 
 128                         // must be "file"
 129                         if (!provider.getScheme().equals("file"))
 130                             throw new Error("Default provider must use scheme 'file'");
 131 
 132                     } catch (Exception x) {
 133                         throw new Error(x);
 134                     }
 135                 }
 136             }
 137             return provider;
 138         }
 139     }
 140 
 141     /**
 142      * Returns the default {@code FileSystem}. The default file system creates
 143      * objects that provide access to the file systems accessible to the Java
 144      * virtual machine. The <em>working directory</em> of the file system is
 145      * the current user directory, named by the system property {@code user.dir}.
 146      * This allows for interoperability with the {@link java.io.File java.io.File}
 147      * class.
 148      *
 149      * <p> The first invocation of any of the methods defined by this class
 150      * locates the default {@link FileSystemProvider provider} object. Where the
 151      * system property {@code java.nio.file.spi.DefaultFileSystemProvider} is
 152      * not defined then the default provider is a system-default provider that
 153      * is invoked to create the default file system.
 154      *
 155      * <p> If the system property {@code java.nio.file.spi.DefaultFileSystemProvider}
 156      * is defined then it is taken to be a list of one or more fully-qualified
 157      * names of concrete provider classes identified by the URI scheme
 158      * {@code "file"}. Where the property is a list of more than one name then
 159      * the names are separated by a comma. Each class is loaded, using the system
 160      * class loader, and instantiated by invoking a one argument constructor
 161      * whose formal parameter type is {@code FileSystemProvider}. The providers
 162      * are loaded and instantiated in the order they are listed in the property.
 163      * If this process fails or a provider's scheme is not equal to {@code "file"}
 164      * then an unspecified error is thrown. URI schemes are normally compared
 165      * without regard to case but for the default provider, the scheme is
 166      * required to be {@code "file"}. The first provider class is instantiated
 167      * by invoking it with a reference to the system-default provider.
 168      * The second provider class is instantiated by invoking it with a reference
 169      * to the first provider instance. The third provider class is instantiated
 170      * by invoking it with a reference to the second instance, and so on. The
 171      * last provider to be instantiated becomes the default provider; its {@code
 172      * getFileSystem} method is invoked with the URI {@code "file:///"} to
 173      * get a reference to the default file system.
 174      *
 175      * <p> Subsequent invocations of this method return the file system that was
 176      * returned by the first invocation.
 177      *
 178      * @return  the default file system
 179      */
 180     public static FileSystem getDefault() {
 181         if (VM.isModuleSystemInited()) {
 182             return DefaultFileSystemHolder.defaultFileSystem;
 183         } else {
 184             // always use the platform's default file system during startup
 185             return DefaultFileSystemProvider.theFileSystem();
 186         }
 187     }
 188 
 189     /**
 190      * Returns a reference to an existing {@code FileSystem}.
 191      *
 192      * <p> This method iterates over the {@link FileSystemProvider#installedProviders()
 193      * installed} providers to locate the provider that is identified by the URI
 194      * {@link URI#getScheme scheme} of the given URI. URI schemes are compared
 195      * without regard to case. The exact form of the URI is highly provider
 196      * dependent. If found, the provider's {@link FileSystemProvider#getFileSystem
 197      * getFileSystem} method is invoked to obtain a reference to the {@code
 198      * FileSystem}.
 199      *
 200      * <p> Once a file system created by this provider is {@link FileSystem#close
 201      * closed} it is provider-dependent if this method returns a reference to
 202      * the closed file system or throws {@link FileSystemNotFoundException}.
 203      * If the provider allows a new file system to be created with the same URI
 204      * as a file system it previously created then this method throws the
 205      * exception if invoked after the file system is closed (and before a new
 206      * instance is created by the {@link #newFileSystem newFileSystem} method).
 207      *
 208      * <p> If a security manager is installed then a provider implementation
 209      * may require to check a permission before returning a reference to an
 210      * existing file system. In the case of the {@link FileSystems#getDefault
 211      * default} file system, no permission check is required.
 212      *
 213      * @param   uri  the URI to locate the file system
 214      *
 215      * @return  the reference to the file system
 216      *
 217      * @throws  IllegalArgumentException
 218      *          if the pre-conditions for the {@code uri} parameter are not met
 219      * @throws  FileSystemNotFoundException
 220      *          if the file system, identified by the URI, does not exist
 221      * @throws  ProviderNotFoundException
 222      *          if a provider supporting the URI scheme is not installed
 223      * @throws  SecurityException
 224      *          if a security manager is installed and it denies an unspecified
 225      *          permission
 226      */
 227     public static FileSystem getFileSystem(URI uri) {
 228         String scheme = uri.getScheme();
 229         for (FileSystemProvider provider: FileSystemProvider.installedProviders()) {
 230             if (scheme.equalsIgnoreCase(provider.getScheme())) {
 231                 return provider.getFileSystem(uri);
 232             }
 233         }
 234         throw new ProviderNotFoundException("Provider \"" + scheme + "\" not found");
 235     }
 236 
 237     /**
 238      * Constructs a new file system that is identified by a {@link URI}
 239      *
 240      * <p> This method iterates over the {@link FileSystemProvider#installedProviders()
 241      * installed} providers to locate the provider that is identified by the URI
 242      * {@link URI#getScheme scheme} of the given URI. URI schemes are compared
 243      * without regard to case. The exact form of the URI is highly provider
 244      * dependent. If found, the provider's {@link FileSystemProvider#newFileSystem(URI,Map)
 245      * newFileSystem(URI,Map)} method is invoked to construct the new file system.
 246      *
 247      * <p> Once a file system is {@link FileSystem#close closed} it is
 248      * provider-dependent if the provider allows a new file system to be created
 249      * with the same URI as a file system it previously created.
 250      *
 251      * <p> <b>Usage Example:</b>
 252      * Suppose there is a provider identified by the scheme {@code "memory"}
 253      * installed:
 254      * <pre>
 255      *   Map&lt;String,String&gt; env = new HashMap&lt;&gt;();
 256      *   env.put("capacity", "16G");
 257      *   env.put("blockSize", "4k");
 258      *   FileSystem fs = FileSystems.newFileSystem(URI.create("memory:///?name=logfs"), env);
 259      * </pre>
 260      *
 261      * @param   uri
 262      *          the URI identifying the file system
 263      * @param   env
 264      *          a map of provider specific properties to configure the file system;
 265      *          may be empty
 266      *
 267      * @return  a new file system
 268      *
 269      * @throws  IllegalArgumentException
 270      *          if the pre-conditions for the {@code uri} parameter are not met,
 271      *          or the {@code env} parameter does not contain properties required
 272      *          by the provider, or a property value is invalid
 273      * @throws  FileSystemAlreadyExistsException
 274      *          if the file system has already been created
 275      * @throws  ProviderNotFoundException
 276      *          if a provider supporting the URI scheme is not installed
 277      * @throws  IOException
 278      *          if an I/O error occurs creating the file system
 279      * @throws  SecurityException
 280      *          if a security manager is installed and it denies an unspecified
 281      *          permission required by the file system provider implementation
 282      */
 283     public static FileSystem newFileSystem(URI uri, Map<String,?> env)
 284         throws IOException
 285     {
 286         return newFileSystem(uri, env, null);
 287     }
 288 
 289     /**
 290      * Constructs a new file system that is identified by a {@link URI}
 291      *
 292      * <p> This method first attempts to locate an installed provider in exactly
 293      * the same manner as the {@link #newFileSystem(URI,Map) newFileSystem(URI,Map)}
 294      * method. If none of the installed providers support the URI scheme then an
 295      * attempt is made to locate the provider using the given class loader. If a
 296      * provider supporting the URI scheme is located then its {@link
 297      * FileSystemProvider#newFileSystem(URI,Map) newFileSystem(URI,Map)} is
 298      * invoked to construct the new file system.
 299      *
 300      * @param   uri
 301      *          the URI identifying the file system
 302      * @param   env
 303      *          a map of provider specific properties to configure the file system;
 304      *          may be empty
 305      * @param   loader
 306      *          the class loader to locate the provider or {@code null} to only
 307      *          attempt to locate an installed provider
 308      *
 309      * @return  a new file system
 310      *
 311      * @throws  IllegalArgumentException
 312      *          if the pre-conditions for the {@code uri} parameter are not met,
 313      *          or the {@code env} parameter does not contain properties required
 314      *          by the provider, or a property value is invalid
 315      * @throws  FileSystemAlreadyExistsException
 316      *          if the URI scheme identifies an installed provider and the file
 317      *          system has already been created
 318      * @throws  ProviderNotFoundException
 319      *          if a provider supporting the URI scheme is not found
 320      * @throws  ServiceConfigurationError
 321      *          when an error occurs while loading a service provider
 322      * @throws  IOException
 323      *          an I/O error occurs creating the file system
 324      * @throws  SecurityException
 325      *          if a security manager is installed and it denies an unspecified
 326      *          permission required by the file system provider implementation
 327      */
 328     public static FileSystem newFileSystem(URI uri, Map<String,?> env, ClassLoader loader)
 329         throws IOException
 330     {
 331         String scheme = uri.getScheme();
 332 
 333         // check installed providers
 334         for (FileSystemProvider provider : FileSystemProvider.installedProviders()) {
 335             if (scheme.equalsIgnoreCase(provider.getScheme())) {
 336                 try {
 337                     return provider.newFileSystem(uri, env);
 338                 } catch (UnsupportedOperationException uoe) {
 339                 }
 340             }
 341         }
 342 
 343         // if not found, use service-provider loading facility
 344         if (loader != null) {
 345             ServiceLoader<FileSystemProvider> sl = ServiceLoader
 346                 .load(FileSystemProvider.class, loader);
 347             for (FileSystemProvider provider : sl) {
 348                 if (scheme.equalsIgnoreCase(provider.getScheme())) {
 349                     try {
 350                         return provider.newFileSystem(uri, env);
 351                     } catch (UnsupportedOperationException uoe) {
 352                     }
 353                 }
 354             }
 355         }
 356 
 357         throw new ProviderNotFoundException("Provider \"" + scheme + "\" not found");
 358     }
 359 
 360     /**
 361      * Constructs a new {@code FileSystem} to access the contents of a file as a
 362      * file system.
 363      *
 364      * <p> This method makes use of specialized providers that create pseudo file
 365      * systems where the contents of one or more files is treated as a file
 366      * system.
 367      *
 368      * <p> This method iterates over the {@link FileSystemProvider#installedProviders()
 369      * installed} providers. It invokes, in turn, each provider's {@link
 370      * FileSystemProvider#newFileSystem(Path,Map) newFileSystem(Path,Map)} method
 371      * with an empty map. If a provider returns a file system then the iteration
 372      * terminates and the file system is returned. If none of the installed
 373      * providers return a {@code FileSystem} then an attempt is made to locate
 374      * the provider using the given class loader. If a provider returns a file
 375      * system then the lookup terminates and the file system is returned.
 376      *
 377      * @param   path
 378      *          the path to the file
 379      * @param   loader
 380      *          the class loader to locate the provider or {@code null} to only
 381      *          attempt to locate an installed provider
 382      *
 383      * @return  a new file system
 384      *
 385      * @throws  ProviderNotFoundException
 386      *          if a provider supporting this file type cannot be located
 387      * @throws  ServiceConfigurationError
 388      *          when an error occurs while loading a service provider
 389      * @throws  IOException
 390      *          if an I/O error occurs
 391      * @throws  SecurityException
 392      *          if a security manager is installed and it denies an unspecified
 393      *          permission
 394      */
 395     public static FileSystem newFileSystem(Path path,
 396                                            ClassLoader loader)
 397         throws IOException
 398     {
 399         if (path == null)
 400             throw new NullPointerException();
 401         Map<String,?> env = Collections.emptyMap();
 402 
 403         // check installed providers
 404         for (FileSystemProvider provider: FileSystemProvider.installedProviders()) {
 405             try {
 406                 return provider.newFileSystem(path, env);
 407             } catch (UnsupportedOperationException uoe) {
 408             }
 409         }
 410 
 411         // if not found, use service-provider loading facility
 412         if (loader != null) {
 413             ServiceLoader<FileSystemProvider> sl = ServiceLoader
 414                 .load(FileSystemProvider.class, loader);
 415             for (FileSystemProvider provider: sl) {
 416                 try {
 417                     return provider.newFileSystem(path, env);
 418                 } catch (UnsupportedOperationException uoe) {
 419                 }
 420             }
 421         }
 422 
 423         throw new ProviderNotFoundException("Provider not found");
 424     }
 425 }