Java Code Examples for java.io.File#createTempFile()

The following examples show how to use java.io.File#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: ScanDirConfigTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test of getXmlConfigString method, of class com.sun.jmx.examples.scandir.ScanDirConfig.
 */
public void testGetXmlConfigString() throws Exception {
    System.out.println("getXmlConfigString");

    try {
        final File file = File.createTempFile("testconf",".xml");
        final ScanDirConfig instance = new ScanDirConfig(file.getAbsolutePath());
        final ScanManagerConfig bean =
            new  ScanManagerConfig("testGetXmlConfigString");
        final DirectoryScannerConfig dir =
            new DirectoryScannerConfig("tmp");
        dir.setRootDirectory(file.getParent());
        bean.putScan(dir);
        instance.setConfiguration(bean);
        System.out.println("Expected: " + XmlConfigUtils.toString(bean));
        System.out.println("Received: " +
                instance.getConfiguration().toString());
        assertEquals(XmlConfigUtils.toString(bean),
            instance.getConfiguration().toString());
    } catch (Exception x) {
        x.printStackTrace();
        throw x;
    }
}
 
Example 2
Source File: BandStructure.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
static OutputStream getDumpStream(String name, int seq, String ext, Object b) throws IOException {
    if (dumpDir == null) {
        dumpDir = File.createTempFile("BD_", "", new File("."));
        dumpDir.delete();
        if (dumpDir.mkdir())
            Utils.log.info("Dumping bands to "+dumpDir);
    }
    name = name.replace('(', ' ').replace(')', ' ');
    name = name.replace('/', ' ');
    name = name.replace('*', ' ');
    name = name.trim().replace(' ','_');
    name = ((10000+seq) + "_" + name).substring(1);
    File dumpFile = new File(dumpDir, name+ext);
    Utils.log.info("Dumping "+b+" to "+dumpFile);
    return new BufferedOutputStream(new FileOutputStream(dumpFile));
}
 
Example 3
Source File: TestFilterOpNumeric.java    From spork with Apache License 2.0 6 votes vote down vote up
@Test
public void testNestedBinCond() throws Throwable {
    File tmpFile = File.createTempFile("test", "txt");
    PrintStream ps = new PrintStream(new FileOutputStream(tmpFile));
    for(int i = 0; i < LOOP_COUNT; i++) {
        ps.println(i + "\t" + i + "\t1");
    }
    ps.close();
    pig.registerQuery("A=load '"
            + Util.encodeEscape(Util.generateURI(tmpFile.toString(), pig.getPigContext())) + "';");
    String query = "A = foreach A generate (($0 < 10 or $0 < 9)?(($1 >= 5 and $1 >= 4) ? 2: 1) : 0);";
    log.info(query);
    pig.registerQuery(query);
    Iterator<Tuple> it = pig.openIterator("A");
    tmpFile.delete();
    int count =0;
    while(it.hasNext()) {
        Tuple t = it.next();
        Integer first = (Integer)t.get(0);
        count+=first;
        assertTrue(first == 1 || first == 2 || first == 0);

    }
    assertEquals("expected count of 15", 15, count);
}
 
Example 4
Source File: RouterServerSSLTest.java    From ambry with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void initializeTests() throws Exception {
  File trustStoreFile = File.createTempFile("truststore", ".jks");
  String sslEnabledDataCentersStr = "DC1,DC2,DC3";
  Properties serverSSLProps = new Properties();
  TestSSLUtils.addSSLProperties(serverSSLProps, sslEnabledDataCentersStr, SSLFactory.Mode.SERVER, trustStoreFile,
      "server");
  TestSSLUtils.addHttp2Properties(serverSSLProps, SSLFactory.Mode.SERVER, true);
  Properties routerProps = getRouterProperties("DC1");
  TestSSLUtils.addSSLProperties(routerProps, sslEnabledDataCentersStr, SSLFactory.Mode.CLIENT, trustStoreFile,
      "router-client");
  sslCluster = new MockCluster(serverSSLProps, false, SystemTime.getInstance());
  MockNotificationSystem notificationSystem = new MockNotificationSystem(sslCluster.getClusterMap());
  sslCluster.initializeServers(notificationSystem);
  sslCluster.startServers();
  MockClusterMap routerClusterMap = sslCluster.getClusterMap();
  // MockClusterMap returns a new registry by default. This is to ensure that each node (server, router and so on,
  // get a different registry. But at this point all server nodes have been initialized, and we want the router and
  // its components, which are going to be created, to use the same registry.
  routerClusterMap.createAndSetPermanentMetricRegistry();
  testFramework = new RouterServerTestFramework(routerProps, routerClusterMap, notificationSystem);
  routerMetricRegistry = routerClusterMap.getMetricRegistry();
}
 
