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

The following examples show how to use java.nio.file.Files#createTempFile() . 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: TestFileSystemProvider.java    From incubator-taverna-language with Apache License 2.0 6 votes vote down vote up
@Test
public void newFileSystemURI() throws Exception {
	Path path = Files.createTempFile("test", null);
	path.toFile().deleteOnExit();
	Files.delete(path);

	URI uri = new URI("app", path.toUri().toASCIIString(), (String) null);

	Map<String, String> env = new HashMap<>();
	env.put("create", "true");
	// And the optional mimetype
	env.put("mimetype", "application/x-test2");
	FileSystem f = FileSystems.newFileSystem(uri, env, getClass()
			.getClassLoader());
	assertTrue(Files.exists(path));
	assertEquals(
			"application/x-test2",
			Files.readAllLines(f.getPath("mimetype"),
					Charset.forName("ASCII")).get(0));
}
 
Example 2
Source File: MojoExecutor.java    From heroku-maven-plugin with MIT License 6 votes vote down vote up
public static Path createDependencyListFile(MavenProject mavenProject,
                                            MavenSession mavenSession,
                                            BuildPluginManager pluginManager) throws MojoExecutionException, IOException {

    Path path = Files.createTempFile("heroku-maven-plugin", "mvn-dependency-list.log");

    executeMojo(
            plugin(
                    groupId("org.apache.maven.plugins"),
                    artifactId("maven-dependency-plugin"),
                    version("2.4")
            ),
            goal("list"),
            configuration(
                    element(name("outputFile"), path.toString())
            ),
            executionEnvironment(
                    mavenProject,
                    mavenSession,
                    pluginManager
            )
    );

    return path;
}
 
