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.arpnetworking.test.junitbenchmarks.JsonBenchmarkConsumerTest.java

@Test
public void testNormalBenchmarkCase() throws IOException {
    final Path path = Paths.get("target/tmp/test/testConsumer.json");
    path.toFile().deleteOnExit();//from  www  .jav a2s . co  m
    Files.deleteIfExists(path);
    final JsonBenchmarkConsumer consumer = new JsonBenchmarkConsumer(path);

    final Result result = DataCreator.createResult();
    consumer.accept(result);
    consumer.close();

    // Read the file back in as json
    final ObjectMapper mapper = ObjectMapperFactory.getInstance();
    final JsonNode resultsArray = mapper.readTree(path.toFile());
    Assert.assertEquals(1, resultsArray.size());
    final JsonNode augmentedResultNode = resultsArray.get(0);
    Assert.assertTrue(augmentedResultNode.isObject());
    final JsonNode resultNode = augmentedResultNode.get("result");
    Assert.assertTrue(resultNode.isObject());

    Assert.assertEquals("com.arpnetworking.test.junitbenchmarks.JsonBenchmarkConsumerTest",
            resultNode.get("testClassName").asText());
    Assert.assertEquals("testNormalBenchmarkCase", resultNode.get("testMethodName").asText());

    Assert.assertEquals(result.benchmarkRounds, resultNode.get("benchmarkRounds").asInt());
    Assert.assertEquals(result.warmupRounds, resultNode.get("warmupRounds").asInt());
    Assert.assertEquals(result.warmupTime, resultNode.get("warmupTime").asInt());
    Assert.assertEquals(result.benchmarkTime, resultNode.get("benchmarkTime").asInt());

    Assert.assertTrue(resultNode.get("roundAverage").isObject());
    final ObjectNode roundAverageNode = (ObjectNode) resultNode.get("roundAverage");
    Assert.assertEquals(result.roundAverage.avg, roundAverageNode.get("avg").asDouble(), 0.0001d);
    Assert.assertEquals(result.roundAverage.stddev, roundAverageNode.get("stddev").asDouble(), 0.0001d);

    Assert.assertTrue(resultNode.get("blockedAverage").isObject());
    final ObjectNode blockedAverageNode = (ObjectNode) resultNode.get("blockedAverage");
    Assert.assertEquals(result.blockedAverage.avg, blockedAverageNode.get("avg").asDouble(), 0.0001d);
    Assert.assertEquals(result.blockedAverage.stddev, blockedAverageNode.get("stddev").asDouble(), 0.0001d);

    Assert.assertTrue(resultNode.get("gcAverage").isObject());
    final ObjectNode gcAverageNode = (ObjectNode) resultNode.get("gcAverage");
    Assert.assertEquals(result.gcAverage.avg, gcAverageNode.get("avg").asDouble(), 0.0001d);
    Assert.assertEquals(result.gcAverage.stddev, gcAverageNode.get("stddev").asDouble(), 0.0001d);

    Assert.assertTrue(resultNode.get("gcInfo").isObject());
    final ObjectNode gcInfoNode = (ObjectNode) resultNode.get("gcInfo");
    Assert.assertEquals(result.gcInfo.accumulatedInvocations(),
            gcInfoNode.get("accumulatedInvocations").asInt());
    Assert.assertEquals(result.gcInfo.accumulatedTime(), gcInfoNode.get("accumulatedTime").asInt());

    Assert.assertEquals(result.getThreadCount(), resultNode.get("threadCount").asInt());
}

From source file:ubicrypt.core.TestUtils.java

public static void deleteR(final Path path) {
    try {//w w  w . java  2s . c  o m
        if (!Files.isDirectory(path)) {
            Files.deleteIfExists(path);
            return;
        }
        Files.list(path).forEach(TestUtils::deleteR);
        Files.deleteIfExists(path);
    } catch (final IOException e) {
        Throwables.propagate(e);
    }
}

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

@BeforeMethod
public void setUp() throws Exception {
    if (this.getClass().getResource(CACHEFILE_NAME) != null) {
        Files.deleteIfExists(getResource(CACHEFILE_NAME));
    }//from  w ww. j  a  v  a  2  s .  c  o m
}

From source file:org.wso2.appcloud.esb.fileupdater.FileUpdaterServiceComponent.java

protected void activate(ComponentContext ctx) {
    String carbonHome = System.getenv("CARBON_HOME_PATH");

    if (carbonHome != null) {
        String folderPath = carbonHome + "/repository/deployment/server/eventpublishers/";
        String configPublisher = "MessageFlowConfigurationPublisher.xml";
        String statsPublisher = "MessageFlowStatisticsPublisher.xml";

        File configurationPublisher = new File(folderPath + configPublisher);
        try {//from   w  w  w  .j  av a  2 s .  c  o m
            Files.deleteIfExists(configurationPublisher.toPath());
            log.info("MessageFlowConfigurationPublisher.xml successfully removed");
        } catch (IOException e) {
            log.error("Error occurred while removing MessageFlowConfigurationPublisher.xml", e);
        }
        File statisticsPublisher = new File(folderPath + statsPublisher);
        try {
            Files.deleteIfExists(statisticsPublisher.toPath());
            log.info("MessageFlowStatisticsPublisher.xml successfully removed");
        } catch (IOException e) {
            log.error("Error occurred while removing MessageFlowStatisticsPublisher.xml", e);
        }
    } else {
        log.warn("CARBON_HOME_PATH environment variable is not set. Therefore, not updating files");
    }
}

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

