Java Code Examples for java.nio.file.FileSystems#getFileSystem()

The following examples show how to use java.nio.file.FileSystems#getFileSystem() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Basic.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test the URI of every file in the jrt file system
 */
@Test
public void testToAndFromUri() throws Exception {
    FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
    Path top = fs.getPath("/");
    try (Stream<Path> stream = Files.walk(top)) {
        stream.forEach(path -> {
            URI u = path.toUri();
            assertTrue(u.getScheme().equalsIgnoreCase("jrt"));
            assertFalse(u.isOpaque());
            assertTrue(u.getAuthority() == null);
            assertEquals(u.getPath(), path.toAbsolutePath().toString());
            Path p = Paths.get(u);
            assertEquals(p, path);
        });
    }
}
 
Example 2
Source File: FileSystemUtils.java    From vind with Apache License 2.0 6 votes vote down vote up
/**
 * Convert a local URL (file:// or jar:// protocol) to a {@link Path}
 * @param resource the URL resource
 * @return the Path
 * @throws URISyntaxException
 * @throws IOException
 */
public static Path toPath(URL resource) throws IOException, URISyntaxException {
    if (resource == null) return null;

    final String protocol = resource.getProtocol();
    if ("file".equals(protocol)) {
        return Paths.get(resource.toURI());
    } else if ("jar".equals(protocol)) {
        final String s = resource.toString();
        final int separator = s.indexOf("!/");
        final String entryName = s.substring(separator + 2);
        final URI fileURI = URI.create(s.substring(0, separator));

        final FileSystem fileSystem;
        synchronized (jarFileSystems) {
            if (jarFileSystems.add(fileURI)) {
                fileSystem = FileSystems.newFileSystem(fileURI, Collections.<String, Object>emptyMap());
            } else {
                fileSystem = FileSystems.getFileSystem(fileURI);
            }
        }
        return fileSystem.getPath(entryName);
    } else {
        throw new IOException("Can't read " + resource + ", unknown protocol '" + protocol + "'");
    }
}
 
Example 3
Source File: Basic.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "topLevelPkgDirs")
public void testNotExists(String path) throws Exception {
    FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
    Path dir = fs.getPath(path);

    // package directories should not be there at top level
    assertTrue(Files.notExists(dir));
}
 
Example 4
Source File: FileSystemManager.java    From clouditor with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a {@link Path} for a given path to a resource.
 *
 * @param resource the resource path
 * @param clazz the class to get the resource from
 * @return a {@link Path} to the resource
 * @throws IOException if the resource was not found or another error occured
 */
public Path getPathForResource(@NotNull String resource, Class<?> clazz) throws IOException {
  URL url = Component.class.getClassLoader().getResource(resource);
  // try directly with class
  if (url == null) {
    // then try with class loader, i.e. for tests
    url = clazz.getResource(resource);
    // if we cannot create an URL, directly try Paths.get()
    if (url == null) {
      return Paths.get(resource);
    }
  }

  URI uri;
  try {
    uri = url.toURI();
  } catch (URISyntaxException ex) {
    throw new IOException(ex);
  }

  /*
   * we need to "register" the specific file system first before we
   * can use Paths.get()
   */
  if ("jar".equals(uri.getScheme())) {
    // this will just register the handler so we can use it for Paths
    try {
      FileSystems.getFileSystem(uri);
    } catch (FileSystemNotFoundException e) {
      jarFileSystem = FileSystems.newFileSystem(uri, Collections.singletonMap("create", true));
      // just to be safe, ignore if we somehow accidentally register it twice
      LOGGER.info("Creating jar file system for URI {}", uri);
    }
  }

  return Paths.get(uri);
}
 
Example 5
Source File: TestClassLoading.java    From openjdk-systemtest with Apache License 2.0 5 votes vote down vote up
@Test
public void readClassBytes() throws Exception {
	FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
	Path path = fs.getPath("/modules/java.base", "java/lang/Object.class");
	byte[]	jlo	= Files.readAllBytes(path);

	assertNotNull("Can not read bytes of class java/lang/Object.class", jlo);
	assertTrue("Empty byte array returned for java/lang/Object.class", jlo.length != 0);
}
 
Example 6
Source File: Basic.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "pathGlobPatterns")
public void testGlobPathMatcher(String pattern, String path,
        boolean expectMatch) throws Exception {
    FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
    PathMatcher pm = fs.getPathMatcher("glob:" + pattern);
    Path p = fs.getPath(path);
    assertTrue(Files.exists(p), path);
    assertTrue(!(pm.matches(p) ^ expectMatch),
        p + (expectMatch? " should match " : " should not match ") +
        pattern);
}
 
