canonical example by Tabnine
public void pathUsage() { Path currentDir = Paths.get("."); // currentDir = "." Path fullPath = currentDir.toAbsolutePath(); // fullPath = "/Users/guest/workspace" Path one = currentDir.resolve("file.txt"); // one = "./file.txt" Path fileName = one.getFileName(); // fileName = "file.txt" }
@Setup public void setUp() throws IOException { queryRunner = new LocalQueryRunner(testSessionBuilder() .setCatalog("memory") .setSchema("default") .build()); queryRunner.installPlugin(new GeoPlugin()); queryRunner.createCatalog("memory", new MemoryConnectorFactory(), ImmutableMap.of()); Path path = Paths.get(BenchmarkSpatialJoin.class.getClassLoader().getResource("us-states.tsv").getPath()); String polygonValues = Files.lines(path) .map(line -> line.split("\t")) .map(parts -> format("('%s', '%s')", parts[0], parts[1])) .collect(Collectors.joining(",")); queryRunner.execute(format("CREATE TABLE memory.default.polygons AS SELECT * FROM (VALUES %s) as t (name, wkt)", polygonValues)); }
@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())); }
@Override public String[] listFiles(URI fileUri, boolean recursive) throws IOException { File file = new File(decodeURI(fileUri.getRawPath())); if (!recursive) { return Arrays.stream(file.list()).map(s -> new File(file, s)).map(File::getAbsolutePath).toArray(String[]::new); } else { return Files.walk(Paths.get(fileUri)). filter(s -> !s.equals(file.toPath())).map(Path::toString).toArray(String[]::new); } }
protected static byte[] getBytes(Object data) throws IOException { byte[] bytes; if (isValidURL(data.toString())) { bytes = ByteStreams.toByteArray((new URL(data.toString()).openStream())); } else if (exists(data.toString())) { Path path = Paths.get(data.toString()); bytes = Files.readAllBytes(path); } else { throw new FileNotFoundException(data.toString() + " doesn't exist. "); } return bytes; }
@Test public void testCreateWithNonexistentStagingDirectory() throws Exception { java.nio.file.Path stagingParent = createTempDirectory("test"); java.nio.file.Path staging = Paths.get(stagingParent.toString(), "staging"); // stagingParent = /tmp/testXXX // staging = /tmp/testXXX/staging try (PrestoS3FileSystem fs = new PrestoS3FileSystem()) { MockAmazonS3 s3 = new MockAmazonS3(); Configuration conf = new Configuration(); conf.set(S3_STAGING_DIRECTORY, staging.toString()); fs.initialize(new URI("s3n://test-bucket/"), conf); fs.setS3Client(s3); FSDataOutputStream stream = fs.create(new Path("s3n://test-bucket/test")); stream.close(); assertTrue(Files.exists(staging)); } finally { deleteRecursively(stagingParent, ALLOW_INSECURE); } }
private static String loadScript(final String filePath) { try { return Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8).stream() .collect(Collectors.joining(System.lineSeparator())); } catch (IOException e) { throw new KsqlException("Failed to read file: " + filePath, e); } } }
protected static void executeDDL(String ddlFile) throws Exception { URL ddlTestFile = TestHelper.class.getClassLoader().getResource(ddlFile); assertNotNull("Cannot locate " + ddlFile, ddlTestFile); String statements = Files.readAllLines(Paths.get(ddlTestFile.toURI())) .stream() .collect(Collectors.joining(System.lineSeparator())); try (PostgresConnection connection = create()) { connection.executeWithoutCommitting(statements); } }
@Test public void shouldThrowWhenRelativePathIsOutsideImportDirectory() throws Exception { assumeFalse( Paths.get( "/" ).relativize( Paths.get( "/../baz.csv" ) ).toString().equals( "baz.csv" ) ); File importDir = new File( "/tmp/neo4jtest" ).getAbsoluteFile(); final Config config = Config.defaults( GraphDatabaseSettings.load_csv_file_url_root, importDir.toString() ); try { URLAccessRules.fileAccess().validate( config, new URL( "file:///../baz.csv" ) ); fail( "expected exception not thrown " ); } catch ( URLAccessValidationError error ) { assertThat( error.getMessage(), equalTo( "file URL points outside configured import directory" ) ); } }
private static List<URL> getUrls(String path) throws MalformedURLException { ImmutableList.Builder<URL> urlList = ImmutableList.builder(); File driverPath = new File(path); if (!driverPath.isDirectory()) { urlList.add(Paths.get(path).toUri().toURL()); return urlList.build(); } File[] files = driverPath.listFiles((dir, name) -> { return name.endsWith(".jar"); }); if (files == null) { return urlList.build(); } for (File file : files) { // Does not handle nested directories if (file.isDirectory()) { continue; } urlList.add(Paths.get(file.getAbsolutePath()).toUri().toURL()); } return urlList.build(); }
private DescriptionBasedDiff( JCCompilationUnit compilationUnit, boolean ignoreOverlappingFixes, ImportOrganizer importOrganizer) { this.compilationUnit = checkNotNull(compilationUnit); URI sourceFileUri = compilationUnit.getSourceFile().toUri(); this.sourcePath = (sourceFileUri.isAbsolute() && Objects.equals(sourceFileUri.getScheme(), "file")) ? Paths.get(sourceFileUri).toAbsolutePath().toString() : sourceFileUri.getPath(); this.ignoreOverlappingFixes = ignoreOverlappingFixes; this.importsToAdd = new LinkedHashSet<>(); this.importsToRemove = new LinkedHashSet<>(); this.endPositions = compilationUnit.endPositions; this.importOrganizer = importOrganizer; }
private Path writeTextTo(final String location) throws IOException { final Path path = Paths.get(location); Files.createDirectories(path.getParent()); try (BufferedWriter buffy = Files.newBufferedWriter(path, Charset.defaultCharset())) { buffy.write("some text"); buffy.newLine(); buffy.flush(); } return path; } }
@Test public void testFromURL() throws IOException, URISyntaxException { //Given Path outputDirectory = Paths.get("build/test/asciidoc/fromUrl"); FileUtils.deleteQuietly(outputDirectory.toFile()); //When Swagger2MarkupConverter.from(new URL("http://petstore.swagger.io/v2/swagger.json")).build() .toFolder(outputDirectory); //Then String[] files = outputDirectory.toFile().list(); assertThat(files).hasSize(4).containsAll(expectedFiles); }
public static void main(String[] args) throws URISyntaxException, IOException { Path worldFile = Paths.get(Resources.getResource("world").toURI()); String world = new String(Files.readAllBytes(worldFile), StandardCharsets.UTF_8); System.out.println("Hello " + world); } }
@Test public void getLocalArtifactUrl_shouldReturnCorrectUrlForArtifactKey() throws Exception { DependencyResolver dependencyResolver = createResolver(); DependencyJar dependencyJar = new DependencyJar("group1", "artifact1", "", null); URL url = dependencyResolver.getLocalArtifactUrl(dependencyJar); assertEquals(Paths.get("path1").toUri().toURL().toExternalForm(), url.toExternalForm()); }
private MagicCommandOutcomeItem handleMvnLocal() { String localRepo = BeakerxSystemProperty.getHomeUser() + "/.m2/repository"; if (Files.exists(Paths.get(localRepo))) { ClasspathAddMvnMagicCommand mvnMagicCommand = kernel.magicCommandConfiguration().getClasspathAddMvnMagicCommand(kernel); try { String result = mvnMagicCommand.addRepo(MVN_LOCAL, new File(localRepo).toURI().toURL().toString()); return createResult(result); } catch (MalformedURLException e) { return new MagicCommandOutput(Status.ERROR, e.toString()); } } return new MagicCommandOutput(Status.OK, String.format("Warning: directory %s not found", localRepo)); }