Example usage for java.nio.file Files deleteIfExists

List of usage examples for java.nio.file Files deleteIfExists

Introduction

In this page you can find the example usage for java.nio.file Files deleteIfExists.

Prototype

public static boolean deleteIfExists(Path path) throws IOException 

Source Link

Document

Deletes a file if it exists.

Usage

From source file:com.surevine.gateway.scm.gatewayclient.GatewayPackage.java

public void createArchive() throws IOException, ArchiveException, CompressorException {
    if (!archiveWritten) {
        String uuid = UUID.randomUUID().toString();
        archivePath = Paths.get(PropertyUtil.getTempDir(), uuid + ".tar.gz");
        Path metadataPath = Paths.get(PropertyUtil.getTempDir(), ".metadata.json");
        Path tarPath = Paths.get(PropertyUtil.getTempDir(), uuid + ".tar");

        writeMetadata(metadataPath);/*from  www  . ja  va  2s.  c  o m*/
        createTar(tarPath, metadataPath, bundlePath);
        writeGZ(archivePath, tarPath);

        // remove everything except the tar.gz
        Files.deleteIfExists(metadataPath);
        Files.deleteIfExists(tarPath);
        Files.deleteIfExists(bundlePath);

        archiveWritten = true;
    }
}

From source file:ch.ledcom.jpreseed.web.TemporaryPreseedStore.java

@Override
public void close() {
    deletePreseeds();//from  www  . ja  va2  s  .c  o  m
    try {
        logger.debug("Deleting temp dir [{}].", tempDir);
        Files.deleteIfExists(tempDir);
    } catch (IOException ioe) {
        logger.error("Could not delete temp dir [{}].", tempDir, ioe);
    }
}

From source file:org.ballerinalang.test.auth.ConfigAuthProviderTest.java

@BeforeClass
public void setup() throws Exception {
    resourceRoot = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getPath())
            .getAbsolutePath();//from  www.ja v  a 2s.  c o m
    Path sourceRoot = Paths.get(resourceRoot, "test-src", "auth");
    Path ballerinaConfPath = Paths.get(resourceRoot, "datafiles", "config", "auth", "configauthprovider",
            BALLERINA_CONF);

    compileResult = BCompileUtil.compile(sourceRoot.resolve("config_auth_provider_test.bal").toString());

    Path secretFilePath = Paths.get(resourceRoot, "datafiles", "config", secretFile);
    secretCopyPath = Paths.get(resourceRoot, "datafiles", "config", "auth", "configauthprovider", secretFile);
    Files.deleteIfExists(secretCopyPath);
    copySecretFile(secretFilePath.toString(), secretCopyPath.toString());

    // load configs
    ConfigRegistry registry = ConfigRegistry.getInstance();
    registry.initRegistry(Collections.singletonMap("b7a.config.secret", secretCopyPath.toString()),
            ballerinaConfPath.toString(), null);
}

From source file:org.sakuli.services.common.CacheHandlingResultServiceImplTest.java

@Test
public void testWriteCachedStepDefinitions() throws Exception {
    final String cacheFilePath = "valid/validTestCase/" + TestCaseStepHelper.STEPS_CACHE_FILE;
    if (this.getClass().getResource(cacheFilePath) != null) {
        Files.deleteIfExists(getResource(cacheFilePath, true));
    }/*from  w w w .  ja  va2s. c om*/

    Path tcFile = getResource("valid/validTestCase/_tc.js", true);
    testSuite.setState(TestSuiteState.ERRORS);
    TestCase tc = new TestCase("test", "test");
    tc.setTcFile(tcFile);
    tc.setSteps(Arrays.asList(new TestCaseStepBuilder("step_ok").withState(TestCaseStepState.OK).build(),
            new TestCaseStepBuilder("step_not_started").build(),
            new TestCaseStepBuilder("step_warning").withState(TestCaseStepState.WARNING).build()));
    testSuite.setTestCases(Collections.singletonMap("1", tc));

    //on error no cache file should be written
    testling.saveAllResults();
    assertNull(getResource(cacheFilePath, false));

    //on != error cache file should be written
    testSuite.setState(TestSuiteState.CRITICAL_IN_SUITE);
    testling.saveAllResults();
    Path cacheFile = getResource(cacheFilePath, true);
    assertTrue(Files.exists(cacheFile));
    assertEquals(FileUtils.readFileToString(cacheFile.toFile(), Charset.forName("UTF-8")),
            "step_ok\nstep_warning\n");
}

From source file:org.egov.infra.filestore.service.impl.LocalDiskFileStoreServiceTest.java

@AfterClass
public static void afterTest() throws IOException {
    Files.deleteIfExists(tempFilePath);
    Path storePath = Paths.get(System.getProperty("user.home") + File.separator + "testfilestore");
    try {/*from w  w  w .  j a  v  a 2  s . c  o m*/
        Files.walkFileTree(storePath, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                if (exc == null) {
                    Files.delete(dir);
                    return FileVisitResult.CONTINUE;
                } else {
                    throw exc;
                }
            }

        });
    } catch (IOException e) {

    }
}

From source file:org.ulyssis.ipp.publisher.FileOutput.java