Example 7
Source File: SwingContainerIsForContainerOnly.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
    fs.getFileStores();
    Files.walkFileTree(fs.getPath("/modules/java.desktop"), new SimpleFileVisitor<>() {
        @Override
        public FileVisitResult visitFile(Path file,
                                         BasicFileAttributes attrs) {
            file = file.subpath(2, file.getNameCount());
            String name = file.toString();
            if (name.endsWith(".class")) {
                name = name.substring(0, name.indexOf(".")).replace('/', '.');

                final Class<?> type;
                try {
                    type = Class.forName(name, false, null);
                } catch (Throwable e) {
                    return FileVisitResult.CONTINUE;
                }
                if (type.isAnnotationPresent(SwingContainer.class)) {
                    if (!Container.class.isAssignableFrom(type)) {
                        System.err.println("Wrong annotation for: " + type);
                        throw new RuntimeException();
                    }
                }
            }
            return FileVisitResult.CONTINUE;
        };
    });
}
 
Example 8
Source File: NotificationInfoTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static Set<String> findStandardMBeansFromRuntime() throws Exception {
    FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
    Path modules = fs.getPath("/modules");
    return Files.walk(modules)
            .filter(path -> path.toString().endsWith(".class"))
            .map(path -> path.subpath(2, path.getNameCount()))
            .map(Path::toString)
            .map(s -> s.substring(0, s.length() - 6))  // drop .class
            .filter(s -> !s.equals("module-info"))
            .map(s -> s.replace('/', '.'))
            .collect(Collectors.toSet());
}
 
Example 9
Source File: Basic.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "packagesLinks")
public void testPackagesLinks(String link) throws Exception {
    FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
    Path path = fs.getPath(link);
    assertTrue(Files.exists(path), link + " missing");
    assertTrue(Files.isSymbolicLink(path), path + " is not a link");
    path = Files.readSymbolicLink(path);
    assertEquals(path.toString(), "/modules" + link.substring(link.lastIndexOf("/")));
}
 
Example 10
Source File: Basic.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "modulesSubDirs")
public void testModulesSubDirs(String module) throws Exception {
    FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
    Path path = fs.getPath("/modules/" + module);
    assertTrue(Files.isDirectory(path), module + " missing");
    assertTrue(!Files.isSymbolicLink(path), path + " is a link");
}
 
Example 11
Source File: Task.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
static List<Class<?>> getClasses(int count) throws Exception {
    List<Class<?>> classes = new ArrayList<>();
    FileSystem fs = null;

    try {
        fs = FileSystems.getFileSystem(URI.create("jrt:/"));
    } catch (ProviderNotFoundException | FileSystemNotFoundException e) {
        throw new RuntimeException("FAIL - JRT Filesystem not found");
    }

    List<String> fileNames;
    Path modules = fs.getPath("/modules");

    Predicate<String> startsWithJavaBase          = path -> path.toString().startsWith("java.base/java");
    Predicate<String> startsWithJavaDesktop       = path -> path.toString().startsWith("java.desktop/java");
    Predicate<String> startsWithJavaDataTransfer  = path -> path.toString().startsWith("java.datatransfer/java");
    Predicate<String> startsWithJavaRMI           = path -> path.toString().startsWith("java.rmi/java");
    Predicate<String> startsWithJavaSmartCardIO   = path -> path.toString().startsWith("java.smartcardio/java");
    Predicate<String> startsWithJavaManagement    = path -> path.toString().startsWith("java.management/java");
    Predicate<String> startsWithJavaXML           = path -> path.toString().startsWith("java.xml/java");
    Predicate<String> startsWithJavaXMLBind       = path -> path.toString().startsWith("java.xml.bind/java");
    Predicate<String> startsWithJavaScripting     = path -> path.toString().startsWith("java.scripting/java");
    Predicate<String> startsWithJavaNaming        = path -> path.toString().startsWith("java.naming/java");
    Predicate<String> startsWithJavaSQL           = path -> path.toString().startsWith("java.sql/java");
    Predicate<String> startsWithJavaActivation    = path -> path.toString().startsWith("java.activation/java");
    Predicate<String> startsWithJavaCompiler      = path -> path.toString().startsWith("java.compiler/java");
    Predicate<String> startsWithJavaAnnotations   = path -> path.toString().startsWith("java.annotations/java");
    Predicate<String> startsWithJavaTransaction   = path -> path.toString().startsWith("java.transaction/java");
    Predicate<String> startsWithJavaLogging       = path -> path.toString().startsWith("java.logging/java");
    Predicate<String> startsWithJavaCorba         = path -> path.toString().startsWith("java.corba/java");
    Predicate<String> startsWithJavaPrefs         = path -> path.toString().startsWith("java.prefs/java");

    fileNames = Files.walk(modules)
            .map(Path::toString)
            .filter(path -> path.toString().contains("java"))
            .map(s -> s.substring(9))  // remove /modules/ from beginning
            .filter(startsWithJavaBase
                .or(startsWithJavaDesktop)
                .or(startsWithJavaDataTransfer)
                .or(startsWithJavaRMI)
                .or(startsWithJavaSmartCardIO)
                .or(startsWithJavaManagement)
                .or(startsWithJavaXML)
                .or(startsWithJavaXMLBind)
                .or(startsWithJavaScripting)
                .or(startsWithJavaNaming)
                .or(startsWithJavaSQL)
                .or(startsWithJavaActivation)
                .or(startsWithJavaCompiler)
                .or(startsWithJavaAnnotations)
                .or(startsWithJavaTransaction)
                .or(startsWithJavaLogging)
                .or(startsWithJavaCorba)
                .or(startsWithJavaPrefs))
            .map(s -> s.replace('/', '.'))
            .filter(path -> path.toString().endsWith(".class"))
            .map(s -> s.substring(0, s.length() - 6))  // drop .class
            .map(s -> s.substring(s.indexOf(".")))
            .filter(path -> path.toString().contains("java"))
            .map(s -> s.substring(s.indexOf("java")))
            .collect(Collectors.toList());

    for (String name : fileNames) {
        classes.add(Class.forName(name));
        if (count == classes.size()) {
            break;
        }
    }

    return classes;
}
 