Example 5
Source File: GogsWebHookTest.java    From gogs-webhook-plugin with MIT License 6 votes vote down vote up
@Test
public void whenUriDoesNotContainUrlNameMustReturnError() throws Exception {
    //Prepare the SUT
    File uniqueFile = File.createTempFile("webHookTest_", ".txt", new File("target"));

    StaplerRequest staplerRequest = Mockito.mock(RequestImpl.class);
    StaplerResponse staplerResponse = Mockito.mock(ResponseImpl.class);
    when(staplerRequest.getHeader("X-Gogs-Event")).thenReturn("push");
    when(staplerRequest.getQueryString()).thenReturn("job=myJob");


    MockServletInputStream inputStream = new MockServletInputStream("body");
    when(staplerRequest.getInputStream()).thenReturn(inputStream);
    when(staplerRequest.getRequestURI()).thenReturn("/badUri/aaa");

    //perform the testÃŽ
    performDoIndexTest(staplerRequest, staplerResponse, uniqueFile);

    //validate that everything was done as planed
    verify(staplerResponse).setStatus(404);

    String expectedOutput = "No payload or URI contains invalid entries.";
    isExpectedOutput(uniqueFile, expectedOutput);

    log.info("Test succeeded.");
}
 
Example 6
Source File: SubbufferLongLong.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
static void setUp() throws Exception {
    testarray = new float[1024];
    for (int i = 0; i < 1024; i++) {
        double ii = i / 1024.0;
        ii = ii * ii;
        testarray[i] = (float)Math.sin(10*ii*2*Math.PI);
        testarray[i] += (float)Math.sin(1.731 + 2*ii*2*Math.PI);
        testarray[i] += (float)Math.sin(0.231 + 6.3*ii*2*Math.PI);
        testarray[i] *= 0.3;
    }
    test_byte_array = new byte[testarray.length*2];
    AudioFloatConverter.getConverter(format).toByteArray(testarray, test_byte_array);
    test_file = File.createTempFile("test", ".raw");
    try (FileOutputStream fos = new FileOutputStream(test_file)) {
        fos.write(test_byte_array);
    }
}
 
Example 7
Source File: NullArgs.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        for (int i = 0;; i++) {
            try {
                switch (i) {
                case 0:  new File((String)null);  break;
                case 1:  new File((String)null, null);  break;
                case 2:  new File((File)null, null);  break;
                case 3:  File.createTempFile(null, null, null);  break;
                case 4:  File.createTempFile(null, null);  break;
                case 5:  new File("foo").compareTo(null);  break;
                case 6:  new File("foo").renameTo(null);  break;
                default:
                    System.err.println();
                    return;
                }
            } catch (NullPointerException x) {
                System.err.print(i + " ");
                continue;
            }
            throw new Exception("NullPointerException not thrown (case " +
                                i + ")");
        }

    }
 
