@Test public void testExtractBatchSpreadsheetWithArea() throws ParseException, IOException { FileSystem fs = FileSystems.getDefault(); String expectedCsv = UtilsForTesting.loadCsv("src/test/resources/technology/tabula/csv/spreadsheet_no_bounding_frame.csv"); Path tmpFolder = Files.createTempDirectory("tabula-java-batch-test"); tmpFolder.toFile().deleteOnExit(); Path copiedPDF = tmpFolder.resolve(fs.getPath("spreadsheet.pdf")); Path sourcePDF = fs.getPath("src/test/resources/technology/tabula/spreadsheet_no_bounding_frame.pdf"); Files.copy(sourcePDF, copiedPDF); copiedPDF.toFile().deleteOnExit(); this.csvFromCommandLineArgs(new String[]{ "-b", tmpFolder.toString(), "-p", "1", "-a", "150.56,58.9,654.7,536.12", "-f", "CSV" }); Path csvPath = tmpFolder.resolve(fs.getPath("spreadsheet.csv")); assertTrue(csvPath.toFile().exists()); assertArrayEquals(expectedCsv.getBytes(), Files.readAllBytes(csvPath)); }
static void validate(Module module) throws IOException { ModuleDescriptor md = module.getDescriptor(); // read m1/module-info.class FileSystem fs = FileSystems.newFileSystem(URI.create("jrt:/"), Collections.emptyMap()); Path path = fs.getPath("/", "modules", module.getName(), "module-info.class"); ModuleDescriptor md1 = ModuleDescriptor.read(Files.newInputStream(path)); // check the module descriptor of a system module and read from jimage checkPackages(md.packages(), "p1", "p2"); checkPackages(md1.packages(), "p1", "p2"); try (InputStream in = Files.newInputStream(path)) { checkModuleTargetAttribute(in, "p1"); } }
@Test public void fetchFailsGracefully() throws Exception { final FileSystem fs = Jimfs.newFileSystem(); final RecipeSource recipeSource = LazyCookbookRecipeSource.of( fs.getPath(System.getProperty("user.home"), ".buckaroo", "buckaroo-recipes")); final CountDownLatch latch = new CountDownLatch(1); recipeSource.fetch(RecipeIdentifier.of(Identifier.of("nosuchorg"), Identifier.of("nosuchrecipe"))) .result() .subscribe(x -> { }, error -> { latch.countDown(); }); latch.await(5000L, TimeUnit.MILLISECONDS); }
public static void main(String[] args) throws Exception { FileSystem fs = FileSystems.getDefault(); if (fs.getClass().getModule() == Object.class.getModule()) throw new RuntimeException("FileSystemProvider not overridden"); // exercise the file system Path dir = Files.createTempDirectory("tmp"); if (dir.getFileSystem() != fs) throw new RuntimeException("'dir' not in default file system"); System.out.println("created: " + dir); Path foo = Files.createFile(dir.resolve("foo")); if (foo.getFileSystem() != fs) throw new RuntimeException("'foo' not in default file system"); System.out.println("created: " + foo); // exercise interop with java.io.File File file = foo.toFile(); Path path = file.toPath(); if (path.getFileSystem() != fs) throw new RuntimeException("'path' not in default file system"); if (!path.equals(foo)) throw new RuntimeException(path + " not equal to " + foo); }
public void testDeleteRecursively_nonDirectoryFile() throws IOException { try (FileSystem fs = newTestFileSystem(SECURE_DIRECTORY_STREAM)) { Path file = fs.getPath("dir/a"); assertTrue(Files.isRegularFile(file, NOFOLLOW_LINKS)); MoreFiles.deleteRecursively(file); assertFalse(Files.exists(file, NOFOLLOW_LINKS)); Path symlink = fs.getPath("/symlinktodir"); assertTrue(Files.isSymbolicLink(symlink)); Path realSymlinkTarget = symlink.toRealPath(); assertTrue(Files.isDirectory(realSymlinkTarget, NOFOLLOW_LINKS)); MoreFiles.deleteRecursively(symlink); assertFalse(Files.exists(symlink, NOFOLLOW_LINKS)); assertTrue(Files.isDirectory(realSymlinkTarget, NOFOLLOW_LINKS)); } }
@Test public void onTest() throws Exception { File testZip = new File("test.zip"); JarFile jarFile = new JarFile(testZip); jarFile.stream().forEach((jarEntry -> { System.out.println(jarEntry.getName()); if (jarEntry.getName().lastIndexOf('/') != -1) { System.out.println( "parent -> " + jarEntry.getName().substring(0, jarEntry .getName() .lastIndexOf('/'))); } })); System.out.println("Filesystems"); FileSystem fileSystem = FileSystems.newFileSystem(testZip.toPath(), null); Path meow = fileSystem.getPath("meow/"); Files.list(meow).forEach((path) -> System.out.println(path.getFileName())); }
@Test public void testNewFileSystemWithJavaHome() throws Exception { if (isExplodedBuild) { System.out.println("Skip testNewFileSystemWithJavaHome" + " since this is an exploded build"); return; } Map<String, String> env = new HashMap<>(); // set java.home property to be underlying java.home // so that jrt-fs.jar loading is exercised. env.put("java.home", System.getProperty("java.home")); try (FileSystem fs = FileSystems.newFileSystem(URI.create("jrt:/"), env)) { checkFileSystem(fs); // jrt-fs.jar classes are loaded by another (non-boot) loader in this case assertNotNull(fs.provider().getClass().getClassLoader()); } }
public void testByteSource_size_ofSymlinkToDirectory() throws IOException { try (FileSystem fs = Jimfs.newFileSystem(Configuration.unix())) { Path dir = fs.getPath("dir"); Files.createDirectory(dir); Path link = fs.getPath("link"); Files.createSymbolicLink(link, dir); ByteSource source = MoreFiles.asByteSource(link); assertThat(source.sizeIfKnown()).isAbsent(); try { source.size(); fail(); } catch (IOException expected) { } } }
@Test public void resolverWorksWithGitHub2() throws Exception { final FileSystem fs = Jimfs.newFileSystem(); final RecipeSource recipeSource = GitProviderRecipeSource.of( fs, GitHubGitProvider.of()); final Single<ResolvedDependencies> task = AsyncDependencyResolver.resolve( recipeSource, ImmutableList.of(Dependency.of( RecipeIdentifier.of("github", "njlr", "test-lib-e"), AnySemanticVersion.of()))) .result(); final ResolvedDependencies resolved = task.timeout(120, TimeUnit.SECONDS).blockingGet(); assertTrue(resolved.dependencies.containsKey( RecipeIdentifier.of("github", "njlr", "test-lib-e"))); }
private static Path getDirectory(FileSystem fileSystem, String propertyName, String... folders) { Objects.requireNonNull(fileSystem); Objects.requireNonNull(propertyName); Objects.requireNonNull(folders); Path directory; String directoryName = System.getProperty(propertyName); if (directoryName != null) { directory = fileSystem.getPath(directoryName); } else { directory = fileSystem.getPath(System.getProperty("user.home"), folders); } return directory; }
@Test public void test() throws IOException { try (FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix())) { InMemoryPlatformConfig platformConfig = new InMemoryPlatformConfig(fileSystem); MapModuleConfig moduleConfig = platformConfig.createModuleConfig("load-flow-action-simulator"); moduleConfig.setClassProperty("load-flow-factory", LoadFlowFactoryMock.class); moduleConfig.setStringProperty("max-iterations", "15"); moduleConfig.setStringProperty("ignore-pre-contingency-violations", "true"); LoadFlowActionSimulatorConfig config = LoadFlowActionSimulatorConfig.load(platformConfig); assertEquals(LoadFlowFactoryMock.class, config.getLoadFlowFactoryClass()); config.setLoadFlowFactoryClass(AnotherLoadFlowFactoryMock.class); assertEquals(AnotherLoadFlowFactoryMock.class, config.getLoadFlowFactoryClass()); assertEquals(15, config.getMaxIterations()); config.setMaxIterations(10); assertEquals(10, config.getMaxIterations()); assertTrue(config.isIgnorePreContingencyViolations()); config.setIgnorePreContingencyViolations(false); assertFalse(config.isIgnorePreContingencyViolations()); } }
static void test8069211() throws Exception { // create a new filesystem, copy this file into it Map<String, Object> env = new HashMap<String, Object>(); env.put("create", "true"); Path fsPath = getTempPath(); try (FileSystem fs = newZipFileSystem(fsPath, env);) { OutputStream out = Files.newOutputStream(fs.getPath("/foo")); out.write("hello".getBytes()); out.close(); out.close(); } try (FileSystem fs = newZipFileSystem(fsPath, new HashMap<String, Object>())) { if (!Arrays.equals(Files.readAllBytes(fs.getPath("/foo")), "hello".getBytes())) { throw new RuntimeException("entry close() failed"); } } catch (Exception x) { throw new RuntimeException("entry close() failed", x); } finally { Files.delete(fsPath); } }
@Test public void testUnix() throws Exception { final FileSystem fileSystem = newUnixFileSystem(); final Path path = fileSystem.getPath("/var/log/syslog"); final PathSet pathSet = new SinglePathSet(path.toString(), fileSystem); assertEquals(path.getParent(), pathSet.getRootPath()); assertTrue(pathSet.isInSet(path)); assertTrue("Path list should be empty without any files in the file system", pathSet.getPaths().isEmpty()); Files.createDirectories(path.getParent()); Files.createFile(path); assertEquals("Path list should not be empty after creating the file", ImmutableSet.of(path), pathSet.getPaths()); }
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); } }
protected Path mockPath(Path parent, String name, long size) { FileSystem fileSystem = parent.getFileSystem(); Path subPath = mock(Path.class); File subPathToFile = mock(File.class); when(subPath.toFile()).thenReturn(subPathToFile); when(subPathToFile.length()).thenReturn(size); when(subPathToFile.exists()).thenReturn(true); when(subPath.getFileSystem()).thenReturn(fileSystem); when(subPath.resolve(anyString())).thenAnswer(invoke -> { String childName = (String) invoke.getArguments()[0]; return mockPath(subPath, childName); }); when(subPath.getParent()).thenReturn(parent); when(fileSystem.getPath(parent.toString(), name)).thenReturn(subPath); String fullPath = (parent.toString() + "/" + name).replace("//", "/"); when(fileSystem.getPath(fullPath)).thenReturn(subPath); when(subPath.toString()).thenReturn(fullPath); Path subPathFileName = mock(Path.class); when(subPathFileName.toString()).thenReturn(name); when(subPath.getFileName()).thenReturn(subPathFileName); return subPath; }
/** * Returns a new FileSystem to read REST resources, or null if they * are available from classpath. */ @SuppressForbidden(reason = "proper use of URL, hack around a JDK bug") protected static FileSystem getFileSystem() throws IOException { // REST suite handling is currently complicated, with lots of filtering and so on // For now, to work embedded in a jar, return a ZipFileSystem over the jar contents. URL codeLocation = FileUtils.class.getProtectionDomain().getCodeSource().getLocation(); boolean loadPackaged = RandomizedTest.systemPropertyAsBoolean(REST_LOAD_PACKAGED_TESTS, true); if (codeLocation.getFile().endsWith(".jar") && loadPackaged) { try { // hack around a bug in the zipfilesystem implementation before java 9, // its checkWritable was incorrect and it won't work without write permissions. // if we add the permission, it will open jars r/w, which is too scary! so copy to a safe r-w location. Path tmp = Files.createTempFile(null, ".jar"); try (InputStream in = FileSystemUtils.openFileURLStream(codeLocation)) { Files.copy(in, tmp, StandardCopyOption.REPLACE_EXISTING); } return FileSystems.newFileSystem(new URI("jar:" + tmp.toUri()), Collections.emptyMap()); } catch (URISyntaxException e) { throw new IOException("couldn't open zipfilesystem: ", e); } } else { return null; } }
@Test public void resolve1() throws Exception { final FileSystem fs = Jimfs.newFileSystem(); final RecipeSource recipeSource = GitProviderRecipeSource.of(fs, GitHubGitProvider.of()); final ImmutableList<Dependency> dependencies = ImmutableList.of( Dependency.of( RecipeIdentifier.of("github", "njlr", "test-lib-d"), AnySemanticVersion.of())); final ResolvedDependencies result = AsyncDependencyResolver.resolve(recipeSource, dependencies) .result() .timeout(20000L, TimeUnit.MILLISECONDS) .blockingGet(); assertTrue(result.isComplete()); assertTrue(result.dependencies.size() == 1); assertTrue(result.dependencies.containsKey(RecipeIdentifier.of("github", "njlr", "test-lib-d"))); }
@Test public void test() throws Exception { final FileSystem fs = Jimfs.newFileSystem(); final RecipeSource recipeSource = GitProviderRecipeSource.of( fs, BitBucketGitProvider.of()); final SettableFuture<Boolean> future = SettableFuture.create(); recipeSource.fetch(RecipeIdentifier.of("bitbucket", "njlr", "hello-buckaroo")) .result() .subscribe(recipe -> { assertEquals("hello-buckaroo", recipe.name); assertTrue(!recipe.versions.isEmpty()); future.set(true); }, error -> { error.printStackTrace(); future.setException(error); future.set(false); }); assertTrue(future.get(20000L, TimeUnit.MILLISECONDS)); }
@Test public void testFileIgnoreDetection() throws IOException { try (FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix())) { Files.createDirectory(fileSystem.getPath("/data")); Files.createDirectory(fileSystem.getPath("/data/ok")); Files.createDirectory(fileSystem.getPath("/data/bad")); // Create ok file Files.createFile(fileSystem.getPath("/data/ok/toto")); // Create ignore file Files.createFile(fileSystem.getPath("/data/bad/.photatoignore")); Assert.assertFalse(FileHelper.folderContainsIgnoreFile(fileSystem.getPath("/data/ok"))); Assert.assertTrue(FileHelper.folderContainsIgnoreFile(fileSystem.getPath("/data/bad"))); } }
/** Returns the application info read from either an app folder or ipa archive */ public static IosAppInfo readFromPath(Path ipaOrAppPath) throws IOException { NSObject plistDict; if (Files.isDirectory(ipaOrAppPath)) { plistDict = PlistParser.fromPath(ipaOrAppPath.resolve("Info.plist")); } else { try (FileSystem ipaFs = FileSystems.newFileSystem(ipaOrAppPath, null)) { Path appPath = MoreFiles.listFiles(ipaFs.getPath("Payload")) .stream() // Can't use Files.isDirectory, because no entry is a "directory" in a zip. .filter(e -> e.toString().endsWith(".app/")) .collect(MoreCollectors.onlyElement()); plistDict = PlistParser.fromPath(appPath.resolve("Info.plist")); } } return readFromPlistDictionary((NSDictionary) plistDict); }
@Override public FileSystem newFileSystem(URI uri, Map<String,?> env) throws IOException { if (env != null && env.keySet().contains("IOException")) { triggerEx("IOException"); } checkUri(uri); synchronized (FaultyFSProvider.class) { if (delegate != null && delegate.isOpen()) throw new FileSystemAlreadyExistsException(); FaultyFileSystem result = new FaultyFileSystem(null); delegate = result; return result; } }
public void testByteSource_size_ofDirectory() throws IOException { try (FileSystem fs = Jimfs.newFileSystem(Configuration.unix())) { Path dir = fs.getPath("dir"); Files.createDirectory(dir); ByteSource source = MoreFiles.asByteSource(dir); assertThat(source.sizeIfKnown()).isAbsent(); try { source.size(); fail(); } catch (IOException expected) { } } }
public void testDirectoryDeletion_sdsNotSupported_fails() throws IOException { for (DirectoryDeleteMethod method : EnumSet.allOf(DirectoryDeleteMethod.class)) { try (FileSystem fs = newTestFileSystem()) { Path dir = fs.getPath("dir"); assertEquals(6, MoreFiles.listFiles(dir).size()); try { method.delete(dir); fail("expected InsecureRecursiveDeleteException"); } catch (InsecureRecursiveDeleteException expected) { } assertTrue(Files.exists(dir)); assertEquals(6, MoreFiles.listFiles(dir).size()); } } }
public void testByteSource_size_ofSymlinkToRegularFile() throws IOException { try (FileSystem fs = Jimfs.newFileSystem(Configuration.unix())) { Path file = fs.getPath("file"); Files.write(file, new byte[10]); Path link = fs.getPath("link"); Files.createSymbolicLink(link, file); ByteSource source = MoreFiles.asByteSource(link); assertEquals(10L, (long) source.sizeIfKnown().get()); assertEquals(10L, source.size()); } }
@Test public void completeDependenciesFailsGracefully() throws Exception { final FileSystem fs = Jimfs.newFileSystem(); // Workaround: JimFs does not implement .toFile; // We clone and fail buckaroo-recipes if it does not exist, so we create it. MoreFiles.createParentDirectories(fs.getPath( System.getProperty("user.home"), ".buckaroo", "buckaroo-recipes", ".git")); final RecipeSource recipeSource = LazyCookbookRecipeSource.of(fs.getPath("nocookbookhere")); final ImmutableList<PartialDependency> partialDependencies = ImmutableList.of( PartialDependency.of(Identifier.of("org"), Identifier.of("example"))); final CountDownLatch latch = new CountDownLatch(1); InstallTasks.completeDependencies(recipeSource, partialDependencies).result().subscribe( x -> { }, error -> { latch.countDown(); }); latch.await(5000L, TimeUnit.MILLISECONDS); }
public synchronized FileSystem up(URI uri) throws IOException { FileSystem fileSystem = this.getOrNewFileSystem(uri); Integer semaphore = this.semaphores.getOrPut(fileSystem, () -> { return 0; }); this.semaphores.put(fileSystem, semaphore + 1); return fileSystem; }
void run() throws Exception { URI uri = URI.create("jar:" + outFile.toURI()); Map<String, String> env = new HashMap<>(); env.put("create", "true"); try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) { toZipfs(zipfs); } }
@Test public void unzip1() throws Exception { final FileSystem fs = Jimfs.newFileSystem(); final String expected = "Hello, world. "; // Write a test file. Files.write(fs.getPath("hello.txt"), expected.getBytes()); // Create the zip. { final ZipOutputStream zipOutputStream = new ZipOutputStream( Files.newOutputStream(fs.getPath("stuff.zip"))); zipOutputStream.finish(); zipOutputStream.close(); } // Add the test file to the zip. try (final FileSystem zipFileSystem = EvenMoreFiles.zipFileSystem(fs.getPath("stuff.zip"))) { Files.copy(fs.getPath("hello.txt"), zipFileSystem.getPath("message.txt"), StandardCopyOption.REPLACE_EXISTING); } // Unpack the zip! EvenMoreFiles.unzip(fs.getPath("stuff.zip"), fs.getPath("stuff"), Optional.empty()); // Verify the unzipped file matches the test file final byte[] bytes = Files.readAllBytes(fs.getPath("stuff", "message.txt")); final String actual = Charset.defaultCharset().decode(ByteBuffer.wrap(bytes)).toString(); assertEquals(expected, actual); }
private FileSystem getOrNewFileSystem(URI uri) throws IOException { try { return FileSystems.getFileSystem(uri); } catch (FileSystemNotFoundException exception) { return FileSystems.newFileSystem(uri, new HashMap<>()); } }
public static Stream<Path> getAllQrdaFiles(FileSystem fileSystem, String extension) { try { return Files.walk(fileSystem.getPath("../qrda-files")) .filter(Files::isRegularFile) .map(Path::toAbsolutePath) .filter(path -> path.toString().endsWith(extension)); } catch (IOException e) { throw new UncheckedIOException(e); } }
private static void handleUnexpectedError(final Throwable error, final TerminalBuffer buffer, final FileSystem fs) { Preconditions.checkNotNull(error); Preconditions.checkNotNull(buffer); Preconditions.checkNotNull(fs); buffer.flip( StackLayout.of( Text.of("Error! \n" + error.toString(), Color.RED), Text.of("Get help at https://github.com/loopperfect/buckaroo/issues", Color.BLUE), Text.of("The stacktrace was written to buckaroo-stacktrace.log. ", Color.YELLOW)) .render(TERMINAL_WIDTH)); try { final String trace = Arrays .stream(error.getStackTrace()) .map(StackTraceElement::toString) .reduce(Instant.now().toString() + ": ", (a, b) -> a + "\n" + b); EvenMoreFiles.writeFile( fs.getPath("buckaroo-stacktrace.log"), trace, Charset.defaultCharset(), true); } catch (final Throwable ignored) { } }
public static void main(String[] args) throws IOException { int status = new CommandLineTools().run(args, new ToolInitializationContext() { @Override public PrintStream getOutputStream() { return System.out; } @Override public PrintStream getErrorStream() { return System.err; } @Override public FileSystem getFileSystem() { return FileSystems.getDefault(); } @Override public Options getAdditionalOptions() { return new Options(); } @Override public ComputationManager createComputationManager(CommandLine commandLine) { try { return new LocalComputationManager(); } catch (IOException e) { throw new UncheckedIOException(e); } } }); if (status != CommandLineTools.COMMAND_OK_STATUS) { System.exit(status); } }
static void checkFileStores(FileSystem fs) throws IOException { // sanity check method if (FileUtils.areFileSystemsAccessible()) { System.out.println("\n--- Begin FileStores ---"); for (FileStore store: fs.getFileStores()) { System.out.println(store); } System.out.println("--- EndFileStores ---\n"); } else { System.err.println ("Skipping FileStore check due to file system access failure"); } }
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; }
@Test public void downloadRemoteFileChecksHash() throws Exception { final FileSystem fs = Jimfs.newFileSystem(); final Path target = fs.getPath("test.txt").toAbsolutePath(); EvenMoreFiles.writeFile(target, "hello", Charset.defaultCharset(), false); final RemoteFile remoteFile = RemoteFile.of( new URI("https://raw.githubusercontent.com/nikhedonia/googletest/665327f0141d4a4fc4f2496e781dce436d742645/BUCK"), HashCode.fromString("d976069f5b47fd8fc57201f47026a70dee4e47b3141ac23567b8a0c56bf9288c")); final SettableFuture<Boolean> future = SettableFuture.create(); CommonTasks.downloadRemoteFile(fs, remoteFile, target) .subscribe( next -> { }, error -> { // true here because it should fail future.set(true); }, () -> { future.set(false); }); assertTrue(future.get(30, TimeUnit.SECONDS)); }
static Stream<Path> jrtPaths() { FileSystem jrt = FileSystems.getFileSystem(URI.create("jrt:/")); Path root = jrt.getPath("/"); try { return Files.walk(root) .filter(p -> p.getNameCount() > 1) .filter(p -> p.toString().endsWith(".class")); } catch (IOException x) { throw new UncheckedIOException(x); } }
public MetadataAggregator(FileSystem fileSystem, String metadataCacheFilename, IGpsCoordinatesDescriptionGetter coordinatesDescriptionGetter) { this.fileSystem = fileSystem; this.metadataCacheFilename = metadataCacheFilename; this.coordinatesDescriptionGetter = coordinatesDescriptionGetter; this.metadatas = readFromCache(this.fileSystem, metadataCacheFilename); this.timer = new Timer(false); this.startAutoSave(); }
public void testDeleteRecursively_symlinkToDir() throws IOException { try (FileSystem fs = newTestFileSystem(SECURE_DIRECTORY_STREAM)) { Path symlink = fs.getPath("/symlinktodir"); Path dir = fs.getPath("dir"); assertEquals(6, MoreFiles.listFiles(dir).size()); MoreFiles.deleteRecursively(symlink); assertFalse(Files.exists(symlink)); assertTrue(Files.exists(dir)); assertEquals(6, MoreFiles.listFiles(dir).size()); } }
private static Observable<Event> downloadResolvedDependency(final FileSystem fs, final ResolvedDependency resolvedDependency, final Path target) { Preconditions.checkNotNull(fs); Preconditions.checkNotNull(resolvedDependency); Preconditions.checkNotNull(target); final Observable<Event> downloadSourceCode = Single.fromCallable(() -> Files.exists(target)) .flatMapObservable(exists -> { if (exists) { return Observable.empty(); } return resolvedDependency.source.join( gitCommit -> CacheTasks.cloneAndCheckoutUsingCache(gitCommit, target), remoteArchive -> CacheTasks.downloadUsingCache(remoteArchive, target, StandardCopyOption.REPLACE_EXISTING)); }); final Path buckFilePath = fs.getPath(target.toString(), "BUCK"); final Observable<Event> downloadBuckFile = Files.exists(buckFilePath) ? Observable.empty() : resolvedDependency.buckResource .map(x -> CommonTasks.downloadRemoteFile(fs, x, buckFilePath)) .orElse(Observable.empty()); final Path buckarooDepsFilePath = fs.getPath(target.toString(), "BUCKAROO_DEPS"); final Observable<Event> writeBuckarooDeps = Single.fromCallable(() -> CommonTasks.generateBuckarooDeps(resolvedDependency.dependencies)) .flatMap(content -> CommonTasks.writeFile( content, buckarooDepsFilePath, true)) .cast(Event.class) .toObservable(); return Observable.concat( downloadSourceCode, downloadBuckFile, writeBuckarooDeps.cast(Event.class)); }
private static String[] getLauncher() throws IOException { String platform = getPlatform(); if (platform == null) { return null; } String launcher = TEST_SRC + File.separator + platform + "-" + ARCH + File.separator + "launcher"; final FileSystem FS = FileSystems.getDefault(); Path launcherPath = FS.getPath(launcher); final boolean hasLauncher = Files.isRegularFile(launcherPath, LinkOption.NOFOLLOW_LINKS)&& Files.isReadable(launcherPath); if (!hasLauncher) { System.out.println("Launcher [" + launcher + "] does not exist. Skipping the test."); return null; } // It is impossible to store an executable file in the source control // We need to copy the launcher to the working directory // and set the executable flag Path localLauncherPath = FS.getPath(WORK_DIR, "launcher"); Files.copy(launcherPath, localLauncherPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); if (!Files.isExecutable(localLauncherPath)) { Set<PosixFilePermission> perms = new HashSet<>( Files.getPosixFilePermissions( localLauncherPath, LinkOption.NOFOLLOW_LINKS ) ); perms.add(PosixFilePermission.OWNER_EXECUTE); Files.setPosixFilePermissions(localLauncherPath, perms); } return new String[] {launcher, localLauncherPath.toAbsolutePath().toString()}; }