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:org.craftercms.commons.mongo.MongoScriptRunner.java

private void runScriptsWithMongoClient() {
    List<String> toExecute = new ArrayList<>();

    try {/*from ww w. j  a  v a2  s . c o m*/
        for (Resource scriptPath : scriptPaths) {
            if (scriptPath.getFile().isDirectory()) {
                Files.walkFileTree(scriptPath.getFile().toPath(), new JSFileVisitor(toExecute));
            } else {
                toExecute.add(scriptPath.getFile().getAbsolutePath());
            }
        }
        final Path allScripsFile = Files.createTempFile("ScriptRunner", ".js");
        StringBuilder builder = new StringBuilder();
        for (String path : toExecute) {
            builder.append(String.format("load('%s');\n", path));
        }
        FileUtils.writeStringToFile(allScripsFile.toFile(), builder.toString(), "UTF-8");
        runScript(allScripsFile);
        Files.deleteIfExists(allScripsFile);
    } catch (IOException | MongoDataException ex) {
        logger.error("Unable to run script using MongoClient", ex);
    }
}

From source file:org.digidoc4j.main.DigiDoc4JTest.java

@Test
public void createsContainerWithSignatureProfileIsTSAForBDoc() throws Exception {
    String fileName = "test1.bdoc";
    Files.deleteIfExists(Paths.get(fileName));

    String[] params = new String[] { "-in", fileName, "-type", "BDOC", "-add", "testFiles/test.txt",
            "text/plain", "-pkcs12", "testFiles/signout.p12", "test", "-profile", "LTA" };

    callMainWithoutSystemExit(params);/* w w w .  j  av  a2  s .  c  o m*/

    Container container = ContainerOpener.open(fileName);
    assertEquals(SignatureProfile.LTA, container.getSignature(0).getProfile());
}

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

private void deleteTempFiles(final File newFile, final FileStoreMapper map) throws IOException {
    Files.deleteIfExists(newFile.toPath());
    Path storePath = Paths.get(System.getProperty("user.home") + File.separator + "testfilestore");
    Files.deleteIfExists(Paths.get(storePath.toString(), map.getFileStoreId().toString()));
}

From source file:com.arpnetworking.metrics.impl.TsdLogSinkTest.java

@Test
public void testSerialization() throws IOException, InterruptedException {
    final File actualFile = new File("./target/TsdLogSinkTest/testSerialization-Query.log");
    Files.deleteIfExists(actualFile.toPath());
    final Sink sink = new TsdLogSink.Builder().setDirectory(createDirectory("./target/TsdLogSinkTest"))
            .setName("testSerialization-Query").setImmediateFlush(Boolean.TRUE).build();

    final Map<String, String> annotations = new LinkedHashMap<>(ANNOTATIONS);
    annotations.put("foo", "bar");
    sink.record(new TsdEvent(annotations, TEST_SERIALIZATION_TIMERS, TEST_SERIALIZATION_COUNTERS,
            TEST_SERIALIZATION_GAUGES));

    // TODO(vkoskela): Add protected option to disable async [MAI-181].
    Thread.sleep(100);// w ww . j  av  a2  s.c o  m

    final String actualOriginalJson = fileToString(actualFile);
    assertMatchesJsonSchema(actualOriginalJson);
    final String actualComparableJson = actualOriginalJson
            .replaceAll("\"_host\":\"[^\"]*\"", "\"_host\":\"<HOST>\"")
            .replaceAll("\"_id\":\"[^\"]*\"", "\"_id\":\"<ID>\"");
    final JsonNode actual = OBJECT_MAPPER.readTree(actualComparableJson);
    final JsonNode expected = OBJECT_MAPPER.readTree(EXPECTED_METRICS_JSON);

    Assert.assertEquals("expectedJson=" + OBJECT_MAPPER.writeValueAsString(expected) + " vs actualJson="
            + OBJECT_MAPPER.writeValueAsString(actual), expected, actual);
}

From source file:org.codice.ddf.admin.insecure.defaults.service.DefaultUsersDeletionScheduler.java

