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" }
import java.nio.file.Path; import java.nio.file.Paths; public class Test { public static void main(String[] args) { Path pathAbsolute = Paths.get("/var/data/stuff/xyz.dat"); Path pathBase = Paths.get("/var/data"); Path pathRelative = pathBase.relativize(pathAbsolute); System.out.println(pathRelative); } }
private static String unixifyPath(String path) { return Paths.get(path).toAbsolutePath().toString().replace("\\", "/"); }
@JsonCreator public LocalLoadSpec( @JacksonInject LocalDataSegmentPuller puller, @JsonProperty(value = "path", required = true) final String path ) { Preconditions.checkNotNull(path); this.path = Paths.get(path); Preconditions.checkArgument(Files.exists(Paths.get(path)), "[%s] does not exist", path); this.puller = puller; }
@Test public void testPrepare() throws Exception { HdfsState state = createHdfsState(); Collection<File> files = FileUtils.listFiles(new File(TEST_OUT_DIR), null, false); File hdfsDataFile = Paths.get(TEST_OUT_DIR, FILE_NAME_PREFIX + "0").toFile(); Assert.assertTrue(files.contains(hdfsDataFile)); }
@Test public void testFileSystemResourceWithFilePath() throws Exception { Path filePath = Paths.get(getClass().getResource("Resource.class").toURI()); Resource resource = new FileSystemResource(filePath); doTestResource(resource); assertEquals(new FileSystemResource(filePath), resource); }
@Test public void testCleanupOldMetaFiles() throws IOException { generateDummyMetaFiles(); Path dataDir = Paths.get(configuration.getDataFileLocation()); Assert.assertEquals(4, dataDir.toFile().listFiles().length); // clean the directory metaProxy.cleanupOldMetaFiles(); Assert.assertEquals(1, dataDir.toFile().listFiles().length); Path dummy = Paths.get(dataDir.toString(), "dummy.tmp"); Assert.assertTrue(dummy.toFile().exists()); }
@Test public void compileFilesTest() throws IOException { Path source = Paths.get("src","test","resources","solidity","file1.sol"); SolidityCompiler.Result res = SolidityCompiler.compile(source.toFile(), true, ABI, BIN, INTERFACE, METADATA); System.out.println("Out: '" + res.output + "'"); System.out.println("Err: '" + res.errors + "'"); CompilationResult result = CompilationResult.parse(res.output); Assert.assertEquals("test1", result.getContractName()); Assert.assertEquals(source.toAbsolutePath(), result.getContractPath()); CompilationResult.ContractMetadata a = result.getContract(source, "test1"); CallTransaction.Contract contract = new CallTransaction.Contract(a.abi); System.out.print(contract.functions[0].toString()); }
@Test public void compileFilesWithImportFromParentPathTest() throws IOException { Path source = Paths.get("src","test","resources","solidity","foo","file3.sol"); SolidityCompiler.Option allowPathsOption = new SolidityCompiler.Options.AllowPaths(Collections.singletonList(source.getParent().getParent())); SolidityCompiler.Result res = SolidityCompiler.compile(source.toFile(), true, ABI, BIN, INTERFACE, METADATA, allowPathsOption); System.out.println("Out: '" + res.output + "'"); System.out.println("Err: '" + res.errors + "'"); CompilationResult result = CompilationResult.parse(res.output); CompilationResult.ContractMetadata a = result.getContract("test3"); CallTransaction.Contract contract = new CallTransaction.Contract(a.abi); System.out.print(contract.functions[0].toString()); }
@Test public void compileFilesWithImportFromParentStringTest() throws IOException { Path source = Paths.get("src","test","resources","solidity","foo","file3.sol"); SolidityCompiler.Option allowPathsOption = new SolidityCompiler.Options.AllowPaths(Collections.singletonList(source.getParent().getParent().toAbsolutePath().toString())); SolidityCompiler.Result res = SolidityCompiler.compile(source.toFile(), true, ABI, BIN, INTERFACE, METADATA, allowPathsOption); System.out.println("Out: '" + res.output + "'"); System.out.println("Err: '" + res.errors + "'"); CompilationResult result = CompilationResult.parse(res.output); CompilationResult.ContractMetadata a = result.getContract(source, "test3"); CallTransaction.Contract contract = new CallTransaction.Contract(a.abi); System.out.print(contract.functions[0].toString()); }
@Test public void testCreateTempDirectoryWithDirectoryBlocking() { FileSystem fs = vertx.fileSystem(); String tempDirectory = fs.createTempDirectoryBlocking(testDir, "project", null); Path path = Paths.get(tempDirectory); assertTrue(Files.exists(Paths.get(tempDirectory))); assertTrue(path.startsWith(testDir)); }
public JavapProcess() throws FileNotFoundException { super(); Path javaHome = Paths.get(System.getProperty("java.home")); executablePath = Paths.get(javaHome.toString(), "..", "bin", EXECUTABLE_NAME); if (!executablePath.toFile().exists()) { executablePath = Paths.get(javaHome.toString(), "bin", EXECUTABLE_NAME); if (!executablePath.toFile().exists()) { throw new FileNotFoundException("Could not find " + EXECUTABLE_NAME); } } executablePath = executablePath.normalize(); }
/** * Tests https://issues.apache.org/jira/browse/LANG-708 * * @throws IOException * if an I/O error occurs */ @Test public void testLang708() throws IOException { final byte[] inputBytes = Files.readAllBytes(Paths.get("src/test/resources/lang-708-input.txt")); final String input = new String(inputBytes, StandardCharsets.UTF_8); final String escaped = StringEscapeUtils.escapeEcmaScript(input); // just the end: assertTrue(escaped, escaped.endsWith("}]")); // a little more: assertTrue(escaped, escaped.endsWith("\"valueCode\\\":\\\"\\\"}]")); }
private static void saveDataFile(String location, String name, DescriptiveStatistics data, TimeUnit scale) { long conv = scale.toNanos(1); Path dst = Paths.get(location, name); try (PrintStream output = new PrintStream(dst.toString())) { // Print all values one per line Arrays.stream(data.getValues()).forEach(d -> output.println(d / conv)); } catch (FileNotFoundException e) { LOG.error("failed to write to {}", dst); } }
@Test public void testReadToString() throws IOException, URISyntaxException { String content = IOKit.readToString(IOKitTest.class.getResourceAsStream("/application.properties")); Assert.assertEquals(true, StringKit.isNotBlank(content)); content = IOKit.readToString(Paths.get(IOKitTest.class.getResource("/application.properties").toURI()).toString()); Assert.assertEquals(true, StringKit.isNotBlank(content)); }
@Test public void wellKnownModules() throws JsonProcessingException, UnsupportedEncodingException { ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().build(); Long timestamp = 1322903730000L; DateTime dateTime = new DateTime(timestamp, DateTimeZone.UTC); assertEquals(timestamp.toString(), new String(objectMapper.writeValueAsBytes(dateTime), "UTF-8")); Path file = Paths.get("foo"); assertTrue(new String(objectMapper.writeValueAsBytes(file), "UTF-8").endsWith("foo\"")); Optional<String> optional = Optional.of("test"); assertEquals("\"test\"", new String(objectMapper.writeValueAsBytes(optional), "UTF-8")); // Kotlin module IntRange range = new IntRange(1, 3); assertEquals("{\"start\":1,\"end\":3}", new String(objectMapper.writeValueAsBytes(range), "UTF-8")); }
public void generate() throws Exception { initPlanTest(); try { getQueryResourcePaths() .parallel() .forEach(queryResourcePath -> { try { Path queryPlanWritePath = Paths.get( getSourcePath().toString(), "src/test/resources", getQueryPlanResourcePath(queryResourcePath)); createParentDirs(queryPlanWritePath.toFile()); write(generateQueryPlan(read(queryResourcePath)).getBytes(UTF_8), queryPlanWritePath.toFile()); System.out.println("Generated expected plan for query: " + queryResourcePath); } catch (IOException e) { throw new UncheckedIOException(e); } }); } finally { destroyPlanTest(); } }
@Test public void testJarSubmission() throws Exception { final TestingDispatcherGateway restfulGateway = new TestingDispatcherGateway.Builder() .setBlobServerPort(blobServerResource.getBlobServerPort()) .setSubmitFunction(jobGraph -> CompletableFuture.completedFuture(Acknowledge.get())) .build(); final JarHandlers handlers = new JarHandlers(temporaryFolder.newFolder().toPath(), restfulGateway); final JarUploadHandler uploadHandler = handlers.uploadHandler; final JarListHandler listHandler = handlers.listHandler; final JarPlanHandler planHandler = handlers.planHandler; final JarRunHandler runHandler = handlers.runHandler; final JarDeleteHandler deleteHandler = handlers.deleteHandler; // targetDir property is set via surefire configuration final Path originalJar = Paths.get(System.getProperty("targetDir")).resolve("test-program.jar"); final Path jar = Files.copy(originalJar, temporaryFolder.getRoot().toPath().resolve("test-program.jar")); final String storedJarPath = uploadJar(uploadHandler, jar, restfulGateway); final String storedJarName = Paths.get(storedJarPath).getFileName().toString(); final JarListInfo postUploadListResponse = listJars(listHandler, restfulGateway); Assert.assertEquals(1, postUploadListResponse.jarFileList.size()); final JarListInfo.JarFileInfo listEntry = postUploadListResponse.jarFileList.iterator().next(); Assert.assertEquals(jar.getFileName().toString(), listEntry.name); Assert.assertEquals(storedJarName, listEntry.id); final JobPlanInfo planResponse = showPlan(planHandler, storedJarName, restfulGateway); // we're only interested in the core functionality so checking for a small detail is sufficient Assert.assertThat(planResponse.getJsonPlan(), containsString("TestProgram.java:29")); runJar(runHandler, storedJarName, restfulGateway); deleteJar(deleteHandler, storedJarName, restfulGateway); final JarListInfo postDeleteListResponse = listJars(listHandler, restfulGateway); Assert.assertEquals(0, postDeleteListResponse.jarFileList.size()); }