Java Code Examples for java.nio.file.FileSystem

The following examples show how to use java.nio.file.FileSystem. These examples are extracted from open source projects. 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 Project: update4j   Source File: Archive.java    License: Apache License 2.0 7 votes vote down vote up
public FileSystem openConnection() throws IOException {
    if (Files.notExists(getLocation())) {
        // I can't use Map.of("create", "true") since the overload taking a path was only added in JDK 13
        // and using URI overload doesn't support nested zip files
        try (OutputStream out = Files.newOutputStream(getLocation(), StandardOpenOption.CREATE_NEW)) {
            // End of Central Directory Record (EOCD)
            out.write(new byte[] { 0x50, 0x4b, 0x05, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
        }
    }

    try {
        return FileSystems.newFileSystem(getLocation(), (ClassLoader) null);
    } catch (ProviderNotFoundException e) {
        ModuleFinder.ofSystem()
                        .find("jdk.zipfs")
                        .orElseThrow(() -> new ProviderNotFoundException(
                                        "Accessing the archive depends on the jdk.zipfs module which is missing from the JRE image"));

        throw e;
    }
}
 
Example 2
Source Project: vespa   Source File: AthenzCredentialsMaintainer.java    License: Apache License 2.0 6 votes vote down vote up
public AthenzCredentialsMaintainer(URI ztsEndpoint,
                                   Path trustStorePath,
                                   ConfigServerInfo configServerInfo,
                                   String certificateDnsSuffix,
                                   ServiceIdentityProvider hostIdentityProvider,
                                   boolean useInternalZts,
                                   Clock clock,
                                   FileSystem fileSystem) {
    this.ztsEndpoint = ztsEndpoint;
    this.trustStorePath = trustStorePath;
    this.configserverIdentity = configServerInfo.getConfigServerIdentity();
    this.csrGenerator = new CsrGenerator(certificateDnsSuffix, configserverIdentity.getFullName());
    this.hostIdentityProvider = hostIdentityProvider;
    this.fileSystem = fileSystem;
    this.identityDocumentClient = new DefaultIdentityDocumentClient(
            configServerInfo.getLoadBalancerEndpoint(),
            hostIdentityProvider,
            new AthenzIdentityVerifier(Set.of(configserverIdentity)));
    this.clock = clock;
    this.useInternalZts = useInternalZts;
}
 
Example 3
Source Project: besu   Source File: FastDownloaderFactoryTest.java    License: Apache License 2.0 6 votes vote down vote up
private void initDataDirectory(final boolean isPivotBlockHeaderFileExist)
    throws NoSuchFieldException {
  final File pivotBlockHeaderFile = mock(File.class);
  when(pivotBlockHeaderFile.isFile()).thenReturn(isPivotBlockHeaderFileExist);
  when(pivotBlockHeaderFile.isDirectory()).thenReturn(true);

  final File fastSyncDirFile = mock(File.class);
  when(fastSyncDirFile.isDirectory()).thenReturn(true);

  final Path storagePath = mock(Path.class);
  final FileSystem fileSystem = mock(FileSystem.class);
  when(storagePath.getFileSystem()).thenReturn(fileSystem);
  when(fileSystem.provider()).thenReturn(mock(FileSystemProvider.class));

  final Path pivotBlockHeaderPath = mock(Path.class);
  when(pivotBlockHeaderPath.toFile()).thenReturn(pivotBlockHeaderFile);
  when(pivotBlockHeaderPath.resolve(anyString())).thenReturn(storagePath);

  final Path fastSyncDir = mock(Path.class);
  when(fastSyncDir.resolve(any(String.class))).thenReturn(pivotBlockHeaderPath);
  when(fastSyncDir.toFile()).thenReturn(fastSyncDirFile);
  when(dataDirectory.resolve(anyString())).thenReturn(fastSyncDir);
}
 
Example 4
Source Project: carbon-kernel   Source File: ConversionTest.java    License: Apache License 2.0 6 votes vote down vote up
private boolean isOSGiBundle(Path bundlePath, String bundleSymbolicName) throws IOException, CarbonToolException {
    if (Files.exists(bundlePath)) {
        boolean validSymbolicName, exportPackageAttributeCheck, importPackageAttributeCheck;
        try (FileSystem zipFileSystem = BundleGeneratorUtils.createZipFileSystem(bundlePath, false)) {
            Path manifestPath = zipFileSystem.getPath(Constants.JAR_MANIFEST_FOLDER, Constants.MANIFEST_FILE_NAME);
            Manifest manifest = new Manifest(Files.newInputStream(manifestPath));

            Attributes attributes = manifest.getMainAttributes();
            String actualBundleSymbolicName = attributes.getValue(Constants.BUNDLE_SYMBOLIC_NAME);
            validSymbolicName = ((actualBundleSymbolicName != null) && ((bundleSymbolicName != null)
                    && bundleSymbolicName.equals(actualBundleSymbolicName)));
            exportPackageAttributeCheck = attributes.getValue(Constants.EXPORT_PACKAGE) != null;
            importPackageAttributeCheck = attributes.getValue(Constants.DYNAMIC_IMPORT_PACKAGE) != null;
        }
        return (validSymbolicName && exportPackageAttributeCheck && importPackageAttributeCheck);
    } else {
        return false;
    }
}
 
Example 5
Source Project: dragonwell8_jdk   Source File: ZipCat.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * The main method for the ZipCat program. Run the program with an empty
 * argument list to see possible arguments.
 *
 * @param args the argument list for ZipCat
 */
public static void main(String[] args) {
    if (args.length != 2) {
        System.out.println("Usage: ZipCat zipfile fileToPrint");
    }
    /*
     * Creates AutoCloseable FileSystem and BufferedReader.
     * They will be closed automatically after the try block.
     * If reader initialization fails, then zipFileSystem will be closed
     * automatically.
     */
    try (FileSystem zipFileSystem
            = FileSystems.newFileSystem(Paths.get(args[0]),null);
            InputStream input
            = Files.newInputStream(zipFileSystem.getPath(args[1]))) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = input.read(buffer)) != -1) {
                    System.out.write(buffer, 0, len);
                }

    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }
}
 