public static boolean removeDefaultUsers() {
    try {/*from  www .ja  v  a2s  . c  om*/
        Bundle bundle = FrameworkUtil.getBundle(DefaultUsersDeletionScheduler.class);
        if (bundle != null) {
            BundleContext bundleContext = bundle.getBundleContext();
            Collection<ServiceReference<BackingEngineFactory>> implementers = bundleContext
                    .getServiceReferences(BackingEngineFactory.class, null);
            for (ServiceReference<BackingEngineFactory> impl : implementers) {

                BackingEngineFactory backingEngineFactory = bundleContext.getService(impl);
                BackingEngine backingEngine = backingEngineFactory
                        .build(ImmutableMap.of("users", getUsersPropertiesFilePath().toString()));

                if (!backingEngine.listUsers().isEmpty()) {
                    backingEngine.listUsers().forEach(user -> backingEngine.deleteUser(user.getName()));
                }
            }
        }

        LOGGER.debug("Default users have been deleted successfully.");

        Files.deleteIfExists(getTempTimestampFilePath());
        return true;
    } catch (Exception e) {
        LOGGER.debug("Unable to remove default users.", e);
        return false;
    }
}

From source file:org.sakuli.datamodel.helper.TestSuiteHelperTest.java

@Test
public void testNotModifyFiles() throws Exception {
    Path path = Paths.get("temp-testsuite.suite");
    try {/*from ww  w. jav a  2s . co  m*/
        String source = "line1\r\nbla\r\n";
        FileUtils.writeStringToFile(path.toFile(), source);
        FileTime beforeTimeStamp = Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS);
        Thread.sleep(1100);

        String result = TestSuiteHelper.prepareTestSuiteFile(path);
        assertEquals(source, result);
        FileTime afterTimeStamp = Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS);
        assertEquals(beforeTimeStamp, afterTimeStamp);
    } finally {
        Files.deleteIfExists(path);
    }
}

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

@Test
public void testGetEnabledJobsByType() 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,TEST3";

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

    String filename1 = jobNameFromPath(path1);

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

    Map<String, Properties> jobs = getEnabledJobsByType(dir, "TEST1");

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

    Files.deleteIfExists(path1);
    Files.deleteIfExists(path2);/*from w  w  w. j a  v a 2  s.c om*/
}

From source file:org.wte4j.examples.showcase.server.hsql.ShowCaseDbInitializerTest.java

private void deleteDirectory(Path path) throws IOException {

    Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
        @Override/*from w  w w. ja v  a 2 s .c o  m*/
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Files.deleteIfExists(file);
            return super.visitFile(file, attrs);
        }
    });
    Files.deleteIfExists(path);

}

From source file:com.arpnetworking.test.junitbenchmarks.JsonBenchmarkConsumerTest.java

@Test
public void testMultipleClose() throws IOException {
    final Path path = Paths.get("target/tmp/test/testConsumerMultiClose.json");
    path.toFile().deleteOnExit();//from   ww  w .  jav a 2  s. c om
    Files.deleteIfExists(path);
    final JsonBenchmarkConsumer consumer = new JsonBenchmarkConsumer(path);

    final Result result = DataCreator.createResult();
    consumer.accept(result);
    consumer.close();
    // Should not throw an exception
    consumer.close();
}

From source file:com.relicum.ipsum.io.PropertyIO.java

/**
 * Write the properties object to the specified string file path.
 *
 * @param properties an instance of a {@link java.util.Properties} object.
 * @param path       the  {@link java.nio.file.Path} that the properties will be written to.
 * @param message    the message that is included in the header of properties files.
 * @throws IOException an {@link java.io.IOException} if their was a problem writing to the file.
 *///from  w  ww .j  a v a 2  s . c om
default void writeToFile(Properties properties, Path path, String message) throws IOException {
    Validate.notNull(properties);
    Validate.notNull(path);
    Validate.notNull(message);
    System.out.println(path);

    Files.deleteIfExists(path);

    try {

        properties.store(Files.newBufferedWriter(path, Charset.defaultCharset()), message);
    } catch (IOException e) {
        Logger.getGlobal().log(Level.SEVERE, e.getMessage(), e.getCause());
        throw e;
    }

}