Example 3
Source File: Standard.java    From presto with Apache License 2.0 6 votes vote down vote up
public static void enablePrestoJavaDebugger(DockerContainer container, int debugPort)
{
    try {
        FileAttribute<Set<PosixFilePermission>> rwx = PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwxrwxrwx"));
        Path script = Files.createTempFile("enable-java-debugger", ".sh", rwx);
        Files.writeString(
                script,
                format(
                        "#!/bin/bash\n" +
                                "printf '%%s\\n' '%s' >> '%s'\n",
                        "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=0.0.0.0:" + debugPort,
                        CONTAINER_PRESTO_JVM_CONFIG),
                UTF_8);
        container.withCopyFileToContainer(MountableFile.forHostPath(script), "/docker/presto-init.d/enable-java-debugger.sh");

        // expose debug port unconditionally when debug is enabled
        exposePort(container, debugPort);
    }
    catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 4
Source File: ArgParserTest.java    From pacaya with Apache License 2.0 6 votes vote down vote up
@Test()
public void testFlagFile() throws ParseException, IOException {
    // Create a temporary file.
    Path ff = Files.createTempFile(Paths.get("."), "flagfile", ".txt");
    try {
        Files.write(ff, Lists.newArrayList(
                "# My flag file", 
                "   ",
                "# My double",
                "--doubleVal=3",
                "# My int",
                " --intVal=3",
                "  "));
        
        String[] args = ("--intVal=2 --flagfile="+ff.toString()).split(" ");
        ArgParser parser = new ArgParser(ArgParserTest.class, true);
        parser.registerClass(ArgParserTest.class);
        parser.parseArgsNoExit(args);

        Assert.assertEquals(2, intVal); // The command line value overrides the flagfile.
        Assert.assertEquals(3, doubleVal, 1e-13);
    } finally {
        Files.delete(ff);
    }
}
 
Example 5
Source File: TestDatabase.java    From org.openntf.domino with Apache License 2.0 5 votes vote down vote up
@Test
public void testCopyDatabase() throws IOException {
	Session session = Factory.getSession();
	Database database = session.getDatabase(AllTests.EMPTY_DB);
	
	Path tempPath = Files.createTempFile(getClass().getSimpleName(), ".nsf");
	Files.deleteIfExists(tempPath);
	
	Database copy = database.createCopy("", tempPath.toString());
	assertNotEquals("copy should not be null", null, copy);
	assertNotEquals("Replica IDs should differ", database.getReplicaID(), copy.getReplicaID());
	
	AllTests.EMPTY_DB_COPY = tempPath.toString();
}
 
Example 6
Source File: OLMOperatorManager.java    From enmasse with Apache License 2.0 5 votes vote down vote up
public void deployCatalogSource(String catalogSourceName, String catalogNamespace, String customRegistryImageToUse) throws IOException {
    Path catalogSourceFile = Files.createTempFile("catalogsource", ".yaml");
    String catalogSource = Files.readString(Paths.get(System.getProperty("user.dir"), "custom-operator-registry", "catalog-source.yaml"));
    Files.writeString(catalogSourceFile,
            catalogSource
                    .replaceAll("\\$\\{CATALOG_SOURCE_NAME}", catalogSourceName)
                    .replaceAll("\\$\\{OPERATOR_NAMESPACE}", catalogNamespace)
                    .replaceAll("\\$\\{REGISTRY_IMAGE}", customRegistryImageToUse));
    KubeCMDClient.applyFromFile(catalogNamespace, catalogSourceFile);
}
 
Example 7
Source File: FilesDelegateTest.java    From tessera with Apache License 2.0 5 votes vote down vote up
@Test
public void notExists() throws Exception {
    Path existentFile = Files.createTempFile(UUID.randomUUID().toString(), ".txt");
    existentFile.toFile().deleteOnExit();
    Path nonExistentFile = Paths.get(UUID.randomUUID().toString());

    assertThat(filesDelegate.notExists(existentFile)).isFalse();
    assertThat(filesDelegate.notExists(nonExistentFile)).isTrue();
}
 
Example 8
Source File: FileVerifiersTest.java    From pf4j-update with Apache License 2.0 5 votes vote down vote up
@Test
public void testSha512Verifier() throws IOException, VerifyException {
    FileVerifier fileVerifier = new Sha512SumVerifier();
    Path testFile = Files.createTempFile("test", ".tmp");
    Files.write(testFile, "Test".getBytes("utf-8"));
    String sha512sum = "c6ee9e33cf5c6715a1d148fd73f7318884b41adcb916021e2bc0e800a5c5dd97f5142178f6ae88c8fdd98e1afb0ce4c8d2c54b5f37b30b7da1997bb33b0b8a31";
    fileVerifier.verify(new FileVerifier.Context("foo", new Date(), "1.2.3",
            null, "http://example.com/repo/foo-1.2.3.zip", sha512sum), testFile);
    Files.delete(testFile);
}
 
Example 9
Source File: TestReadTwice.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Throwable {
    Recording r = new Recording();
    r.enable(MyEvent.class).withoutStackTrace();
    r.start();

    // Commit a single event to the recording
    MyEvent event = new MyEvent();
    event.commit();

    r.stop();

    // Dump the recording to a file
    Path path = Files.createTempFile("recording", ".jfr");
    System.out.println("Dumping to " + path);
    r.dump(path);
    r.close();

    // Read all events from the file in one go
    List<RecordedEvent> events = RecordingFile.readAllEvents(path);

    // Read again the same events one by one
    RecordingFile rfile = new RecordingFile(path);
    List<RecordedEvent> events2 = new LinkedList<>();
    while (rfile.hasMoreEvents()) {
        events2.add(rfile.readEvent());
    }

    // Compare sizes
    Asserts.assertEquals(events.size(), events2.size());
    rfile.close();
}
 
Example 10
Source File: TestGenerateESExperiments.java    From quaerite with Apache License 2.0 5 votes vote down vote up
@BeforeAll
public static void setUp() throws Exception {
    JSON = Files.createTempFile("quaerite-features", ".json");
    EXPERIMENTS = Files.createTempFile("quaerite-experiments", ".json");
    Files.copy(
            TestGenerateESExperiments.class.getResourceAsStream(
                    "/test-documents/experiment_features_es_1.json"),
            JSON, StandardCopyOption.REPLACE_EXISTING);
}
 
Example 11
Source File: AuthenticatedImagePullTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
private Path getLocalTempFile(String s) throws IOException {
    Path projectRoot = Paths.get(".");
    Path tempDirectory = Files.createTempDirectory(projectRoot, this.getClass().getSimpleName() + "-test-");
    Path relativeTempDirectory = projectRoot.relativize(tempDirectory);
    Path tempFile = Files.createTempFile(relativeTempDirectory, "test", s);

    tempDirectory.toFile().deleteOnExit();
    tempFile.toFile().deleteOnExit();

    return tempFile;
}
 
Example 12
Source File: FilesDelegateTest.java    From tessera with Apache License 2.0 5 votes vote down vote up
@Test
public void lines() throws Exception {
    Path somefile = Files.createTempFile("FilesDelegateTest#lines", ".txt");
    somefile.toFile().deleteOnExit();
    try (BufferedWriter writer = Files.newBufferedWriter(somefile)) {
        writer.write("ONE");
        writer.newLine();
        writer.write("");
        writer.newLine();
        writer.write("THREE");
    }

    List<String> results = filesDelegate.lines(somefile).collect(Collectors.toList());
    assertThat(results).containsExactly("ONE", "", "THREE");
}
 
Example 13
Source File: SpannerReadIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void readDbEndToEnd() throws Exception {
  Path outPath = Files.createTempFile("out", "txt");
  SpannerReadAll.main(
      new String[] {
        "--instanceId=" + instanceId,
        "--databaseId=" + databaseId,
        "--output=" + outPath,
        "--runner=DirectRunner"
      });

  String content = Files.readAllLines(outPath).stream().collect(Collectors.joining("\n"));

  assertEquals("132", content);
}
 
Example 14
Source File: ALSUpdateIT.java    From oryx with Apache License 2.0 5 votes vote down vote up
private static Path copyAndUncompress(Path compressed) throws IOException {
  Path tempFile = Files.createTempFile("part", ".csv");
  tempFile.toFile().deleteOnExit();
  try (InputStream in = new GZIPInputStream(Files.newInputStream(compressed))) {
    Files.copy(in, tempFile, StandardCopyOption.REPLACE_EXISTING);
  }
  return tempFile;
}
 
Example 15
Source File: TestCombineManifest.java    From incubator-taverna-language with Apache License 2.0 5 votes vote down vote up
@Test
public void convertDirectoryMadnessZipped() throws Exception {
	Path file = Files.createTempFile("DirectoryMadnessZipped", ".omex");
	try (InputStream src = getClass().getResourceAsStream(
			"/combine/DirectoryMadnessZipped-skeleton.omex")) {
		Files.copy(src, file, StandardCopyOption.REPLACE_EXISTING);
	}
	//System.out.println(file);
	try (Bundle bundle = Bundles.openBundle(file)) {

	}
}
 
Example 16
Source File: ZipOutputStreamTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Before
public void createZipFileDestination() throws IOException {
  output = Files.createTempFile("example", ".zip");
}
 
Example 17
Source File: LegacyCliAdapterTest.java    From tessera with Apache License 2.0 4 votes vote down vote up
@Test
public void withoutCliArgsAllConfigIsSetFromTomlFile() throws Exception {
    dataDirectory = Paths.get("data");
    Files.createDirectory(dataDirectory);

    Path alwaysSendTo1 = Files.createFile(dataDirectory.resolve("alwayssendto1"));
    Files.write(
            alwaysSendTo1,
            ("/+UuD63zItL1EbjxkKUljMgG8Z1w0AJ8pNOR4iq2yQc=\n" + "jWKqelS4XjJ67JBbuKE7x9CVGFJ706wRYy/ev/OCOzk=")
                    .getBytes());

    Path alwaysSendTo2 = Files.createFile(dataDirectory.resolve("alwayssendto2"));
    Files.write(alwaysSendTo2, "yGcjkFyZklTTXrn8+WIkYwicA2EGBn9wZFkctAad4X0=".getBytes());

    Path sampleFile = Paths.get(getClass().getResource("/sample-toml-no-nulls.conf").toURI());
    Map<String, Object> params = new HashMap<>();
    params.put("alwaysSendToPath1", "alwayssendto1");
    params.put("alwaysSendToPath2", "alwayssendto2");

    String data = ElUtil.process(new String(Files.readAllBytes(sampleFile)), params);

    Path configFile = Files.createTempFile("noOptions", ".txt");
    Files.write(configFile, data.getBytes());

    commandLine.execute("--tomlfile", configFile.toString());
    final CliResult result = commandLine.getExecutionResult();

    assertThat(result).isNotNull();
    assertThat(result.getConfig()).isPresent();
    final Config config = result.getConfig().get();
    final ServerConfig p2pServer = config.getP2PServerConfig();
    final SslConfig sslConfig = p2pServer.getSslConfig();

    assertThat(p2pServer.getServerAddress()).isEqualTo("http://127.0.0.1:9001");
    assertThat(p2pServer.getBindingAddress()).isEqualTo("http://127.0.0.1:9001");
    assertThat(this.getUnixSocketServerAddress(config))
            .isEqualTo("unix:" + Paths.get("data/constellation.ipc").toAbsolutePath());
    assertThat(config.getPeers())
            .hasSize(2)
            .extracting("url")
            .containsExactlyInAnyOrder("http://127.0.0.1:9001/", "http://127.0.0.1:9002/");
    assertThat(config.getKeys().getKeyData())
            .hasSize(2)
            .extracting("publicKeyPath", "privateKeyPath")
            .containsExactlyInAnyOrder(
                    Tuple.tuple(Paths.get("data/foo.pub"), Paths.get("data/foo.key")),
                    Tuple.tuple(Paths.get("data/foo2.pub"), Paths.get("data/foo2.key")));
    assertThat(config.getAlwaysSendTo())
            .hasSize(3)
            .containsExactlyInAnyOrder(
                    "/+UuD63zItL1EbjxkKUljMgG8Z1w0AJ8pNOR4iq2yQc=",
                    "jWKqelS4XjJ67JBbuKE7x9CVGFJ706wRYy/ev/OCOzk=",
                    "yGcjkFyZklTTXrn8+WIkYwicA2EGBn9wZFkctAad4X0=");
    assertThat(config.getKeys().getPasswordFile().toString()).isEqualTo("data/passwords");
    assertThat(config.getJdbcConfig().getUrl()).isEqualTo("jdbc:h2:mem:tessera");
    assertThat(config.isUseWhiteList()).isTrue();
    assertThat(sslConfig.getTls()).isEqualByComparingTo(SslAuthenticationMode.STRICT);
    assertThat(sslConfig.getServerTlsCertificatePath().toString()).isEqualTo("data/tls-server-cert.pem");
    assertThat(sslConfig.getServerTrustCertificates())
            .hasSize(2)
            .containsExactlyInAnyOrder(Paths.get("data/chain1"), Paths.get("data/chain2"));
    assertThat(sslConfig.getServerTlsKeyPath().toString()).isEqualTo("data/tls-server-key.pem");
    assertThat(sslConfig.getServerTrustMode()).isEqualByComparingTo(SslTrustMode.TOFU);
    assertThat(sslConfig.getKnownClientsFile().toString()).isEqualTo("data/tls-known-clients");
    assertThat(sslConfig.getClientTlsCertificatePath().toString()).isEqualTo("data/tls-client-cert.pem");
    assertThat(sslConfig.getClientTrustCertificates())
            .hasSize(2)
            .containsExactlyInAnyOrder(Paths.get("data/clientchain1"), Paths.get("data/clientchain2"));
    assertThat(sslConfig.getClientTlsKeyPath().toString()).isEqualTo("data/tls-client-key.pem");
    assertThat(sslConfig.getClientTrustMode()).isEqualByComparingTo(SslTrustMode.CA_OR_TOFU);
    assertThat(sslConfig.getKnownServersFile().toString()).isEqualTo("data/tls-known-servers");
}
 
Example 18
Source File: ImageListener.java    From logbook-kai with MIT License 4 votes vote down vote up
private Path tempFile() throws IOException {
    return Files.createTempFile("ImageListener-", "");
}
 
Example 19
Source File: AbstractAssetProcessor.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
private Path createTmpFile(String repoPath) throws IOException {
    return Files.createTempFile(FilenameUtils.getBaseName(repoPath), "." + FilenameUtils.getExtension(repoPath));
}
 
Example 20
Source File: NettyClientTest.java    From selenium with Apache License 2.0 4 votes vote down vote up
@Before
public void setupUnixDomainSocketServer() throws IOException, URISyntaxException {
  Class<? extends ServerDomainSocketChannel> channelType = null;

  if (Epoll.isAvailable()) {
    group = new EpollEventLoopGroup(2);
    channelType = EpollServerDomainSocketChannel.class;
  } else if (KQueue.isAvailable()) {
    group = new KQueueEventLoopGroup(2);
    channelType = KQueueServerDomainSocketChannel.class;
  }

  assumeThat(group).isNotNull();
  assumeThat(channelType).isNotNull();

  ServerBootstrap bootstrap = new ServerBootstrap()
    .group(group)
    .option(ChannelOption.SO_BACKLOG, 1024)
    .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
    .channel(channelType)
    .childHandler(new ChannelInitializer<DomainSocketChannel>() {
      @Override
      protected void initChannel(DomainSocketChannel ch) {
        ch.pipeline()
          .addLast("http-codec", new HttpServerCodec())
          .addLast("http-keep-alive", new HttpServerKeepAliveHandler())
          .addLast("http-aggregator", new HttpObjectAggregator(Integer.MAX_VALUE))
          .addLast(new SimpleChannelInboundHandler<FullHttpRequest>() {
            @Override
            protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) {
              byte[] bytes = responseText.get().getBytes(UTF_8);
              ByteBuf text = Unpooled.wrappedBuffer(bytes);
              FullHttpResponse res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, text);
              res.headers().set(CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8.toString());
              res.headers().set(CONTENT_LENGTH, bytes.length);

              ctx.writeAndFlush(res);
            }
          });
      }
    });

  Path temp = Files.createTempFile("domain-socket-test", "socket");
  Files.deleteIfExists(temp);

  SocketAddress address = new DomainSocketAddress(temp.toFile());
  future = bootstrap.bind(address);

  socket = new URI("unix", null, null, 0, temp.toString(), null, null);
}