Example 6
public static synchronized FileSystem open(URI uri) throws IOException {
	FileSystem ret = null;

	try {
		ret = FileSystems.getFileSystem(uri);
	} catch (FileSystemNotFoundException e) { }

	boolean opened;

	if (ret == null) {
		ret = FileSystems.newFileSystem(uri, Collections.emptyMap());
		opened = true;
	} else {
		opened = false;
	}

	RefData data = fsRefs.get(ret);

	if (data == null) {
		fsRefs.put(ret, new RefData(opened, 1));
	} else {
		data.refs++;
	}

	return ret;
}
 
Example 7
Source Project: jdk8u_jdk   Source File: FaultyFileSystem.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public FileSystem newFileSystem(Path fakeRoot, Map<String,?> env)
    throws IOException
{
    if (env != null && env.keySet().contains("IOException")) {
        triggerEx("IOException");
    }

    synchronized (FaultyFSProvider.class) {
        if (delegate != null && delegate.isOpen())
            throw new FileSystemAlreadyExistsException();
        FaultyFileSystem result = new FaultyFileSystem(fakeRoot);
        delegate = result;
        return result;
    }
}
 
Example 8
public static LocalComputationConfig load(PlatformConfig platformConfig, FileSystem fileSystem) {
    Objects.requireNonNull(platformConfig);

    Path localDir = getDefaultLocalDir(fileSystem);
    int availableCore = DEFAULT_AVAILABLE_CORE;
    if (platformConfig.moduleExists(CONFIG_MODULE_NAME)) {
        ModuleConfig config = platformConfig.getModuleConfig(CONFIG_MODULE_NAME);
        localDir = getTmpDir(config, "tmp-dir")
                       .orElseGet(() -> getTmpDir(config, "tmpDir")
                                            .orElseGet(() -> getDefaultLocalDir(fileSystem)));
        availableCore = config.getOptionalIntProperty("available-core")
                              .orElseGet(() -> config.getOptionalIntProperty("availableCore")
                                                     .orElse(DEFAULT_AVAILABLE_CORE));
    }
    if (availableCore <= 0) {
        availableCore = Runtime.getRuntime().availableProcessors();
    }
    return new LocalComputationConfig(localDir, availableCore);
}
 