@AfterClass
public static void tearDown() throws IOException {
    Files.deleteIfExists(manifestFile.toPath());
}

From source file:org.apache.bookkeeper.statelib.impl.rocksdb.checkpoint.RocksCheckpointer.java

public static CheckpointMetadata restore(String dbName, File dbPath, CheckpointStore checkpointStore)
        throws StateStoreException {
    try {//from ww w. j a  va2 s  .  com
        String dbPrefix = String.format("%s", dbName);

        Pair<String, CheckpointMetadata> latestCheckpoint = getLatestCheckpoint(dbPrefix, checkpointStore);
        File checkpointsDir = new File(dbPath, "checkpoints");
        String checkpointId = latestCheckpoint.getLeft();
        CheckpointMetadata checkpointMetadata = latestCheckpoint.getRight();
        if (checkpointId != null) {
            RocksdbRestoreTask task = new RocksdbRestoreTask(dbName, checkpointsDir, checkpointStore);
            task.restore(checkpointId, checkpointMetadata);
        } else {
            // no checkpoints available, create an empty directory
            checkpointId = UUID.randomUUID().toString();
            Files.createDirectories(Paths.get(checkpointsDir.getAbsolutePath(), checkpointId));
        }
        Path restoredCheckpointPath = Paths.get(checkpointsDir.getAbsolutePath(), checkpointId);
        log.info("Successfully restore checkpoint {} to {}", checkpointId, restoredCheckpointPath);

        File currentDir = new File(dbPath, "current");
        Files.deleteIfExists(Paths.get(currentDir.getAbsolutePath()));
        Files.createSymbolicLink(Paths.get(currentDir.getAbsolutePath()), restoredCheckpointPath);

        // after successfully restore from remote checkpoints, cleanup other unused checkpoints
        cleanupLocalCheckpoints(checkpointsDir, checkpointId);

        return checkpointMetadata;
    } catch (IOException ioe) {
        log.error("Failed to restore rocksdb {}", dbName, ioe);
        throw new StateStoreException("Failed to restore rocksdb " + dbName, ioe);
    }
}

From source file:com.arpnetworking.configuration.jackson.JsonNodeDirectorySourceTest.java

@Test
public void testDirectoryNotDirectory() throws IOException {
    final File directory = new File(
            "./target/tmp/filter/JsonNodeDirectorySourceTest/testDirectoryNotDirectory");
    Files.deleteIfExists(directory.toPath());
    Files.createFile(directory.toPath());
    final JsonNodeDirectorySource source = new JsonNodeDirectorySource.Builder().setDirectory(directory)
            .build();/* w w  w .  j av a  2s  .c  o  m*/
    Assert.assertFalse(source.getJsonNode().isPresent());
}

From source file:sadl.utils.IoUtils.java

public static void deleteFiles(Path[] paths) throws IOException {
    for (final Path p : paths) {
        if (!Files.deleteIfExists(p)) {
            logger.warn("{} should have been explicitly deleted, but did not exist.", p);
        }/*from ww w  .j ava  2 s  . c  o m*/
    }
}

From source file:org.apache.mnemonic.service.computing.DurableSinglyLinkedListNGPrintTest.java

@BeforeClass
public void setUp() throws IOException {
    m_rand = Utils.createRandom();/*www.  j  a v a  2  s. c  o m*/
    Files.deleteIfExists(Paths.get(uri));
    m_act = new NonVolatileMemAllocator(Utils.getNonVolatileMemoryAllocatorService("pmalloc"),
            1024 * 1024 * 1024, uri, true);
    cKEYCAPACITY = m_act.handlerCapacity();
    for (long i = 0; i < cKEYCAPACITY; ++i) {
        m_act.setHandler(i, 0L);
    }
}

From source file:at.tfr.securefs.ws.FileServiceBean.java

@MTOM(enabled = true, threshold = 10240)
@WebMethod/*  w  w w.  j a  va2  s  .  c o  m*/
@Override
public void write(@WebParam(name = "relativePath") String relPath, @WebParam(name = "bytes") byte[] b)
        throws IOException {

    log.debug("write File: " + relPath);
    try {
        String tmpFileName = Paths.get(relPath).getFileName().toString() + System.currentTimeMillis();
        Path tmpPath = Files.createFile(configuration.getTmpPath().resolve(tmpFileName));
        try {
            try (OutputStream os = Files.newOutputStream(tmpPath)) {
                IOUtils.write(b, os);
            }
            preProcessor.preProcess(tmpPath);
            log.debug("preprocessed File: " + relPath);
        } finally {
            Files.deleteIfExists(tmpPath);
        }
    } catch (ModuleException me) {
        String message = "preProcessing of relPath failed: " + me.getMessage();
        if (log.isDebugEnabled()) {
            log.debug(message, me);
        }
        log.info(message);
        throw new IOException(message);
    }

    Path path = SecureFileSystemBean.resolvePath(relPath, configuration.getBasePath(),
            configuration.isRestrictedToBasePath());
    log.debug("write File: " + relPath + " to " + path);
    Path parent = path.getParent();
    Files.createDirectories(parent); // create parent directories unconditionally
    OutputStream encrypter = crypterProvider.getEncrypter(path);
    try {
        IOUtils.copyLarge(new ByteArrayInputStream(b), encrypter);
    } finally {
        encrypter.close();
    }
    logInfo("written File: " + path, null);
}