Java Code Examples for java.nio.file.Files#list()

The following examples show how to use java.nio.file.Files#list() . 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: JobMasterStopWithSavepointIT.java    From flink with Apache License 2.0 6 votes vote down vote up
private void stopWithSavepointNormalExecutionHelper(final boolean terminate) throws Exception {
	setUpJobGraph(NoOpBlockingStreamTask.class, RestartStrategies.noRestart());

	final CompletableFuture<String> savepointLocationFuture = stopWithSavepoint(terminate);

	assertThat(getJobStatus(), equalTo(JobStatus.RUNNING));

	finishingLatch.trigger();

	final String savepointLocation = savepointLocationFuture.get();
	assertThat(getJobStatus(), equalTo(JobStatus.FINISHED));

	final List<Path> savepoints;
	try (Stream<Path> savepointFiles = Files.list(savepointDirectory)) {
		savepoints = savepointFiles.map(Path::getFileName).collect(Collectors.toList());
	}
	assertThat(savepoints, hasItem(Paths.get(savepointLocation).getFileName()));
}
 
Example 2
Source File: RTSGroup.java    From indexr with Apache License 2.0 6 votes vote down vote up
public static State getState(Path path) throws IOException {
    if (!Files.exists(path)) {
        return Begin;
    }
    try (Stream<Path> paths = Files.list(path)) {
        Set<String> stateFiles = paths
                .map(p -> p.getFileName().toString())
                .filter(n -> n.startsWith("_ST_") || n.startsWith("_st_"))
                .collect(Collectors.toSet());
        State stat = Begin;
        for (State st : State.values()) {
            if (stateFiles.contains(st.fileName) || stateFiles.contains(st.fileName.toLowerCase())) {
                stat = st;
            }
        }
        return stat;
    }
}
 
Example 3
Source File: FileSystemHttpVfs.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
protected List<String> blockingList(Executor fileReadExecutor, String path) {
    path = normalizePath(path);
    try (Stream<Path> stream = Files.list(Paths.get(rootDir + path))) {
        return stream.filter(Files::isReadable)
                     .map(p -> {
                         final String fileName = p.getFileName().toString();
                         return Files.isDirectory(p) ? fileName + '/' : fileName;
                     })
                     .sorted(String.CASE_INSENSITIVE_ORDER)
                     .collect(toImmutableList());
    } catch (IOException e) {
        // Failed to retrieve the listing.
        return ImmutableList.of();
    }
}
 
Example 4
Source File: MCRIFSCopyTest.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void async() throws Exception {
    // create derivate
    create();
    MCRSessionMgr.getCurrentSession().commitTransaction();

    // execute threads
    MCRSystemUserInformation systemUser = MCRSystemUserInformation.getSystemUserInstance();
    ExecutorService executorService = Executors.newFixedThreadPool(3);
    Future<Exception> future1 = executorService
        .submit(new MCRFixedUserCallable<>(new CopyTask("anpassbar.jpg", derivate), systemUser));
    Future<Exception> future2 = executorService
        .submit(new MCRFixedUserCallable<>(new CopyTask("nachhaltig.jpg", derivate), systemUser));
    Future<Exception> future3 = executorService
        .submit(new MCRFixedUserCallable<>(new CopyTask("vielseitig.jpg", derivate), systemUser));
    throwException(future1.get(5, TimeUnit.SECONDS));
    throwException(future2.get(5, TimeUnit.SECONDS));
    throwException(future3.get(5, TimeUnit.SECONDS));
    try (Stream<Path> streamPath = Files.list(MCRPath.getPath(derivate.getId().toString(), "/"))) {
        assertEquals("the derivate should contain three files", 3, streamPath.count());
    }

    executorService.awaitTermination(1, TimeUnit.SECONDS);
}
 
Example 5
Source File: UtilsTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteApplicationFiles() throws Exception {
	final Path applicationFilesDir = temporaryFolder.newFolder(".flink").toPath();
	Files.createFile(applicationFilesDir.resolve("flink.jar"));
	try (Stream<Path> files = Files.list(temporaryFolder.getRoot().toPath())) {
		assertThat(files.count(), equalTo(1L));
	}
	try (Stream<Path> files = Files.list(applicationFilesDir)) {
		assertThat(files.count(), equalTo(1L));
	}

	Utils.deleteApplicationFiles(Collections.singletonMap(
		YarnConfigKeys.FLINK_YARN_FILES,
		applicationFilesDir.toString()));
	try (Stream<Path> files = Files.list(temporaryFolder.getRoot().toPath())) {
		assertThat(files.count(), equalTo(0L));
	}
}
 
Example 6
Source File: SSTableUtils.java    From cassandra-backup with Apache License 2.0 5 votes vote down vote up
private static Stream<? extends Path> tryListFiles(Path path) {
    try {
        return Files.list(path);
    } catch (IOException e) {
        logger.error("Failed to retrieve the file(s)", e);
        return Stream.empty();
    }
}
 