Example 9
private JavaFileObject getFileForInput(Location location, String relativePath)
        throws IOException {
    for (Path p: getLocation(location)) {
        if (isDirectory(p)) {
            Path f = resolve(p, relativePath);
            if (Files.exists(f))
                return PathFileObject.createDirectoryPathFileObject(this, f, p);
        } else {
            FileSystem fs = getFileSystem(p);
            if (fs != null) {
                Path file = getPath(fs, relativePath);
                if (Files.exists(file))
                    return PathFileObject.createJarPathFileObject(this, file);
            }
        }
    }
    return null;
}
 
Example 10
Source Project: openjdk-8   Source File: FaultyFileSystem.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public FileSystem newFileSystem(Path fakeRoot, Map<String,?> env)
    throws IOException
{
    if (env != null && env.keySet().contains("IOException")) {
        triggerEx("IOException");
    }

    synchronized (FaultyFSProvider.class) {
        if (delegate != null && delegate.isOpen())
            throw new FileSystemAlreadyExistsException();
        FaultyFileSystem result = new FaultyFileSystem(fakeRoot);
        delegate = result;
        return result;
    }
}
 
Example 11
Source Project: ipst   Source File: TapChangeActionTest.java    License: Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void testToTask() throws Exception {
    Network network = PhaseShifterTestCaseFactory.create();
    PhaseTapChanger tapChanger = network.getTwoWindingsTransformer("PS1").getPhaseTapChanger();
    assertEquals(1, tapChanger.getTapPosition());


    TapChangeAction action = new TapChangeAction("PS1", 2);
    ModificationTask task = action.toTask();
    try (FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix())) {
        Path localDir = fileSystem.getPath("/tmp");
        ComputationManager computationManager = new LocalComputationManager(localDir);
        task.modify(network, computationManager);
        assertEquals(2, tapChanger.getTapPosition());

        try {
            action.toTask(null);
            fail();
        } catch (UnsupportedOperationException exc) {
        }
    }

}
 
Example 12
Source Project: rembulan   Source File: BasicLib.java    License: Apache License 2.0 6 votes vote down vote up
static LuaFunction loadTextChunkFromFile(FileSystem fileSystem, ChunkLoader loader, String fileName, ByteString modeString, Object env)
		throws LoaderException {

	final LuaFunction fn;
	try {
		Path p = fileSystem.getPath(fileName);

		if (!modeString.contains((byte) 't')) {
			throw new LuaRuntimeException("attempt to load a text chunk (mode is '" + modeString + "')");
		}

		// FIXME: this is extremely wasteful!
		byte[] bytes = Files.readAllBytes(p);
		ByteString chunkText = ByteString.copyOf(bytes);
		fn = loader.loadTextChunk(new Variable(env), fileName, chunkText.toString());
	}
	catch (InvalidPathException | IOException ex) {
		throw new LoaderException(ex, fileName);
	}

	if (fn == null) {
		throw new LuaRuntimeException("loader returned nil");
	}

	return fn;
}
 
Example 13
Source Project: quarkus   Source File: TestClassIndexer.java    License: Apache License 2.0 6 votes vote down vote up
public static Index indexTestClasses(Class<?> testClass) {
    final Indexer indexer = new Indexer();
    final Path testClassesLocation = getTestClassesLocation(testClass);
    try {
        if (Files.isDirectory(testClassesLocation)) {
            indexTestClassesDir(indexer, testClassesLocation);
        } else {
            try (FileSystem jarFs = FileSystems.newFileSystem(testClassesLocation, null)) {
                for (Path p : jarFs.getRootDirectories()) {
                    indexTestClassesDir(indexer, p);
                }
            }
        }
    } catch (IOException e) {
        throw new UncheckedIOException("Unable to index the test-classes/ directory.", e);
    }
    return indexer.complete();
}
 