Example 8
Source File: PosixTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testPreadBytes() throws Exception{
  final String testString = "hello, world!";
  byte[] bytesToWrite = testString.getBytes("UTF-8");
  ByteBuffer buf = ByteBuffer.allocate(bytesToWrite.length);

  File tmpFile = File.createTempFile("preadbug-", ".tmp");
  tmpFile.deleteOnExit();

  try (
      FileOutputStream fos = new FileOutputStream(tmpFile)) {
    fos.write(bytesToWrite);
  }

  try (
      RandomAccessFile raf = new RandomAccessFile(tmpFile, "r");
      FileChannel channel = raf.getChannel()) {
    channel.read(buf, 0);
  }

  String dstString = new String(buf.array(), "UTF-8");
  assertEquals(testString, dstString);
}
 
Example 9
Source File: P12SecretKey.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private void run(String keystoreType) throws Exception {
    char[] pw = "password".toCharArray();
    KeyStore ks = KeyStore.getInstance(keystoreType);
    ks.load(null, pw);

    KeyGenerator kg = KeyGenerator.getInstance("AES");
    kg.init(128);
    SecretKey key = kg.generateKey();

    KeyStore.SecretKeyEntry ske = new KeyStore.SecretKeyEntry(key);
    KeyStore.ProtectionParameter kspp = new KeyStore.PasswordProtection(pw);
    ks.setEntry(ALIAS, ske, kspp);

    File ksFile = File.createTempFile("test", ".test");
    try (FileOutputStream fos = new FileOutputStream(ksFile)) {
        ks.store(fos, pw);
        fos.flush();
    }

    // now see if we can get it back
    try (FileInputStream fis = new FileInputStream(ksFile)) {
        KeyStore ks2 = KeyStore.getInstance(keystoreType);
        ks2.load(fis, pw);
        KeyStore.Entry entry = ks2.getEntry(ALIAS, kspp);
        SecretKey keyIn = ((KeyStore.SecretKeyEntry)entry).getSecretKey();
        if (Arrays.equals(key.getEncoded(), keyIn.getEncoded())) {
            System.err.println("OK: worked just fine with " + keystoreType +
                               " keystore");
        } else {
            System.err.println("ERROR: keys are NOT equal after storing in "
                               + keystoreType + " keystore");
        }
    }
}
 
Example 10
Source File: RandomAccessFileOutputStreamTest.java    From archive-patcher with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws IOException {
  testData = new byte[128];
  for (int x = 0; x < 128; x++) {
    testData[x] = (byte) x;
  }
  tempFile = File.createTempFile("ra-fost", "tmp");
  tempFile.deleteOnExit();
}
 
Example 11
Source File: S3OutputStream.java    From incubator-tajo with Apache License 2.0 5 votes vote down vote up
private File newBackupFile() throws IOException {
  File dir = new File(conf.get("fs.s3.buffer.dir"));
  if (!dir.exists() && !dir.mkdirs()) {
    throw new IOException("Cannot create S3 buffer directory: " + dir);
  }
  File result = File.createTempFile("output-", ".tmp", dir);
  result.deleteOnExit();
  return result;
}
 
Example 12
Source File: TestStore.java    From lsmtree with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
    tmpDir = File.createTempFile("tmp", "", new File("."));
    tmpDir.delete();
    tmpDir.mkdirs();
    String treeSizeStr = System.getProperty("lsmtree.test.size");
    treeSize = "large".equals(treeSizeStr) ? LARGE_TREE_SIZE : SMALL_TREE_SIZE;
}
 
Example 13
Source File: EarAssemblerTest.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
public void testEarAssemblyToTempDir() throws Exception {
    AssemblerConfig config = new AssemblerConfig();
    config.setSource( earFile );
    File assembledEar = File.createTempFile( earFile.getName(), ".ear" ); 
    config.setDestination( assembledEar );
    EarAssembler assembler = new EarAssembler();
    assembler.assemble( config );
    validateEarAssembly( assembledEar );
    assembledEar.delete();
}
 
Example 14
Source File: IOExtTest.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadLines() throws Exception {
    File file = File.createTempFile("junit", ".txt", new File("build"));
    try (Writer fwr = new FileWriter(file)) {
        fwr.write("line1\n");
        fwr.write("line2");
    }

    List<String> lines = IOExt.readLines(file);
    assertThat(lines).containsExactly("line1", "line2");
}
 
