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

The following are Jave code examples for showing how to use createTempFile() of the java.nio.file.Files class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: openjdk-jdk10   File: ZeroDate.java   Source Code and License Vote up 10 votes
public static void main(String[] args) throws Exception {
    // create a zip file, and read it in as a byte array
    Path path = Files.createTempFile("bad", ".zip");
    try (OutputStream os = Files.newOutputStream(path);
            ZipOutputStream zos = new ZipOutputStream(os)) {
        ZipEntry e = new ZipEntry("x");
        zos.putNextEntry(e);
        zos.write((int) 'x');
    }
    int len = (int) Files.size(path);
    byte[] data = new byte[len];
    try (InputStream is = Files.newInputStream(path)) {
        is.read(data);
    }
    Files.delete(path);

    // year, month, day are zero
    testDate(data.clone(), 0, LocalDate.of(1979, 11, 30));
    // only year is zero
    testDate(data.clone(), 0 << 25 | 4 << 21 | 5 << 16, LocalDate.of(1980, 4, 5));
}
 
Example 2
Project: centraldogma   File: FileBasedSessionDAO.java   Source Code and License Vote up 7 votes
@Override
public void update(Session session) {
    final String sessionId = ensureStringSessionId(session);
    final Path oldPath = sessionId2Path(sessionId);
    if (!Files.exists(oldPath)) {
        throw new UnknownSessionException(sessionId);
    }

    try {
        final Path newPath = Files.createTempFile(tmpDir, null, null);
        Files.write(newPath, serialize(session));
        Files.move(newPath, oldPath, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new SerializationException(e);
    }
}
 
Example 3
Project: hype   File: ManifestLoaderTest.java   Source Code and License Vote up 6 votes
@Test
public void end2endStaging() throws Exception {
  List<StagedPackage> stagedPackages =
      StagingUtil.stageClasspathElements(testFiles, stagingLocation);

  RunManifest manifest = new RunManifestBuilder()
      .continuation(stagedPackages.get(0).name())
      .files(stagedPackages.stream().map(StagedPackage::name).collect(toList()))
      .build();

  Path manifestFile = stagingPath.resolve("manifest.txt");
  RunManifest.write(manifest, manifestFile);

  // add one extra file to staging directory
  Files.createTempFile(stagingPath, "extra", "");
  List<Path> stagedFiles = Files.list(stagingPath).collect(toList());
  assertThat(stagedFiles.size(), is(testFiles.size() + 2)); // extra + manifest

  Path readPath = Files.createTempDirectory("unit-test");
  RunManifest downloadedManifest = ManifestLoader.downloadManifest(manifestFile, readPath);

  List<Path> readFiles = Files.list(readPath).collect(toList());
  assertThat(readFiles.size(), is(testFiles.size()));
  assertThat(downloadedManifest, is(manifest));
}
 
Example 4
Project: ios-device-control   File: ExampleSimulatorDeviceControl.java   Source Code and License Vote up 6 votes
public static void main(String[] args) throws Exception {
  FluentLogger logger = FluentLogger.forEnclosingClass();
  SimulatorDeviceHost simHost = SimulatorDeviceHost.INSTANCE;

  // Optionally shutdown all devices before starting one.
  simHost.shutdownAllDevices();

  // Pick an arbitrary device.
  SimulatorDevice sim = (SimulatorDevice) simHost.connectedDevices().iterator().next();
  // Or specify one by udid
  // SimulatorDevice sim = (SimulatorDevice) simHost.connectedDevice(udid);

  // Start the device before interacting with it.
  sim.startup();

  // The device can now be interacted with. Here is an example of starting Safari, taking a
  // screenshot, then closing Safari
  IosAppProcess safariProcess = sim.runApplication(new IosAppBundleId("com.apple.mobilesafari"));
  byte[] screenshotBytes = sim.takeScreenshot();
  Path screenshotPath = Files.createTempFile("screenshot", ".png");
  Files.write(screenshotPath, screenshotBytes);
  safariProcess.kill();
  logger.atInfo().log("Screenshot written to: %s", screenshotPath);
}
 
Example 5
Project: openjdk-jdk10   File: ZeroDate.java   Source Code and License Vote up 6 votes
private static void testDate(byte[] data, int date, LocalDate expected) throws IOException {
    // set the datetime
    int endpos = data.length - ENDHDR;
    int cenpos = u16(data, endpos + ENDOFF);
    int locpos = u16(data, cenpos + CENOFF);
    writeU32(data, cenpos + CENTIM, date);
    writeU32(data, locpos + LOCTIM, date);

    // ensure that the archive is still readable, and the date is 1979-11-30
    Path path = Files.createTempFile("out", ".zip");
    try (OutputStream os = Files.newOutputStream(path)) {
        os.write(data);
    }
    try (ZipFile zf = new ZipFile(path.toFile())) {
        ZipEntry ze = zf.entries().nextElement();
        Instant actualInstant = ze.getLastModifiedTime().toInstant();
        Instant expectedInstant =
                expected.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
        if (!actualInstant.equals(expectedInstant)) {
            throw new AssertionError(
                    String.format("actual: %s, expected: %s", actualInstant, expectedInstant));
        }
    } finally {
        Files.delete(path);
    }
}
 
Example 6
Project: OpenJSharp   File: DflCache.java   Source Code and License Vote up 6 votes
private static void expunge(Path p, KerberosTime currTime)
        throws IOException {
    Path p2 = Files.createTempFile(p.getParent(), "rcache", null);
    try (SeekableByteChannel oldChan = Files.newByteChannel(p);
            SeekableByteChannel newChan = createNoClose(p2)) {
        long timeLimit = currTime.getSeconds() - readHeader(oldChan);
        while (true) {
            try {
                AuthTime at = AuthTime.readFrom(oldChan);
                if (at.ctime > timeLimit) {
                    ByteBuffer bb = ByteBuffer.wrap(at.encode(true));
                    newChan.write(bb);
                }
            } catch (BufferUnderflowException e) {
                break;
            }
        }
    }
    makeMine(p2);
    Files.move(p2, p,
            StandardCopyOption.REPLACE_EXISTING,
            StandardCopyOption.ATOMIC_MOVE);
}
 
Example 7
Project: reactivejournal   File: ReactiveJournalDirectoryTest.java   Source Code and License Vote up 6 votes
@Test
public void rxJournalClearsOnlyCq4FilesAndKeepsBaseDir() throws IOException {
    Files.createDirectories(expectedDir);
    Path tempFile = Files.createTempFile(expectedDir, "rxJournalClearsOnlyCq4", ".txt");

    ReactiveJournal journal = new ReactiveJournal(base.toString());

    ReactiveRecorder recorder = journal.createReactiveRecorder();
    recorder.record(Flowable.just("foo"), "");

    //short circuit the test if the dir is unexpected, just in case the clearCache would then be too destructive
    Assert.assertEquals(expectedDir.toString(), journal.getDir());

    journal.clearCache();

    Assert.assertTrue(Files.exists(expectedDir));
    Assert.assertTrue(Files.exists(tempFile));

    long count = Files.walk(expectedDir, 1)
            .map(Path::toFile)
            .filter(File::isFile)
            .count();

    Assert.assertEquals(1, count);
}
 
Example 8
Project: openjdk-jdk10   File: TestLambdaFormRetransformation.java   Source Code and License Vote up 6 votes
private static Path buildAgent() throws IOException {
    Path manifest = TestLambdaFormRetransformation.createManifest();
    Path jar = Files.createTempFile(Paths.get("."), null, ".jar");

    String[] args = new String[] {
        "-cfm",
        jar.toAbsolutePath().toString(),
        manifest.toAbsolutePath().toString(),
        "-C",
        TestLambdaFormRetransformation.CP,
        Agent.class.getName() + ".class"
    };

    sun.tools.jar.Main jarTool = new sun.tools.jar.Main(System.out, System.err, "jar");

    if (!jarTool.run(args)) {
        throw new Error("jar failed: args=" + Arrays.toString(args));
    }
    return jar;
}
 
Example 9
Project: OpenJSharp   File: Driver.java   Source Code and License Vote up 6 votes
static private
File createTempFile(String basefile, String suffix) throws IOException {
    File base = new File(basefile);
    String prefix = base.getName();
    if (prefix.length() < 3)  prefix += "tmp";

    File where = (base.getParentFile() == null && suffix.equals(".bak"))
            ? new File(".").getAbsoluteFile()
            : base.getParentFile();

    Path tmpfile = (where == null)
            ? Files.createTempFile(prefix, suffix)
            : Files.createTempFile(where.toPath(), prefix, suffix);

    return tmpfile.toFile();
}
 
Example 10
Project: hype   File: ManifestUtilTest.java   Source Code and License Vote up 5 votes
@Test
public void writeManifest() throws Exception {
  Path manifest = Files.createTempFile("manifest", ".txt");
  ManifestUtil.write(EXAMPLE, manifest);

  List<String> expected = Files.readAllLines(load("/example-manifest.txt"));
  List<String> strings = Files.readAllLines(manifest);

  assertThat(strings, is(expected));
}
 
Example 11
Project: instalint   File: PluginCache.java   Source Code and License Vote up 5 votes
private Path newTempFile() {
  try {
    return Files.createTempFile(tmpDirInCacheDir, null, null);
  } catch (IOException e) {
    throw new IllegalStateException("Fail to create temp file in " + tmpDirInCacheDir, e);
  }
}
 
Example 12
Project: Stargraph   File: ElasticIndexerIT.java   Source Code and License Vote up 5 votes
@BeforeClass
public void before() throws Exception {
    Path root = Files.createTempFile("stargraph-", "-dataDir");
    Path hdtPath = createPath(root, factsId).resolve("triples.hdt");
    copyResource("dataSets/obama/facts/triples.hdt", hdtPath);
    System.setProperty("stargraph.data.root-dir", root.toString());
    ConfigFactory.invalidateCaches();
    stargraph = new Stargraph();

    //TODO: replace with KBLoader#loadAll()
    loadProperties(stargraph);
    loadEntities(stargraph);
    loadFacts(stargraph);
}
 
Example 13
Project: elasticsearch_my   File: SystemCallFilter.java   Source Code and License Vote up 5 votes
/** try to install our custom rule profile into sandbox_init() to block execution */
private static void macImpl(Path tmpFile) throws IOException {
    // first be defensive: we can give nice errors this way, at the very least.
    boolean supported = Constants.MAC_OS_X;
    if (supported == false) {
        throw new IllegalStateException("bug: should not be trying to initialize seatbelt for an unsupported OS");
    }

    // we couldn't link methods, could be some really ancient OS X (< Leopard) or some bug
    if (libc_mac == null) {
        throw new UnsupportedOperationException("seatbelt unavailable: could not link methods. requires Leopard or above.");
    }

    // write rules to a temporary file, which will be passed to sandbox_init()
    Path rules = Files.createTempFile(tmpFile, "es", "sb");
    Files.write(rules, Collections.singleton(SANDBOX_RULES));

    boolean success = false;
    try {
        PointerByReference errorRef = new PointerByReference();
        int ret = libc_mac.sandbox_init(rules.toAbsolutePath().toString(), SANDBOX_NAMED, errorRef);
        // if sandbox_init() fails, add the message from the OS (e.g. syntax error) and free the buffer
        if (ret != 0) {
            Pointer errorBuf = errorRef.getValue();
            RuntimeException e = new UnsupportedOperationException("sandbox_init(): " + errorBuf.getString(0));
            libc_mac.sandbox_free_error(errorBuf);
            throw e;
        }
        logger.debug("OS X seatbelt initialization successful");
        success = true;
    } finally {
        if (success) {
            Files.delete(rules);
        } else {
            IOUtils.deleteFilesIgnoringExceptions(rules);
        }
    }
}
 
Example 14
Project: s3-channels   File: AbstractS3WritableObjectChannelSuite.java   Source Code and License Vote up 5 votes
protected void verifyFileContentEquality() throws IOException {
    final Path tmp = Files.createTempFile("tmp", "" + key.hashCode());
    defaultAmazonS3().getObject(new GetObjectRequest(testBucket, key), tmp.toFile());

    assertArrayEquals(Files.readAllBytes(file.path), Files.readAllBytes(tmp));

    Files.delete(tmp);
}
 
Example 15
Project: JavaRushTasks   File: FileBucket.java   Source Code and License Vote up 5 votes
public FileBucket() {
    try {
        path = Files.createTempFile(null, null);
        Files.deleteIfExists(path);
        Files.createFile(path);
    } catch (IOException e) {
        ExceptionHandler.log(e);
    }
    path.toFile().deleteOnExit();
}
 
Example 16
Project: openjdk-jdk10   File: ExternalEditor.java   Source Code and License Vote up 5 votes
/**
 * Creates a WatchService and registers the given directory
 */
private void setupWatch(final String initialText) throws IOException {
    this.watcher = FileSystems.getDefault().newWatchService();
    this.dir = Files.createTempDirectory("REPL");
    this.tmpfile = Files.createTempFile(dir, null, ".js");
    Files.write(tmpfile, initialText.getBytes(Charset.forName("UTF-8")));
    dir.register(watcher,
            ENTRY_CREATE,
            ENTRY_DELETE,
            ENTRY_MODIFY);
    watchedThread = new Thread(() -> {
        for (;;) {
            WatchKey key;
            try {
                key = watcher.take();
            } catch (final ClosedWatchServiceException ex) {
                break;
            } catch (final InterruptedException ex) {
                continue; // tolerate an intrupt
            }

            if (!key.pollEvents().isEmpty()) {
                if (!input.terminalEditorRunning()) {
                    saveFile();
                }
            }

            boolean valid = key.reset();
            if (!valid) {
                errorHandler.accept("Invalid key");
                break;
            }
        }
    });
    watchedThread.start();
}
 
Example 17
Project: openjdk-jdk10   File: ParallelProbes.java   Source Code and License Vote up 5 votes
private Path createTmpFile() throws IOException {
    Path dir = Paths.get(System.getProperty("test.dir", "."));
    final Path p = Files.createTempFile(dir, "prefix", ".json");
    Files.write(p, "{\"test\"}".getBytes());
    System.out.println("Write test file <" + p + ">");
    return p;
}
 
Example 18
Project: gw4e.project   File: ProcessFacade.java   Source Code and License Vote up 5 votes
public static File buildOfflineShellFile(IJavaProject jproject, IFile graphModel, String pathGenerator,
		String startElement) throws CoreException, IOException {
	IRuntimeClasspathEntry e = JavaRuntime.computeJREEntry(jproject);
	IVMInstall intall = JavaRuntime.getVMInstall(e.getPath());

	StringBuilder sb = new StringBuilder();
	File javaLocation = intall.getInstallLocation();

	sb.append(javaLocation.getAbsolutePath()).append(File.separator).append("bin").append(File.separator)
			.append("java").append(" -cp ").append("\"");

	String cpSeparator = "";
	String[] classpath = JavaRuntime.computeDefaultRuntimeClassPath(jproject);
	for (String cpElement : classpath) {
		sb.append(cpSeparator).append(cpElement);
		cpSeparator = System.getProperty("path.separator");
	}

	sb.append("\"").append(" org.graphwalker.cli.CLI ").append(" offline ").append(" -m ")
			.append(ResourceManager.toFile(graphModel.getFullPath()).getAbsolutePath()).append(" \"")
			.append(pathGenerator).append("\" ").append(" -e ").append(startElement).append(" --verbose ");

	 
	String extension = isWindows() ? "bat" : "sh";

	Path path = Files.createTempFile("offlineShellRunner", "." + extension);

	Files.write(path, sb.toString().getBytes(StandardCharsets.UTF_8));

	File file = path.toFile();
	 
	ResourceManager.logInfo(jproject.getProject().getName(), "Shell file : " + file.getAbsolutePath());
	return file;
}
 
Example 19
Project: elasticsearch_my   File: Security.java   Source Code and License Vote up 5 votes
/** Simple checks that everything is ok */
@SuppressForbidden(reason = "accesses jvm default tempdir as a self-test")
static void selfTest() throws IOException {
    // check we can manipulate temporary files
    try {
        Path p = Files.createTempFile(null, null);
        try {
            Files.delete(p);
        } catch (IOException ignored) {
            // potentially virus scanner
        }
    } catch (SecurityException problem) {
        throw new SecurityException("Security misconfiguration: cannot access java.io.tmpdir", problem);
    }
}
 
Example 20
Project: ciesvium   File: EncryptedDataSetTest.java   Source Code and License Vote up 4 votes
private EncryptedDataSet[] createAndReadDataSet(SecretKey key1, SecretKey key2) throws IOException, CryptoException {

        final Path plain_text_path = Files.createTempFile("test", ".csv");
        final Path cipher_text_path = Files.createTempFile("test", ".txt");

        try (final OutputStreamWriter writer = FileManipulation.getOutputStreamWriter(plain_text_path)) {
            writer.append("the quick brown fox\njumps over the lazy dog");
        }

        // Creation.

        final EncryptedDataSet new_data_set = new EncryptedDataSet(plain_text_path);
        new_data_set.print(cipher_text_path, key1);

        // Use.

        EncryptedDataSet existing_data_set = new EncryptedDataSet(cipher_text_path, key2);

        return new EncryptedDataSet[]{new_data_set, existing_data_set};
    }