Example 14
Source Project: openjdk-jdk9   Source File: ZipFSTester.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static void z2zmove(FileSystem src, FileSystem dst, String path)
    throws IOException
{
    Path srcPath = src.getPath(path);
    Path dstPath = dst.getPath(path);

    if (Files.isDirectory(srcPath)) {
        if (!Files.exists(dstPath))
            mkdirs(dstPath);
        try (DirectoryStream<Path> ds = Files.newDirectoryStream(srcPath)) {
            for (Path child : ds) {
                z2zmove(src, dst,
                        path + (path.endsWith("/")?"":"/") + child.getFileName());
            }
        }
    } else {
        //System.out.println("moving..." + path);
        Path parent = dstPath.getParent();
        if (parent != null && Files.notExists(parent))
            mkdirs(parent);
        Files.move(srcPath, dstPath);
    }
}
 
Example 15
@Override
public FileSystem newFileSystem(Path fakeRoot, Map<String,?> env)
    throws IOException
{
    if (env != null && env.keySet().contains("IOException")) {
        triggerEx("IOException");
    }

    synchronized (FaultyFSProvider.class) {
        if (delegate != null && delegate.isOpen())
            throw new FileSystemAlreadyExistsException();
        FaultyFileSystem result = new FaultyFileSystem(fakeRoot);
        delegate = result;
        return result;
    }
}
 
Example 16
Source Project: lucene-solr   Source File: TestIOUtils.java    License: Apache License 2.0 6 votes vote down vote up
public void testRotatingPlatters() throws Exception {
  assumeFalse("windows is not supported", Constants.WINDOWS);
  Path dir = createTempDir();
  dir = FilterPath.unwrap(dir).toRealPath();
  
  // fake ssd
  FileStore root = new MockFileStore(dir.toString() + " (/dev/zzz1)", "reiser4", "/dev/zzz1");
  // make a fake /dev/zzz1 for it
  Path devdir = dir.resolve("dev");
  Files.createDirectories(devdir);
  Files.createFile(devdir.resolve("zzz1"));
  // make a fake /sys/block/zzz/queue/rotational file for it
  Path sysdir = dir.resolve("sys").resolve("block").resolve("zzz").resolve("queue");
  Files.createDirectories(sysdir);
  try (OutputStream o = Files.newOutputStream(sysdir.resolve("rotational"))) {
    o.write("1\n".getBytes(StandardCharsets.US_ASCII));
  }
  Map<String,FileStore> mappings = Collections.singletonMap(dir.toString(), root);
  FileSystem mockLinux = new MockLinuxFileSystemProvider(dir.getFileSystem(), mappings, dir).getFileSystem(null);
  
  Path mockPath = mockLinux.getPath(dir.toString());
  assertTrue(IOUtils.spinsLinux(mockPath));
}
 
Example 17
Source Project: buck   Source File: PythonDslProjectBuildFileParser.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static ImmutableList<BuildFileParseExceptionStackTraceEntry> parseStackTrace(
    Map<String, Object> exceptionMap, FileSystem fileSystem) {
  List<Map<String, Object>> traceback =
      (List<Map<String, Object>>) Objects.requireNonNull(exceptionMap.get("traceback"));
  ImmutableList.Builder<BuildFileParseExceptionStackTraceEntry> stackTraceBuilder =
      ImmutableList.builder();
  for (Map<String, Object> tracebackItem : traceback) {
    stackTraceBuilder.add(
        BuildFileParseExceptionStackTraceEntry.of(
            fileSystem.getPath((String) Objects.requireNonNull(tracebackItem.get("filename"))),
            (Number) Objects.requireNonNull(tracebackItem.get("line_number")),
            (String) Objects.requireNonNull(tracebackItem.get("function_name")),
            (String) Objects.requireNonNull(tracebackItem.get("text"))));
  }
  return stackTraceBuilder.build();
}
 
Example 18
Source Project: android-arscblamer   Source File: ApkUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Finds all files in an apk that match a given regular expression.
 *
 * @param apkFile The {@link FileSystem} representation of the apk zip archive.
 * @param matcher A {@link PathMatcher} to match the requested filenames.
 * @return A list of paths matching the provided matcher.
 * @throws IOException Thrown if a matching file cannot be read from the apk.
 */
public static ImmutableList<Path> findFiles(FileSystem apkFile, PathMatcher matcher)
    throws IOException {
  ImmutableList.Builder<Path> result = ImmutableList.builder();
  Path root = apkFile.getPath("/");
  Files.walkFileTree(
      root,
      new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path p, BasicFileAttributes attrs) throws IOException {
          if (matcher.matches(p) || matcher.matches(p.normalize())) {
            result.add(
                // fancy way of eliding leading slash
                root.relativize(p));
          }
          return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException e) {
          return FileVisitResult.SKIP_SUBTREE;
        }
      });
  return result.build();
}
 
