Java Code Examples for java.io.File.deleteOnExit()

The following are Jave code examples for showing how to use deleteOnExit() of the java.io.File class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: openjdk-jdk10   File: XmlTest.java   View Source Code Vote up 10 votes
public void test() throws Exception {

        File file = new File("message.xml");
        file.deleteOnExit();

        MessageFactory mf = MessageFactory.newInstance();
        SOAPMessage msg = createMessage(mf);

        // Save the soap message to file
        try (FileOutputStream sentFile = new FileOutputStream(file)) {
            msg.writeTo(sentFile);
        }

        // See if we get the image object back
        try (FileInputStream fin = new FileInputStream(file)) {
            SOAPMessage newMsg = mf.createMessage(msg.getMimeHeaders(), fin);

            newMsg.writeTo(new ByteArrayOutputStream());

            Iterator<?> i = newMsg.getAttachments();
            while (i.hasNext()) {
                AttachmentPart att = (AttachmentPart) i.next();
                Object obj = att.getContent();
                if (!(obj instanceof StreamSource)) {
                    fail("Got incorrect attachment type [" + obj.getClass() + "], " +
                         "expected [javax.xml.transform.stream.StreamSource]");
                }
            }
        }

    }
 
Example 2
Project: secrets-locker   File: KmsEncryptionServiceIT_encryptFile.java   View Source Code Vote up 6 votes
@Test
public void testEncryptFile_filename() throws IOException {

    File encryptedFile
            = new File(
                    encryptionService
                            .encryptFile(
                                    plainTextFilename));

    encryptedFile
            .deleteOnExit();

    KmsDecryptionService
            .instance()
            .decryptFile(
                    encryptedFile,
                    decryptedFilename);

    assertEquals(
            SECRET_FILE_CONTENTS,
            new String(
                    Files.readAllBytes(
                            Paths.get(
                                    decryptedFilename))));
}
 