Example 15
Source File: StratumChainTest.java    From java-stratum with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws IOException {
    File file = File.createTempFile("stratum-chain", ".chain");
    client = createMock(StratumClient.class);
    expect(client.getHeadersQueue()).andStubReturn(null);
    params = NetworkParameters.fromID(NetworkParameters.ID_UNITTESTNET);
    //new CheckpointManager(params, new ByteArrayInputStream("TXT CHECKPOINTS 1\n0\n0\n".getBytes("UTF-8")))
    store = new HeadersStore(params, file, null, null);
    chain = new StratumChain(params, store, client);
}
 
Example 16
Source File: LogServiceApplication.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    ConfigurableApplicationContext context =
            SpringApplication.run(LogServiceApplication.class, args);

    LogService logsService = context.getBean(LogService.class);
    FileService fileService = context.getBean(FileService.class);

    File tempFile = File.createTempFile("LogServiceApplication", ".tmp");
    tempFile.deleteOnExit();

    fileService.writeTo(tempFile.getAbsolutePath(), logsService.stream());

    RatpackServer.start(server ->
            server.handlers(chain ->
                    chain.all(ctx -> {

                        Publisher<String> logs = logsService.stream();

                        ServerSentEvents events = serverSentEvents(
                                logs,
                                event -> event.id(Objects::toString)
                                              .event("log")
                                              .data(Function.identity())
                        );

                        ctx.render(events);
                    })
            )
    );
}
 
Example 17
Source File: StorageManagerTest.java    From ambry with Apache License 2.0 4 votes vote down vote up
/**
 * Test add new BlobStore with given {@link ReplicaId}.
 */
@Test
public void addBlobStoreTest() throws Exception {
  generateConfigs(true, false);
  MockDataNodeId localNode = clusterMap.getDataNodes().get(0);
  List<ReplicaId> localReplicas = clusterMap.getReplicaIds(localNode);
  int newMountPathIndex = 3;
  // add new MountPath to local node
  File f = File.createTempFile("ambry", ".tmp");
  File mountFile =
      new File(f.getParent(), "mountpathfile" + MockClusterMap.PLAIN_TEXT_PORT_START_NUMBER + newMountPathIndex);
  MockClusterMap.deleteFileOrDirectory(mountFile);
  assertTrue("Couldn't create mount path directory", mountFile.mkdir());
  localNode.addMountPaths(Collections.singletonList(mountFile.getAbsolutePath()));
  PartitionId newPartition1 =
      new MockPartitionId(10L, MockClusterMap.DEFAULT_PARTITION_CLASS, clusterMap.getDataNodes(), newMountPathIndex);
  StorageManager storageManager = createStorageManager(localNode, metricRegistry, null);
  storageManager.start();
  // test add store that already exists, which should fail
  assertFalse("Add store which is already existing should fail", storageManager.addBlobStore(localReplicas.get(0)));
  // test add store onto a new disk, which should succeed
  assertTrue("Add new store should succeed", storageManager.addBlobStore(newPartition1.getReplicaIds().get(0)));
  assertNotNull("The store shouldn't be null because new store is successfully added",
      storageManager.getStore(newPartition1, false));
  // test add store whose diskManager is not running, which should fail
  PartitionId newPartition2 =
      new MockPartitionId(11L, MockClusterMap.DEFAULT_PARTITION_CLASS, clusterMap.getDataNodes(), 0);
  storageManager.getDiskManager(localReplicas.get(0).getPartitionId()).shutdown();
  assertFalse("Add store onto the DiskManager which is not running should fail",
      storageManager.addBlobStore(newPartition2.getReplicaIds().get(0)));
  storageManager.getDiskManager(localReplicas.get(0).getPartitionId()).start();
  // test replica addition can correctly handle existing dir (should delete it and create a new one)
  // To verify the directory has been recreated, we purposely put a test file in previous dir.
  PartitionId newPartition3 =
      new MockPartitionId(12L, MockClusterMap.DEFAULT_PARTITION_CLASS, clusterMap.getDataNodes(), 0);
  ReplicaId replicaToAdd = newPartition3.getReplicaIds().get(0);
  File previousDir = new File(replicaToAdd.getReplicaPath());
  File testFile = new File(previousDir, "testFile");
  MockClusterMap.deleteFileOrDirectory(previousDir);
  assertTrue("Cannot create dir for " + replicaToAdd.getReplicaPath(), previousDir.mkdir());
  assertTrue("Cannot create test file within previous dir", testFile.createNewFile());
  assertTrue("Adding new store should succeed", storageManager.addBlobStore(replicaToAdd));
  assertFalse("Test file should not exist", testFile.exists());
  assertNotNull("Store associated new added replica should not be null",
      storageManager.getStore(newPartition3, false));
  shutdownAndAssertStoresInaccessible(storageManager, localReplicas);
  // test add store but fail to add segment requirements to DiskSpaceAllocator. (This is simulated by inducing
  // addRequiredSegments failure to make store inaccessible)
  List<String> mountPaths = localNode.getMountPaths();
  String diskToFail = mountPaths.get(0);
  File reservePoolDir = new File(diskToFail, diskManagerConfig.diskManagerReserveFileDirName);
  File storeReserveDir = new File(reservePoolDir, DiskSpaceAllocator.STORE_DIR_PREFIX + newPartition2.toString());
  StorageManager storageManager2 = createStorageManager(localNode, new MetricRegistry(), null);
  storageManager2.start();
  Utils.deleteFileOrDirectory(storeReserveDir);
  assertTrue("File creation should succeed", storeReserveDir.createNewFile());

  assertFalse("Add store should fail if store couldn't start due to initializePool failure",
      storageManager2.addBlobStore(newPartition2.getReplicaIds().get(0)));
  assertNull("New store shouldn't be in in-memory data structure", storageManager2.getStore(newPartition2, false));
  shutdownAndAssertStoresInaccessible(storageManager2, localReplicas);
}
 