Example 19
/**
 * Thread-safe ClosedFileSystemException test
 * 
 * @return
 */
protected FileSystem getOrigFS() {
	FileSystem orig = origFS;
	if (orig == null || !orig.isOpen()) {
		throw new ClosedFileSystemException();
	}
	return orig;
}
 
Example 20
Source Project: copybara   Source File: FolderOrigin.java    License: Apache License 2.0 5 votes vote down vote up
FolderOrigin(FileSystem fs, Author author, String message, Path cwd,
    boolean materializeOutsideSymlinks, boolean ignoreInvalidSymlinks) {
  this.fs = Preconditions.checkNotNull(fs);
  this.author = author;
  this.message = message;
  this.cwd = Preconditions.checkNotNull(cwd);
  this.copySymlinkStrategy = ignoreInvalidSymlinks
          ? CopySymlinkStrategy.IGNORE_INVALID_SYMLINKS
          : materializeOutsideSymlinks
              ? CopySymlinkStrategy.MATERIALIZE_OUTSIDE_SYMLINKS
              : CopySymlinkStrategy.FAIL_OUTSIDE_SYMLINKS;
}
 
Example 21
private FileSystem getFileSystem(Path p) throws IOException {
    FileSystem fs = fileSystems.get(p);
    if (fs == null) {
        fs = FileSystems.newFileSystem(p, null);
        fileSystems.put(p, fs);
    }
    return fs;
}
 
Example 22
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 23
Source Project: gate-core   Source File: Plugin.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
public void walkResources(FileVisitor<? super Path> visitor) throws URISyntaxException, IOException {
  try (FileSystem zipFs =
               FileSystems.newFileSystem(artifactURL.toURI(), new HashMap<>())) {
    Path resourcesPath = zipFs.getPath("/resources");
    if(Files.isDirectory(resourcesPath)) {
      Files.walkFileTree(resourcesPath, visitor);
    }
  }
}
 
Example 24
Source Project: buck   Source File: AndroidNdkFactoryTest.java    License: Apache License 2.0 5 votes vote down vote up
public TestAndroidNdkResolver(
    FileSystem fileSystem,
    ImmutableMap<String, String> environment,
    AndroidBuckConfig config,
    Optional<Path> ndkRoot,
    Optional<String> ndkVersion) {
  super(fileSystem, environment, config);
  this.ndkRoot = ndkRoot;
  this.ndkVersion = ndkVersion;
}
 
Example 25
Source Project: reactor-netty   Source File: HttpSendFileTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void sendZipFileCompressionSize_2() throws IOException {
	Path path = Files.createTempFile(null, ".zip");
	Files.copy(this.getClass().getResourceAsStream("/zipFile.zip"), path, StandardCopyOption.REPLACE_EXISTING);
	path.toFile().deleteOnExit();

	try (FileSystem zipFs = FileSystems.newFileSystem(path, (ClassLoader) null)) {
		Path fromZipFile = zipFs.getPath("/largeFile.txt");
		long fileSize = Files.size(fromZipFile);

		assertSendFile(out -> out.addHeader(HttpHeaderNames.CONTENT_LENGTH, "1245")
		                         .sendFile(fromZipFile, 0, fileSize), true, 2048, (req, res) -> true);
	}
}
 
Example 26
Source Project: copybara   Source File: WorkflowTest.java    License: Apache License 2.0 5 votes vote down vote up
private void prepareOriginExcludes(String content) throws IOException {
  FileSystem fileSystem = Jimfs.newFileSystem();
  Path base = fileSystem.getPath("excludesTest");
  Path folder = workdir.resolve("folder");
  Files.createDirectories(folder);
  touchFile(base, "folder/file.txt", content);
  touchFile(base, "folder/subfolder/file.txt", content);
  touchFile(base, "folder/subfolder/file.java", content);
  touchFile(base, "folder2/file.txt", content);
  touchFile(base, "folder2/subfolder/file.txt", content);
  touchFile(base, "folder2/subfolder/file.java", content);
  origin.addChange(1, base, "excludes", /*matchesGlob=*/true);
}
 