Example 3
Project: Weather-Forecast   File: GetCurrentRegion.java   View Source Code Vote up 6 votes
private File getResourceAsFile(String resourcePath) {
    try {
        InputStream in = getClass().getResourceAsStream(resourcePath);
        if (in == null) {
            return null;
        }

        File tempFile = File.createTempFile(String.valueOf(in.hashCode()), ".tmp");
        tempFile.deleteOnExit();

        try (FileOutputStream out = new FileOutputStream(tempFile)) {
            byte[] buffer = new byte[2048];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
        return tempFile;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 4
Project: scanning   File: AcquireRequestTest.java   View Source Code Vote up 6 votes
private AcquireRequest createRequest() throws IOException {
	final AcquireRequest request = new AcquireRequest();

	final File file = File.createTempFile("acquire_servlet_test", ".nxs");
	System.err.println("Writing to file " + file);
	file.deleteOnExit();
	request.setFilePath(file.getAbsolutePath());

	final MandelbrotModel mandyModel = new MandelbrotModel();
	mandyModel.setName("mandelbrot");
	mandyModel.setRealAxisName("xNex");
	mandyModel.setImaginaryAxisName("yNex");
	mandyModel.setExposureTime(0.01);

	request.setDetectorName(mandyModel.getName());
	request.setDetectorModel(mandyModel);

	return request;
}
 
Example 5
Project: incubator-netbeans   File: FileBasedFileSystem.java   View Source Code Vote up 5 votes
@Override
public FileObject createTempFile(FileObject parent, String prefix, String suffix, boolean deleteOnExit) throws IOException {
    if (parent.isFolder() && parent.isValid()) {
        File tmpFile = File.createTempFile(prefix, suffix, FileUtil.toFile(parent));
        if (deleteOnExit) {
            tmpFile.deleteOnExit();
        }
        FileObject fo = FileUtil.toFileObject(tmpFile);
        if (fo != null && fo.isData() && fo.isValid()) {
            return fo;
        }
        tmpFile.delete();
    }
    throw new IOException("Cannot create temporary file"); // NOI18N
}
 
Example 6
Project: alfresco-repository   File: AbstractWritableContentStoreTest.java   View Source Code Vote up 5 votes
@Test
public void testReadAndWriteFile() throws Exception
{
    ContentWriter writer = getWriter();
    
    File sourceFile = TempFileProvider.createTempFile("testReadAndWriteFile", ".txt");
    sourceFile.deleteOnExit();
    // dump some content into the temp file
    String content = "ABC";
    FileOutputStream os = new FileOutputStream(sourceFile);
    os.write(content.getBytes());
    os.flush();
    os.close();
    
    // put our temp file's content
    writer.putContent(sourceFile);
    assertTrue("Stream close not detected", writer.isClosed());
    
    // create a sink temp file
    File sinkFile = TempFileProvider.createTempFile("testReadAndWriteFile", ".txt");
    sinkFile.deleteOnExit();
    
    // get the content into our temp file
    ContentReader reader = writer.getReader();
    reader.getContent(sinkFile);
    
    // read the sink file manually
    FileInputStream is = new FileInputStream(sinkFile);
    byte[] buffer = new byte[100];
    int count = is.read(buffer);
    assertEquals("No content read", 3, count);
    is.close();
    String check = new String(buffer, 0, count);
    
    assertEquals("Write out of and read into files failed", content, check);
}
 
Example 7
Project: OpenVertretung   File: ConnectionTest.java   View Source Code Vote up 5 votes
public void testLocalInfileDisabled() throws Exception {
    createTable("testLocalInfileDisabled", "(field1 varchar(255))");

    File infile = File.createTempFile("foo", "txt");
    infile.deleteOnExit();
    //String url = infile.toURL().toExternalForm();
    FileWriter output = new FileWriter(infile);
    output.write("Test");
    output.flush();
    output.close();

    Connection loadConn = getConnectionWithProps(new Properties());

    try {
        // have to do this after connect, otherwise it's the server that's enforcing it
        ((com.mysql.jdbc.Connection) loadConn).setAllowLoadLocalInfile(false);
        try {
            loadConn.createStatement().execute("LOAD DATA LOCAL INFILE '" + infile.getCanonicalPath() + "' INTO TABLE testLocalInfileDisabled");
            fail("Should've thrown an exception.");
        } catch (SQLException sqlEx) {
            assertEquals(SQLError.SQL_STATE_GENERAL_ERROR, sqlEx.getSQLState());
        }

        assertFalse(loadConn.createStatement().executeQuery("SELECT * FROM testLocalInfileDisabled").next());
    } finally {
        loadConn.close();
    }
}
 
Example 8
Project: jdk8u-jdk   File: GetFilePointer.java   View Source Code Vote up 5 votes
public static void main(String[] args) throws Exception {
    RIFFWriter writer = null;
    RIFFReader reader = null;
    File tempfile = File.createTempFile("test",".riff");
    try
    {
        writer = new RIFFWriter(tempfile, "TEST");
        RIFFWriter chunk = writer.writeChunk("TSCH");
        chunk.writeByte(10);
        writer.close();
        writer = null;
        FileInputStream fis = new FileInputStream(tempfile);
        reader = new RIFFReader(fis);
        RIFFReader readchunk = reader.nextChunk();
        long p = readchunk.getFilePointer();
        readchunk.readByte();
        assertEquals(p+1,readchunk.getFilePointer());
        fis.close();
        reader = null;


    }
    finally
    {
        if(writer != null)
            writer.close();
        if(reader != null)
            reader.close();

        if(tempfile.exists())
            if(!tempfile.delete())
                tempfile.deleteOnExit();
    }
}
 
Example 9
Project: Bachelor-Thesis   File: SettingsTest.java   View Source Code Vote up 5 votes
protected void setUp() throws Exception {
	super.setUp();
	File tempFile = File.createTempFile("settingsTest", ".tmp");
	tempFile.deleteOnExit();
	
	PrintWriter out = new PrintWriter(tempFile);
	
	for (String s : INPUT) {
		out.println(s);
	}
	out.close();
	
	Settings.init(tempFile.getAbsolutePath());
	s = new Settings();
}
 
Example 10
Project: incubator-netbeans   File: Utils.java   View Source Code Vote up 5 votes
/**
 * Deletes a file. If the file is a directory its contents are recursively
 * deleted.
 *
 * @param file File to be deleted.
 */
public static void delete(final File file) {
    if (file.isDirectory()) {
        for (File child: file.listFiles()) {
            delete(child);
        }
    }
    if (!file.delete()) {
        file.deleteOnExit();
    }
}
 
Example 11
Project: jdk8u-jdk   File: MLet.java   View Source Code Vote up 5 votes
/**
 * Search the specified native library in any of the JAR files
 * loaded by this classloader.  If the library is found copy it
 * into the library directory and return the absolute path.  If
 * the library is not found then return null.
 */
private synchronized String loadLibraryAsResource(String libname) {
    try {
        InputStream is = getResourceAsStream(
                libname.replace(File.separatorChar,'/'));
        if (is != null) {
            try {
                File directory = new File(libraryDirectory);
                directory.mkdirs();
                File file = Files.createTempFile(directory.toPath(),
                                                 libname + ".", null)
                                 .toFile();
                file.deleteOnExit();
                FileOutputStream fileOutput = new FileOutputStream(file);
                try {
                    byte[] buf = new byte[4096];
                    int n;
                    while ((n = is.read(buf)) >= 0) {
                       fileOutput.write(buf, 0, n);
                    }
                } finally {
                    fileOutput.close();
                }
                if (file.exists()) {
                    return file.getAbsolutePath();
                }
            } finally {
                is.close();
            }
        }
    } catch (Exception e) {
        MLET_LOGGER.logp(Level.FINEST, MLet.class.getName(),
                "loadLibraryAsResource",
                "Failed to load library : " + libname, e);
        return null;
    }
    return null;
}
 
Example 12
Project: secrets-locker   File: KmsEncryptionServiceIT_encryptFile.java   View Source Code Vote up 5 votes
@Test
public void testEncryptFile_file() throws IOException {

    File encryptedFile
            = encryptionService
                    .encryptFile(
                            plainTextFile);

    encryptedFile
            .deleteOnExit();

    KmsDecryptionService
            .instance()
            .decryptFile(
                    encryptedFile,
                    decryptedFilename);

    File decryptedFile
            = new File(decryptedFilename);

    decryptedFile
            .deleteOnExit();

    assertEquals(
            SECRET_FILE_CONTENTS,
            new String(
                    Files.readAllBytes(
                            Paths.get(
                                    decryptedFilename))));
}
 
Example 13
Project: scanning   File: BenchmarkScanTest.java   View Source Code Vote up 5 votes
private long benchmarkNexus(int imageSize, long max)  throws Exception {

		MandelbrotModel model = new MandelbrotModel();
		model.setName("mandelbrot");
		model.setRealAxisName("xNex");
		model.setImaginaryAxisName("yNex");
		model.setColumns(imageSize);
		model.setRows(imageSize);
		model.setMaxIterations(1);
		model.setExposureTime(0.0);

		IRunnableDevice<MandelbrotModel> detector = dservice.createRunnableDevice(model);

		final BenchmarkBean bean = new BenchmarkBean(256, 5000l, 1, true, detector);
		File output = File.createTempFile("test_mandel_nexus", ".nxs");
		output.deleteOnExit();
		bean.setFilePath(output.getAbsolutePath());

		try {
			benchmarkStep(bean); // set things up

			// Benchmark things. A good idea to do nothing much else on your machine for this...
			long point1     = benchmarkStep(new BenchmarkBean(1, 100, 1, detector, output)); // should take not more than 2ms sleep + scan time

			// should take not more than 64*point1 + scan time
			long point10    = benchmarkStep(new BenchmarkBean(10,    (10*point1)+fudge, max,   10, detector, output));

			// should take not more than 4*point64 sleep + scan time
			long point100   = benchmarkStep(new BenchmarkBean(100,   (10*point10)+fudge, max,  10, detector, output));

			return point100/100;

		} finally {
		    output.delete();
		}
	}
 
Example 14
Project: alfresco-repository   File: ContentCacheImplTest.java   View Source Code Vote up 4 votes
private File tempfile(String name, String suffix)
{
    File file = TempFileProvider.createTempFile(name, suffix);
    file.deleteOnExit();
    return file;
}
 
Example 15
Project: monarch   File: DUnitLauncher.java   View Source Code Vote up 4 votes
private static void launch() throws URISyntaxException, AlreadyBoundException, IOException,
    InterruptedException, NotBoundException {
  DUNIT_SUSPECT_FILE = new File(SUSPECT_FILENAME);
  DUNIT_SUSPECT_FILE.delete();
  DUNIT_SUSPECT_FILE.deleteOnExit();

  // create an RMI registry and add an object to share our tests config
  int namingPort = AvailablePortHelper.getRandomAvailableTCPPort();
  Registry registry = LocateRegistry.createRegistry(namingPort);
  System.setProperty(RMI_PORT_PARAM, "" + namingPort);

  JUnit4DistributedTestCase.initializeBlackboard();

  final ProcessManager processManager = new ProcessManager(namingPort, registry);
  master = new Master(registry, processManager);
  registry.bind(MASTER_PARAM, master);

  // inhibit banners to make logs smaller
  System.setProperty(InternalLocator.INHIBIT_DM_BANNER, "true");

  // restrict membership ports to be outside of AvailablePort's range
  System.setProperty(DistributionConfig.RESTRICT_MEMBERSHIP_PORT_RANGE, "true");

  Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() {
      // System.out.println("shutting down DUnit JVMs");
      // for (int i=0; i<NUM_VMS; i++) {
      // try {
      // processManager.getStub(i).shutDownVM();
      // } catch (Exception e) {
      // System.out.println("exception shutting down vm_"+i+": " + e);
      // }
      // }
      // // TODO - hasLiveVMs always returns true
      // System.out.print("waiting for JVMs to exit");
      // long giveUp = System.currentTimeMillis() + 5000;
      // while (giveUp > System.currentTimeMillis()) {
      // if (!processManager.hasLiveVMs()) {
      // return;
      // }
      // System.out.print(".");
      // System.out.flush();
      // try {
      // Thread.sleep(1000);
      // } catch (InterruptedException e) {
      // break;
      // }
      // }
      // System.out.println("\nkilling any remaining JVMs");
      processManager.killVMs();
    }
  });

  // Create a VM for the locator
  processManager.launchVM(LOCATOR_VM_NUM);

  // wait for the VM to start up
  if (!processManager.waitForVMs(STARTUP_TIMEOUT)) {
    throw new RuntimeException(STARTUP_TIMEOUT_MESSAGE);
  }

  locatorPort = startLocator(registry);

  init(master);

  // Launch an initial set of VMs
  for (int i = 0; i < NUM_VMS; i++) {
    processManager.launchVM(i);
  }

  // wait for the VMS to start up
  if (!processManager.waitForVMs(STARTUP_TIMEOUT)) {
    throw new RuntimeException(STARTUP_TIMEOUT_MESSAGE);
  }

  // populate the Host class with our stubs. The tests use this host class
  DUnitHost host =
      new DUnitHost(InetAddress.getLocalHost().getCanonicalHostName(), processManager);
  host.init(registry, NUM_VMS);

}
 
Example 16
Project: ProyectoPacientes   File: ConnectionRegressionTest.java   View Source Code Vote up 4 votes
/**
 * Tests fix for BUG#11237 useCompression=true and LOAD DATA LOCAL INFILE SQL Command
 * 
 * @throws Exception
 *             if any errors occur
 */
public void testBug11237() throws Exception {
    this.rs = this.stmt.executeQuery("SHOW VARIABLES LIKE 'max_allowed_packet'");
    this.rs.next();
    if (this.rs.getInt(2) < 4 + 1024 * 1024 * 16 - 1) {
        fail("You need to increase max_allowed_packet to at least " + (4 + 1024 * 1024 * 16 - 1) + " before running this test!");
    }

    int requiredSize = 1024 * 1024 * 300;
    int fieldLength = 1023;
    int loops = requiredSize / 2 / (fieldLength + 1);

    File testFile = File.createTempFile("cj-testloaddata", ".dat");
    testFile.deleteOnExit();

    // TODO: following cleanup doesn't work correctly during concurrent execution of testsuite 
    // cleanupTempFiles(testFile, "cj-testloaddata");

    BufferedOutputStream bOut = new BufferedOutputStream(new FileOutputStream(testFile));

    for (int i = 0; i < loops; i++) {
        for (int j = 0; j < fieldLength; j++) {
            bOut.write("a".getBytes()[0]);
        }
        bOut.write("\t".getBytes()[0]);
        for (int j = 0; j < fieldLength; j++) {
            bOut.write("b".getBytes()[0]);
        }
        bOut.write("\n".getBytes()[0]);
    }

    bOut.flush();
    bOut.close();

    createTable("testBug11237", "(field1 VARCHAR(1024), field2 VARCHAR(1024))");

    StringBuilder fileNameBuf = null;

    if (File.separatorChar == '\\') {
        fileNameBuf = new StringBuilder();

        String fileName = testFile.getAbsolutePath();
        int fileNameLength = fileName.length();

        for (int i = 0; i < fileNameLength; i++) {
            char c = fileName.charAt(i);

            if (c == '\\') {
                fileNameBuf.append("/");
            } else {
                fileNameBuf.append(c);
            }
        }
    } else {
        fileNameBuf = new StringBuilder(testFile.getAbsolutePath());
    }

    Properties props = new Properties();
    props.put("useCompression", "true");
    Connection conn1 = getConnectionWithProps(props);
    Statement stmt1 = conn1.createStatement();

    int updateCount = stmt1.executeUpdate("LOAD DATA LOCAL INFILE '" + fileNameBuf.toString() + "' INTO TABLE testBug11237 CHARACTER SET "
            + CharsetMapping.getMysqlCharsetForJavaEncoding(((MySQLConnection) this.conn).getEncoding(), (com.mysql.jdbc.Connection) conn1));

    assertTrue(updateCount == loops);

}
 
Example 17
Project: jmeter-wssecurity   File: TestWSSDecryptionPostProcessor.java   View Source Code Vote up 4 votes
@BeforeClass
public static void setUpClass() throws IOException {
    File propsFile = File.createTempFile("jmeter-wssecurity-test-", ".properties");
    propsFile.deleteOnExit();
    JMeterUtils.loadJMeterProperties(propsFile.getAbsolutePath());
}
 
Example 18
Project: jermit   File: Xmodem12.java   View Source Code Vote up 4 votes
/**
 * Run the test.
 */
@Override
public void doTest() throws IOException, TestFailedException {
    System.out.printf("Xmodem12: NOISY ASCII file upload\n");

    // Process:
    //
    //   1. Extract jermit/tests/data/ALICE26A_NO_EOT.TXT to
    //      a temp file.
    //   2. Spawn 'rx /path/to/temp'
    //   3. Spin up XmodemSender to send /path/to/ALICE26A_NO_EOT.TXT.
    //   4. Read both files and compare contents.

    File source = File.createTempFile("send-xmodem", ".txt");
    saveResourceToFile("jermit/tests/data/ALICE26A_NO_EOT.TXT", source);
    source.deleteOnExit();

    File destination = File.createTempFile("receive-xmodem", ".txt");
    destination.deleteOnExit();

    ProcessBuilder rxb = new ProcessBuilder("rx", destination.getPath());
    Process rx = rxb.start();

    // Allow overwrite of destination file, because we just created it.
    XmodemSender sx = new XmodemSender(XmodemSession.Flavor.VANILLA,
        new NoisyInputStream(rx.getInputStream()),
        new NoisyOutputStream(rx.getOutputStream()),
        source.getPath());

    sx.run();

    // Wait for rx to finish before comparing files!
    for (;;) {
        try {
            if (rx.waitFor() == 0) {
                break;
            }
        } catch (InterruptedException e) {
            // SQUASH
        }
    }

    if (!compareFilesAscii(source, destination)) {
        throw new TestFailedException("Files are not the same");
    }

}
 
Example 19
Project: monarch   File: DiskRegionPerfJUnitPerformanceTest.java   View Source Code Vote up 4 votes
@Test
public void testpersistASyncWithBuffer5() {
  try {
    // Create four Dirs for Disk Dirs
    File file1 = new File("testpersistASyncWithBuffer5Dir1");
    file1.mkdir();
    file1.deleteOnExit();
    File file2 = new File("testpersistASyncWithBuffer5Dir2");
    file2.mkdir();
    file2.deleteOnExit();
    File file3 = new File("testpersistASyncWithBuffer5Dir3");
    file3.mkdir();
    file3.deleteOnExit();
    File file4 = new File("testpersistASyncWithBuffer5Dir4");
    file4.mkdir();
    file4.deleteOnExit();
    dirs = new File[4];
    dirs[0] = file1;
    dirs[1] = file2;
    dirs[2] = file3;
    dirs[3] = file4;

    diskProps.setTimeInterval(15000l);
    diskProps.setBytesThreshold(10000l);
    region = DiskRegionHelperFactory.getAsyncPersistOnlyRegion(cache, diskProps);
  } catch (Exception e) {
    e.printStackTrace();
    fail("failed in testpersistASyncWithBuffer5");
  }
  // Perf test for 1kb writes
  populateData();
  System.out.println("PersistASyncWithBuffer5:: Stats for 1 kb writes :" + stats);
  // Perf test for 1kb writes. Puting values on the same KEY
  // populateDataPutOnSameKey();
  // System.out.println("OverflowASyncWithBuffer5:: Stats for 1 kb writes :"+
  // stats_ForSameKeyputs);
  // Deleting all the files and logs created during the test...
  deleteFiles();
  // closeDown();

}
 
Example 20
Project: apache-maven-shade-plugin   File: ServiceResourceTransformerTest.java   View Source Code Vote up 4 votes
@Test
public void relocatedClasses() throws Exception {
    SimpleRelocator relocator =
        new SimpleRelocator( "org.foo", "borg.foo", null, Arrays.asList( "org.foo.exclude.*" ) );
    List<Relocator> relocators = Lists.<Relocator>newArrayList( relocator );

    String content = "org.foo.Service\norg.foo.exclude.OtherService\n";
    byte[] contentBytes = content.getBytes( "UTF-8" );
    InputStream contentStream = new ByteArrayInputStream( contentBytes );
    String contentResource = "META-INF/services/org.foo.something.another";
    String contentResourceShaded = "META-INF/services/borg.foo.something.another";

    ServicesResourceTransformer xformer = new ServicesResourceTransformer();
    xformer.processResource( contentResource, contentStream, relocators );
    contentStream.close();

    File tempJar = File.createTempFile("shade.", ".jar");
    tempJar.deleteOnExit();
    FileOutputStream fos = new FileOutputStream( tempJar );
    JarOutputStream jos = new JarOutputStream( fos );
    try {
        xformer.modifyOutputStream( jos, false );
        jos.close();
        jos = null;
        JarFile jarFile = new JarFile( tempJar );
        JarEntry jarEntry = jarFile.getJarEntry( contentResourceShaded );
        assertNotNull( jarEntry );
        InputStream entryStream = jarFile.getInputStream( jarEntry );
        try {
            String xformedContent = IOUtils.toString( entryStream, "utf-8" );
            assertEquals( "borg.foo.Service" + System.getProperty( "line.separator" )
                + "org.foo.exclude.OtherService" + System.getProperty( "line.separator" ), xformedContent );
        } finally {
            IOUtils.closeQuietly( entryStream );
            jarFile.close();
        }
    } finally {
        if (jos != null)
        {
            IOUtils.closeQuietly( jos );
        }
        tempJar.delete();
    }
}