Example 7
Source File: Files1.java    From java8-tutorial with MIT License 5 votes vote down vote up
private static void testList() throws IOException {
    try (Stream<Path> stream = Files.list(Paths.get(""))) {
        String joined = stream
                .map(String::valueOf)
                .filter(path -> !path.startsWith("."))
                .sorted()
                .collect(Collectors.joining("; "));
        System.out.println("list(): " + joined);
    }
}
 
Example 8
Source File: EnvResourceAssert.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
private List<Path> resourceDirs() throws IOException {
    try (Stream<Path> stream = Files.list(actual)) {
        return stream.filter(Files::isDirectory)
                     .map(path -> path.resolve("resources")).filter(Files::exists)
                     .collect(Collectors.toList());
    }
}
 
Example 9
Source File: DependenciesTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void run() throws IOException {
    Path src = Paths.get(System.getProperty("test.src"), "tests");

    try (Stream<Path> tests = Files.list(src)) {
        tests.map(p -> Files.isRegularFile(p) ? Stream.of(p) : silentWalk(p))
             .forEach(this :: runTest);
    }
}
 
Example 10
Source File: ResumeCheckpointManuallyITCase.java    From flink with Apache License 2.0 5 votes vote down vote up
private static Optional<Path> findExternalizedCheckpoint(File checkpointDir, JobID jobId) throws IOException {
	try (Stream<Path> checkpoints = Files.list(checkpointDir.toPath().resolve(jobId.toString()))) {
		return checkpoints
			.filter(path -> path.getFileName().toString().startsWith("chk-"))
			.filter(path -> {
				try (Stream<Path> checkpointFiles = Files.list(path)) {
					return checkpointFiles.anyMatch(child -> child.getFileName().toString().contains("meta"));
				} catch (IOException ignored) {
					return false;
				}
			})
			.findAny();
	}
}
 
Example 11
Source File: PathUtil.java    From manifold with Apache License 2.0 5 votes vote down vote up
public static Path[] listFiles( Path path )
{
  try( Stream<Path> list = Files.list( path ) )
  {
    return list.toArray( Path[]::new );
  }
  catch( IOException e )
  {
    throw new RuntimeException( e );
  }
}
 
Example 12
Source File: NetCollector.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
@Override
public void fill(SysInfo info) throws Exception {
    // /sys/class/net/eth0/statistics/rx_bytes
    // /sys/class/net/eth0/statistics/tx_bytes
    Map<String, SysInfo.Net> nets = info.getNet();
    for(Path devPath: (Iterable<Path>)(Files.list(path)::iterator)) {
        String dev = devPath.getFileName().toString();
        SysInfo.Net net = new SysInfo.Net();
        readNet(devPath, net);
        nets.put(dev, net);
    }
}
 
Example 13
Source File: TokenInfoDictionaryBuilder.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public TokenInfoDictionaryWriter build(Path dir) throws IOException {
  try (Stream<Path> files = Files.list(dir)) {
    List<Path> csvFiles = files
        .filter(path -> path.getFileName().toString().endsWith(".csv"))
        .sorted()
        .collect(Collectors.toList());
    return buildDictionary(csvFiles);
  }
}
 
Example 14
Source File: JobMasterTriggerSavepointIT.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
@Test
public void testStopJobAfterSavepoint() throws Exception {
	setUpWithCheckpointInterval(10L);

	final String savepointLocation = cancelWithSavepoint();
	final JobStatus jobStatus = clusterClient.getJobStatus(jobGraph.getJobID()).get();

	assertThat(jobStatus, isOneOf(JobStatus.CANCELED, JobStatus.CANCELLING));

	final List<Path> savepoints;
	try (Stream<Path> savepointFiles = Files.list(savepointDirectory)) {
		savepoints = savepointFiles.map(Path::getFileName).collect(Collectors.toList());
	}
	assertThat(savepoints, hasItem(Paths.get(savepointLocation).getFileName()));
}
 
Example 15
Source File: SubjectStorage.java    From LuckPerms with MIT License 5 votes vote down vote up
/**
 * Returns a set of all known collections
 *
 * @return the identifiers of all known collections
 */
public Set<String> getSavedCollections() {
    if (!Files.exists(this.container)) {
        return ImmutableSet.of();
    }

    try (Stream<Path> s = Files.list(this.container)) {
        return s.filter(p -> Files.isDirectory(p))
                .map(p -> p.getFileName().toString())
                .collect(ImmutableCollectors.toSet());
    } catch (IOException e) {
        e.printStackTrace();
        return ImmutableSet.of();
    }
}
 