Example 18
Source File: MergeBamAlignmentTest.java    From picard with MIT License 4 votes vote down vote up
@Test
public void testShortFragmentHardClipping() throws IOException {
    final File output = File.createTempFile("testShortFragmentClipping", ".sam");
    output.deleteOnExit();
    final File alignedSam = new File(TEST_DATA_DIR, "hardclip.aligned.sam");
    final File unmappedSam = new File(TEST_DATA_DIR, "hardclip.unmapped.sam");
    final File ref = new File(TEST_DATA_DIR, "cliptest.fasta");

    final List<String> args = Arrays.asList(
            "UNMAPPED_BAM=" + unmappedSam.getAbsolutePath(),
            "ALIGNED_BAM=" + alignedSam.getAbsolutePath(),
            "OUTPUT=" + output.getAbsolutePath(),
            "REFERENCE_SEQUENCE=" + ref.getAbsolutePath(),
            "HARD_CLIP_OVERLAPPING_READS=true"
            );

    Assert.assertEquals(runPicardCommandLine(args), 0);

    final SamReader result = SamReaderFactory.makeDefault().open(output);
    final Map<String, SAMRecord> firstReadEncountered = new HashMap<String, SAMRecord>();
    for (final SAMRecord rec : result) {
        final SAMRecord otherEnd = firstReadEncountered.get(rec.getReadName());
        if (otherEnd == null) {
            firstReadEncountered.put(rec.getReadName(), rec);
        } else {
            final int fragmentStart = Math.min(rec.getAlignmentStart(), otherEnd.getAlignmentStart());
            final int fragmentEnd = Math.max(rec.getAlignmentEnd(), otherEnd.getAlignmentEnd());
            final String[] readNameFields = rec.getReadName().split(":");
            // Read name of each pair includes the expected fragment start and fragment end positions.
            final int expectedFragmentStart = Integer.parseInt(readNameFields[1]);
            final int expectedFragmentEnd = Integer.parseInt(readNameFields[2]);
            Assert.assertEquals(fragmentStart, expectedFragmentStart, rec.getReadName());
            Assert.assertEquals(fragmentEnd, expectedFragmentEnd, rec.getReadName());
            if (readNameFields[0].equals("FR_clip")) {
                Assert.assertEquals(rec.getCigarString(), rec.getReadNegativeStrandFlag()? "20H56M" : "56M20H");
                Assert.assertEquals(otherEnd.getCigarString(), otherEnd.getReadNegativeStrandFlag()? "20H56M" : "56M20H");

                if (!rec.getReadNegativeStrandFlag()) {
                    Assert.assertEquals(rec.getAttribute("XB"), "AGATCGGAAGAGCACACGTC");
                    Assert.assertEquals(rec.getAttribute("XQ"), "BBBBB?BBB?<?A?<7<<=9");
                } else {
                    Assert.assertEquals(rec.getAttribute("XB"), "AGATCGGAAGAGCGTCGTGT");
                    Assert.assertEquals(rec.getAttribute("XQ"), "BCFD=@CBBADCF=CC:CCD");
                }
            } else {
                Assert.assertEquals(rec.getCigarString(), "76M");
                Assert.assertEquals(otherEnd.getCigarString(), "76M");
            }
        }
    }
}
 