Example 12
Source File: Basic.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test(dataProvider = "packagesSubDirs")
public void testPackagesSubDirs(String pkg) throws Exception {
    FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
    assertTrue(Files.isDirectory(fs.getPath("/packages/" + pkg)),
        pkg + " missing");
}
 
Example 13
Source File: Basic.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testPackagesAndModules() throws Exception {
    FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
    assertTrue(Files.isDirectory(fs.getPath("/packages")));
    assertTrue(Files.isDirectory(fs.getPath("/modules")));
}
 
Example 14
Source File: JRTIndex.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Create and initialize the index.
 */
private JRTIndex() throws IOException {
    jrtfs = FileSystems.getFileSystem(URI.create("jrt:/"));
    entries = new HashMap<>();
}
 
Example 15
Source File: Locations.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private void initSystemModules() throws IOException {
    if (moduleTable != null)
        return;

    if (systemJavaHome == null) {
        moduleTable = new ModuleTable();
        return;
    }

    if (modules == null) {
        try {
            URI jrtURI = URI.create("jrt:/");
            FileSystem jrtfs;

            if (isCurrentPlatform(systemJavaHome)) {
                jrtfs = FileSystems.getFileSystem(jrtURI);
            } else {
                try {
                    Map<String, String> attrMap =
                            Collections.singletonMap("java.home", systemJavaHome.toString());
                    jrtfs = FileSystems.newFileSystem(jrtURI, attrMap);
                } catch (ProviderNotFoundException ex) {
                    URL javaHomeURL = systemJavaHome.resolve("jrt-fs.jar").toUri().toURL();
                    ClassLoader currentLoader = Locations.class.getClassLoader();
                    URLClassLoader fsLoader =
                            new URLClassLoader(new URL[] {javaHomeURL}, currentLoader);

                    jrtfs = FileSystems.newFileSystem(jrtURI, Collections.emptyMap(), fsLoader);

                    closeables.add(fsLoader);
                }

                closeables.add(jrtfs);
            }

            modules = jrtfs.getPath("/modules");
        } catch (FileSystemNotFoundException | ProviderNotFoundException e) {
            modules = systemJavaHome.resolve("modules");
            if (!Files.exists(modules))
                throw new IOException("can't find system classes", e);
        }
    }

    moduleTable = new ModuleTable();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(modules, Files::isDirectory)) {
        for (Path entry : stream) {
            String moduleName = entry.getFileName().toString();
            String name = location.getName() + "[" + moduleName + "]";
            ModuleLocationHandler h = new ModuleLocationHandler(this,
                    name, moduleName, Collections.singletonList(entry), false);
            moduleTable.add(h);
        }
    }
}
 