@Override
public void outputScore(Score score) {
    Path tmpFile = null;//from  www.ja v a 2  s. c o  m
    try {
        if (tmpDir.isPresent()) {
            tmpFile = Files.createTempFile(tmpDir.get(), "score-", ".json",
                    PosixFilePermissions.asFileAttribute(defaultPerms));
        } else {
            tmpFile = Files.createTempFile("score-", ".json",
                    PosixFilePermissions.asFileAttribute(defaultPerms));
        }
        BufferedWriter writer = Files.newBufferedWriter(tmpFile, StandardCharsets.UTF_8);
        Serialization.getJsonMapper().writer(new DefaultPrettyPrinter()).writeValue(writer, score);
        Files.move(tmpFile, filePath, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        LOG.error("Error writing score to file!", e);
    } finally {
        try {
            if (tmpFile != null)
                Files.deleteIfExists(tmpFile);
        } catch (IOException ignored) {
        }
    }
}

From source file:com.spectralogic.ds3client.helpers.FileObjectPutter_Test.java

/**
 * This test cannot run on Windows without extra privileges
 *///  ww  w. j  a  va 2s. c  o  m
@Test
public void testSymlink() throws IOException {
    assumeFalse(Platform.isWindows());
    final Path tempDir = Files.createTempDirectory("ds3_file_object_putter_");
    final Path tempPath = Files.createTempFile(tempDir, "temp_", ".txt");

    try {
        try (final SeekableByteChannel channel = Files.newByteChannel(tempPath, StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
            channel.write(ByteBuffer.wrap(testData));
        }

        final Path symLinkPath = tempDir.resolve("sym_" + tempPath.getFileName().toString());
        Files.createSymbolicLink(symLinkPath, tempPath);

        getFileWithPutter(tempDir, symLinkPath);
    } finally {
        Files.deleteIfExists(tempPath);
        Files.deleteIfExists(tempDir);
    }
}

From source file:org.kitodo.dataeditor.MetsKitodoWriterTest.java

@Test
public void shouldWriteMetsFile()
        throws TransformerException, JAXBException, IOException, DatatypeConfigurationException {
    URI xmlFile = Paths.get("./src/test/resources/testmeta.xml").toUri();

    URI xmlTestFile = Paths.get(System.getProperty("user.dir") + "/target/test-classes/newtestmeta.xml")
            .toUri();/*  w w  w.  j  a v  a2s . c  om*/

    MetsKitodoWrapper metsKitodoWrapper = new MetsKitodoWrapper(xmlFile, xsltFile);
    metsKitodoWriter.writeSerializedToFile(metsKitodoWrapper.getMets(), xmlTestFile);
    MetsKitodoWrapper savedMetsKitodoWrapper = new MetsKitodoWrapper(xmlTestFile, xsltFile);
    Files.deleteIfExists(Paths.get(xmlTestFile));

    String loadedMetadata = metsKitodoWrapper.getDmdSecs().get(0).getKitodoType().getMetadata().get(0)
            .getValue();
    String savedMetadata = metsKitodoWrapper.getDmdSecs().get(0).getKitodoType().getMetadata().get(0)
            .getValue();

    Assert.assertEquals("The metadata of the loaded and the saved mets file are not equal", loadedMetadata,
            savedMetadata);
    Assert.assertEquals("The number of dmdSec elements of the loaded and the saved mets file are not equal",
            metsKitodoWrapper.getDmdSecs().size(), savedMetsKitodoWrapper.getDmdSecs().size());

    Assert.assertEquals("Lastmoddate of Mets header was wrong",
            savedMetsKitodoWrapper.getMets().getMetsHdr().getLASTMODDATE().getHour(),
            new DateTime().getHourOfDay());

    String result = metsKitodoWriter.writeSerializedToString(metsKitodoWrapper.getMets());

    Assert.assertTrue("Prefix mapping for kitodo namespace is wrong", result.contains("kitodo:metadata"));
    Assert.assertTrue("Prefix mapping for mets namespace is wrong", result.contains("mets:dmdSec"));
}

From source file:wherehows.common.utils.JobsUtilTest.java

@Test
public void testGetScheduledJobs() throws IOException, ConfigurationException {
    String propertyStr1 = "job.class=test\n" + "job.cron.expr=0 0 1 * * ? *\n" + "#job.disabled=1\n"
            + "job.type=TEST1";
    String propertyStr2 = "job.class=test\n" + "job.cron.expr=0 0 1 * * ? *\n" + "job.disabled=1\n"
            + "job.type=TEST2";
    String propertyStr3 = "job.class=test\n" + "#job.disabled=1\n" + "job.type=TEST3";

    Path path1 = createPropertiesFile(propertyStr1);
    Path path2 = createPropertiesFile(propertyStr2);
    Path path3 = createPropertiesFile(propertyStr3);

    String filename1 = jobNameFromPath(path1);

    String dir = path1.getParent().toString();

    Map<String, Properties> jobs = getScheduledJobs(dir);

    Assert.assertEquals(jobs.size(), 1);
    Assert.assertEquals(jobs.get(filename1).getProperty(Constant.JOB_TYPE_KEY), "TEST1");
    Assert.assertEquals(jobs.get(filename1).getProperty("job.class"), "test");

    Files.deleteIfExists(path1);
    Files.deleteIfExists(path2);//from   w w  w  .  j  a va  2 s .com
    Files.deleteIfExists(path3);
}

From source file:org.eclipse.winery.yaml.common.Utils.java

public static void deleteTmpDir(Path path) {
    try {/*from ww w .j  a  v  a  2 s.co  m*/
        Files.deleteIfExists(tmpBase);
    } catch (Exception e) {
        e.printStackTrace();
    }
}