Example 27
private void importExport(String ts, ReadOnlyDataSource ds, FileSystem fs) throws IOException {
    CgmesImport i = new CgmesImport();
    Properties importParameters = new Properties();
    importParameters.put("powsyblTripleStore", ts);
    importParameters.put("storeCgmesModelAsNetworkExtension", "true");
    Network n = i.importData(ds, importParameters);
    CgmesModel cgmes = n.getExtension(CgmesModelExtension.class).getCgmesModel();
    cgmes.print(LOG::info);

    CgmesExport e = new CgmesExport();
    Path exportFolder = fs.getPath("impl-" + ts);
    Files.createDirectories(exportFolder);
    DataSource exportDataSource = new FileDataSource(exportFolder, "");
    e.export(n, new Properties(), exportDataSource);
}
 
Example 28
Source Project: js-dossier   Source File: ConfigTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void pathSpecResolvesToExpectedSetOfFiles() throws IOException {
  FileSystem fs = Jimfs.newFileSystem();
  Path baseDir = fs.getPath("/root");
  Path foo = baseDir.resolve("foo.js");
  Path bar = baseDir.resolve("a/bar.js");
  Path baz = baseDir.resolve("a/b/baz.js");
  Path quux = baseDir.resolve("a/b/c/quux.js");
  Path quot = baseDir.resolve("a/b/c/quot.js");

  Path otherDir = fs.getPath("/other");
  Path otherFooTest = otherDir.resolve("a/b/foo_test.js");
  Path otherBarTest = otherDir.resolve("a/bar_test.js");

  Files.createDirectories(quux.getParent());
  Files.createDirectories(otherFooTest.getParent());
  Files.createFile(foo);
  Files.createFile(bar);
  Files.createFile(baz);
  Files.createFile(quux);
  Files.createFile(quot);
  Files.createFile(otherFooTest);
  Files.createFile(otherBarTest);

  assertContentsAnyOrder(getPaths(baseDir, ""), foo, bar, baz, quux, quot);
  assertContentsAnyOrder(getPaths(baseDir, "foo.js"), foo);
  assertContentsAnyOrder(getPaths(baseDir, "a"), bar, baz, quux, quot);
  assertContentsAnyOrder(getPaths(baseDir, "a/b"), baz, quux, quot);
  assertContentsAnyOrder(getPaths(baseDir, "a/b/c"), quux, quot);

  assertContentsAnyOrder(getPaths(baseDir, "*.js"), foo);
  assertContentsAnyOrder(getPaths(baseDir, "a/b/*.js"), baz);
  assertContentsAnyOrder(getPaths(baseDir, "a/b/c/*.js"), quux, quot);
  assertContentsAnyOrder(getPaths(baseDir, "**.js"), foo, bar, baz, quux, quot);
  assertContentsAnyOrder(getPaths(baseDir, "a/**.js"), bar, baz, quux, quot);

  assertContentsAnyOrder(getPaths(baseDir, otherDir + "/a/*.js"), otherBarTest);
  assertContentsAnyOrder(
      getPaths(baseDir, otherDir + "/a/**_test.js"), otherBarTest, otherFooTest);
}
 
Example 29
Source Project: buck   Source File: MostFilesTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void deleteRecursivelyIfExistsDoesNotFollowSymlinks() throws IOException {
  FileSystem vfs = Jimfs.newFileSystem(Configuration.unix());
  Path linkTarget = vfs.getPath("/link-target");
  Path linkSource = vfs.getPath("/link-source");
  Files.createDirectory(linkTarget);
  Files.createSymbolicLink(linkSource, linkTarget);
  MostFiles.deleteRecursivelyIfExists(linkSource);
  // link is deleted, but target should still exist
  assertTrue(Files.exists(linkTarget));
  assertFalse(Files.exists(linkSource));
}
 
Example 30
Source Project: openjdk-jdk9   Source File: Basic.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void objectClassSizeTest() throws Exception {
    String path = "/modules/java.base/java/lang/Object.class";
    FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
    Path classFile = fs.getPath(path);

    assertTrue(Files.size(classFile) > 0L);
}