Example 16
Source File: MTGDavFolderResource.java    From MtgDesktopCompanion with GNU General Public License v3.0 5 votes vote down vote up
@Override
public List<? extends Resource> getChildren() throws NotAuthorizedException, BadRequestException {
	if(children==null)
	{
			children = new ArrayList<>();
			
			if(root)
			{
				fs.getRootDirectories().forEach(p->children.add(new MTGDavFolderResource((MTGPath)p, fs, false,user,pass)));
				return children;
			}
			else
			{
				try (Stream<Path> s = Files.list(mtgpath))
				{
					s.forEach(p->{
						if(((MTGPath)p).isCard())
							children.add(new MTGDavFileResource((MTGPath)p, fs, user,pass));
						else
							children.add(new MTGDavFolderResource((MTGPath)p, fs, false,user,pass));
					});
				} catch (IOException e) {
					logger.error(e);
				}
					
			}
	}
	return children;
}
 
Example 17
Source File: ClassLoaderService.java    From amidst with GNU General Public License v3.0 5 votes vote down vote up
private Stream<Path> getLibrarySearchFiles(Path librarySearchPath) {
	if (Files.isDirectory(librarySearchPath)) {
		try {
			return Files.list(librarySearchPath);
		} catch (IOException e) {
			AmidstLogger.error(e, "Error while reading library directory " + librarySearchPath);
		}
	}
	return Stream.empty();
}
 
Example 18
Source File: TarContainerPacker.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
private void includePath(Path dir, String subdir,
    ArchiveOutputStream archiveOutput) throws IOException {

  try (Stream<Path> dirEntries = Files.list(dir)) {
    for (Path path : dirEntries.collect(toList())) {
      String entryName = subdir + "/" + path.getFileName();
      includeFile(path.toFile(), entryName, archiveOutput);
    }
  }
}
 
Example 19
Source File: ToolPath.java    From protools with Apache License 2.0 4 votes vote down vote up
public static Stream<Path> dirStream(Path dir) throws IOException {
    return Files.list(dir);
}
 
Example 20
Source File: UpdateIntelliJSdksTask.java    From curiostack with MIT License 4 votes vote down vote up
@TaskAction
public void exec() throws IOException {
  Path userHome = Paths.get(System.getProperty("user.home"));
  final List<Path> intelliJFolders;
  try (var files = Files.list(userHome)) {
    intelliJFolders =
        files
            .filter(
                path ->
                    Files.isDirectory(path)
                        && (path.getFileName().toString().startsWith(".IntelliJIdea")
                            || path.getFileName().toString().startsWith(".IdeaIC")))
            .sorted()
            .collect(toImmutableList());
  }

  final Path intelliJFolder;
  if (!intelliJFolders.isEmpty()) {
    intelliJFolder = Iterables.getLast(intelliJFolders);
  } else {
    getProject()
        .getLogger()
        .info("No IntelliJ config folder found, writing to default location.");
    intelliJFolder = userHome.resolve(LATEST_INTELLIJ_CONFIG_FOLDER);
  }

  getProject()
      .getLogger()
      .info("Updating IntelliJ folder {}, found folders {}", intelliJFolder, intelliJFolders);

  String javaVersion = ToolDependencies.getOpenJdkVersion(getProject());
  String majorVersion =
      javaVersion.startsWith("zulu")
          ? JavaVersion.toVersion(javaVersion.substring("zulu".length())).getMajorVersion()
          : JavaVersion.toVersion(javaVersion).getMajorVersion();

  String java8Version = ToolDependencies.getOpenJdk8Version(getProject());
  final String jdk8FolderSuffix;
  switch (new PlatformHelper().getOs()) {
    case WINDOWS:
      jdk8FolderSuffix = "win_x64";
      break;
    case MAC_OSX:
      jdk8FolderSuffix = "macosx_x64";
      break;
    case LINUX:
      jdk8FolderSuffix = "linux_x64";
      break;
    default:
      throw new IllegalStateException("Unknown OS");
  }
  String jdk8FolderName = java8Version + "/" + java8Version + "-" + jdk8FolderSuffix;

  var jdkTable =
      Files.createDirectories(intelliJFolder.resolve("config/options")).resolve("jdk.table.xml");
  updateConfig(
      jdkTable,
      "jdk-" + javaVersion,
      majorVersion,
      "curiostack/openjdk-intellij-table-snippet.template.xml",
      ImmutableMap.of(
          "javaVersion", javaVersion, "javaModules", JAVA_MODULES, "majorVersion", majorVersion),
      getProject());
  updateConfig(
      jdkTable,
      jdk8FolderName,
      "1.8",
      "curiostack/openjdk-8-intellij-table-snippet.template.xml",
      ImmutableMap.of("javaVersion", java8Version, "javaModules", JAVA_8_JARS),
      getProject());

  updateGoSdk(intelliJFolder, getProject());
  updateGoPath(intelliJFolder, getProject());
}