Example 19
Source File: IptcAddTest.java    From commons-imaging with Apache License 2.0 4 votes vote down vote up
@ParameterizedTest
@MethodSource("data")
public void testAddIptcData(File imageFile) throws Exception {
    final ByteSource byteSource = new ByteSourceFile(imageFile);

    final Map<String, Object> params = new HashMap<>();
    final boolean ignoreImageData = isPhilHarveyTestImage(imageFile);
    params.put(ImagingConstants.PARAM_KEY_READ_THUMBNAILS, Boolean.valueOf(!ignoreImageData));

    final JpegPhotoshopMetadata metadata = new JpegImageParser().getPhotoshopMetadata(byteSource, params);
    if (metadata == null) {
        // FIXME select only files with meta for this test
        return;
    }

    final List<IptcBlock> newBlocks = new ArrayList<>(metadata.photoshopApp13Data.getNonIptcBlocks());
    final List<IptcRecord> oldRecords = metadata.photoshopApp13Data.getRecords();

    final List<IptcRecord> newRecords = new ArrayList<>();
    for (final IptcRecord record : oldRecords) {
        if (record.iptcType != IptcTypes.CITY
                && record.iptcType != IptcTypes.CREDIT) {
            newRecords.add(record);
        }
    }

    newRecords.add(new IptcRecord(IptcTypes.CITY, "Albany, NY"));
    newRecords.add(new IptcRecord(IptcTypes.CREDIT, "William Sorensen"));

    final PhotoshopApp13Data newData = new PhotoshopApp13Data(newRecords, newBlocks);

    final File updated = File.createTempFile(imageFile.getName() + ".iptc.add.", ".jpg");
    try (FileOutputStream fos = new FileOutputStream(updated);
            OutputStream os = new BufferedOutputStream(fos)) {
        new JpegIptcRewriter().writeIPTC(byteSource, os, newData);
    }

    final ByteSource updateByteSource = new ByteSourceFile(updated);
    final JpegPhotoshopMetadata outMetadata = new JpegImageParser().getPhotoshopMetadata(
            updateByteSource, params);

    assertNotNull(outMetadata);
    assertTrue(outMetadata.getItems().size() == newRecords.size());
}
 
Example 20
Source File: ZipUtilITCase.java    From olat with Apache License 2.0 2 votes vote down vote up
/**
 * creates and deletes file, just for purpose of getting an temporary file name.
 * 
 * @param prefix
 * @return
 * @throws IOException
 */
private File getTempFileName(String prefix) throws IOException {
    File tempFile = File.createTempFile(prefix, "output");
    delete(tempFile);
    return tempFile;
}