Example 16
Source File: ModuleSourceProvider.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public ModuleSourceProvider() {
    this(FileSystems.getFileSystem(URI.create("jrt:/")), ClassLoader.getSystemClassLoader(), new FileSupport());
}
 
Example 17
Source File: PathOps.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Throwable {
    fs = FileSystems.getFileSystem(URI.create("jrt:/"));
    npes();
    doPathOpTests();
}
 
Example 18
Source File: FileSystemsTest.java    From openjdk-systemtest with Apache License 2.0 4 votes vote down vote up
public void testFileSystemIsRegistered() throws URISyntaxException {

		// Check that the expected "memory0" FileSystem is available
		boolean foundInitialProvider = false;

		for (FileSystemProvider provider: FileSystemProvider.installedProviders()) {
			if (provider.getScheme().equalsIgnoreCase("memory0")) {
				foundInitialProvider = true;
			}
		}

		assertTrue("Unable to find intial provider 'memory0'", foundInitialProvider);


		FileSystem memoryFileSystem = FileSystems.getFileSystem(new URI("memory0:///"));
		assertNotNull("Returned memoryFileSystem for 'memory0:///' was null", memoryFileSystem);

		String filename = "bargh";
		assertNotNull("Returned filename for 'memory0:///"+filename+"' was null", memoryFileSystem.getPath(filename));
		
		assertEquals("MemoryFileSystem did not return the expected string representation",
				"/memory/" + filename, memoryFileSystem.getPath(filename).toString());


	}
 
Example 19
Source File: CompressorPluginTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public void test() throws Exception {
    FileSystem fs;
    try {
        fs = FileSystems.getFileSystem(URI.create("jrt:/"));
    } catch (ProviderNotFoundException | FileSystemNotFoundException e) {
        System.err.println("Not an image build, test skipped.");
        return;
    }
    Path javabase = fs.getPath("/modules/java.base");

    checkCompress(gatherResources(javabase), new ZipPlugin(), null,
            new ResourceDecompressorFactory[]{
                new ZipDecompressorFactory()
            });

    ResourcePool classes = gatherClasses(javabase);
    // compress = String sharing
    checkCompress(classes, new StringSharingPlugin(), null,
            new ResourceDecompressorFactory[]{
                new StringSharingDecompressorFactory()});

    // compress level 0 == no compression
    Properties options0 = new Properties();
    options0.setProperty(DefaultCompressPlugin.NAME,
            "0");
    checkCompress(classes, new DefaultCompressPlugin(),
            options0,
            new ResourceDecompressorFactory[]{
            });

    // compress level 1 == String sharing
    Properties options1 = new Properties();
    options1.setProperty(DefaultCompressPlugin.NAME, "1");
    checkCompress(classes, new DefaultCompressPlugin(),
            options1,
            new ResourceDecompressorFactory[]{
                new StringSharingDecompressorFactory()
            });

    // compress level 1 == String sharing + filter
    options1.setProperty(DefaultCompressPlugin.FILTER,
            "**Exception.class");
    options1.setProperty(DefaultCompressPlugin.NAME, "1");
    checkCompress(classes, new DefaultCompressPlugin(),
            options1,
            new ResourceDecompressorFactory[]{
                new StringSharingDecompressorFactory()
            }, Collections.singletonList(".*Exception.class"));

    // compress level 2 == ZIP
    Properties options2 = new Properties();
    options2.setProperty(DefaultCompressPlugin.FILTER,
            "**Exception.class");
    options2.setProperty(DefaultCompressPlugin.NAME, "2");
    checkCompress(classes, new DefaultCompressPlugin(),
            options2,
            new ResourceDecompressorFactory[]{
                new ZipDecompressorFactory()
            }, Collections.singletonList(".*Exception.class"));

    // compress level 2 == ZIP + filter
    options2.setProperty(DefaultCompressPlugin.FILTER,
            "**Exception.class");
    options2.setProperty(DefaultCompressPlugin.NAME, "2");
    checkCompress(classes, new DefaultCompressPlugin(),
            options2,
            new ResourceDecompressorFactory[]{
                new ZipDecompressorFactory(),
            }, Collections.singletonList(".*Exception.class"));
}
 
Example 20
Source File: ModularRuntimeImage.java    From Bytecoder with Apache License 2.0 2 votes vote down vote up
/**
 * Constructs a default instance.
 *
 * @throws IOException
 *             an I/O error occurs accessing the file system
 */
public ModularRuntimeImage() throws IOException {
    this(null, FileSystems.getFileSystem(URI.create("jrt:/")));
}