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.metrics.generator.util.TestFileGenerator.java

/**
 * Generates the test file.//from w w  w  .  j  av  a  2  s.c o m
 */
public void generate() {
    try {
        Files.deleteIfExists(_fileName);
    } catch (final IOException e) {
        throw Throwables.propagate(e);
    }

    final long totalSampleCount = ((long) _uowCount) * _namesCount * _samplesCount;
    LOGGER.info().setEvent("GeneratingFile").setMessage("Starting file generation")
            .addData("file", _fileName.toAbsolutePath()).addData("expectedSamples", totalSampleCount).log();

    final Duration duration = new Duration(_startTime, _endTime);

    final List<MetricGenerator> metricGenerators = Lists.newArrayList();
    for (int x = 0; x < _namesCount; ++x) {
        final GaussianMetricGenerator gaussian = new GaussianMetricGenerator(50d, 8d,
                new SingleNameGenerator(_random));
        final ConstantCountMetricGenerator sampleGenerator = new ConstantCountMetricGenerator(_samplesCount,
                gaussian);
        metricGenerators.add(sampleGenerator);
    }
    final UnitOfWorkGenerator uowGenerator = new UnitOfWorkGenerator(metricGenerators);

    final List<UnitOfWorkSchedule> schedules = Lists.newArrayList();
    final long durationInNanos = TimeUnit.NANOSECONDS.convert(duration.getMillis(), TimeUnit.MILLISECONDS);
    final long periodInNanos = durationInNanos / _uowCount;
    schedules.add(new UnitOfWorkSchedule(uowGenerator, new ConstantTimeScheduler(periodInNanos)));

    final MetricGenerator canary = new ConstantMetricGenerator(5, new SpecifiedName(CANARY));

    // Special canary unit of work schedulers
    // Each UOW generator is guaranteed to be executed once
    final UnitOfWorkGenerator canaryUOW = new UnitOfWorkGenerator(Collections.singletonList(canary));
    schedules
            .add(new UnitOfWorkSchedule(canaryUOW, new ConstantTimeScheduler(durationInNanos + periodInNanos)));

    final IntervalExecutor executor = new IntervalExecutor(_startTime, _endTime, schedules, _fileName,
            _clusterName, _serviceName);
    executor.execute();
    try {
        final BasicFileAttributes attributes = Files.readAttributes(_fileName, BasicFileAttributes.class);
        LOGGER.info().setEvent("GenerationComplete").setMessage("Generation completed successfully")
                .addData("size", attributes.size()).log();
    } catch (final IOException e) {
        LOGGER.warn().setEvent("GenerationComplete")
                .setMessage("Generation completed successfully but unable to read attributes of generated file")
                .setThrowable(e).log();
    }
}

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

public void deleteArchive() throws IOException {
    Files.deleteIfExists(archivePath);
}

From source file:com.vaushell.superpipes.transforms.done.T_DoneTest.java

/**
 * Test duplicate./*from   ww  w.j  a  va 2  s .  c o m*/
 *
 * @throws java.lang.Exception
 */
@Test
public void testDuplicate() throws Exception {
    final A_Node n = dispatcher.addNode("dummy", N_Dummy.class, ConfigProperties.EMPTY_COMMONS);
    final A_Transform t = n.addTransformIN(T_Done.class, ConfigProperties.EMPTY_COMMONS);

    final Path p = dispatcher.getDatas().resolve(Paths.get(n.getNodeID(), "done.dat"));

    Files.deleteIfExists(p);

    // Prepare
    n.prepare();

    // Transform
    final Message mLearn = Message.create(Message.KeyIndex.TITLE, "mon titre", Message.KeyIndex.DESCRIPTION,
            "ma description");
    final Message mLearn2 = Message.create(Message.KeyIndex.TITLE, "mon titre2", Message.KeyIndex.DESCRIPTION,
            "ma description2");

    assertNotNull("Message is learned", t.transform(mLearn));
    assertNotNull("Message 2 is learned", t.transform(mLearn2));

    assertNull("Message is not duplicated", t.transform(mLearn));
    assertNull("Message 2 is not duplicated", t.transform(mLearn2));

    // Terminate
    n.terminate();
}

From source file:net.javacrumbs.codecamp.boot.common.CsvFileLogger.java

@Override
public void clear() {
    try {//from ww w. ja  v a  2  s.c o m
        Files.deleteIfExists(file.toPath());
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.eclipse.che.api.fs.server.impl.ZipArchiver.java

void unzip(Path fsPath, InputStream content, boolean overwrite, boolean withParents, boolean skipRoot)
        throws ServerException {
    try {//w w w  .  j a va 2  s  .co  m
        if (withParents) {
            Files.createDirectories(fsPath);
        }

        try (ZipInputStream zis = new ZipInputStream(content)) {
            ZipEntry zipEntry = zis.getNextEntry();

            String prefixToSkip = null;
            if (zipEntry.isDirectory() && skipRoot) {
                prefixToSkip = zipEntry.getName();
                zipEntry = zis.getNextEntry();
            }

            while (zipEntry != null) {
                String name = prefixToSkip != null ? zipEntry.getName().replaceFirst(prefixToSkip, "")
                        : zipEntry.getName();
                Path path = fsPath.resolve(name);

                if (overwrite) {
                    Files.deleteIfExists(path);
                }
                if (zipEntry.isDirectory()) {
                    Files.createDirectory(path);
                } else {
                    try (FileOutputStream fos = new FileOutputStream(path.toFile())) {
                        IOUtils.copy(zis, fos);
                    }
                }

                zipEntry = zis.getNextEntry();
            }
        }
    } catch (IOException e) {
        throw new ServerException("Failed to unzip item " + fsPath, e);
    }
}

From source file:it.infn.ct.futuregateway.apiserver.storage.LocalStorage.java

@Override
public final void storeFile(final RESOURCE res, final String id, final InputStream input,
        final String destinationName, final String operation) throws IOException {

    Path filePath;// ww w.j  a  v  a  2  s. c  o  m
    if (operation != null && !operation.isEmpty()) {
        filePath = Paths.get(path, res.name().toLowerCase(), id, operation, destinationName);
    } else {
        filePath = Paths.get(path, res.name().toLowerCase(), id, destinationName);
    }

    Files.createDirectories(filePath.getParent());
    Files.deleteIfExists(filePath);
    Files.copy(input, filePath);
    log.debug("File " + destinationName + " written at '" + filePath + "'");
}

From source file:org.forgerock.openidm.maintenance.upgrade.StaticFileUpdateTest.java

@AfterMethod
public void deleteTempFile() throws IOException {
    Files.deleteIfExists(tempFile.resolveSibling(getNewVersionPath(tempFile)));
    Files.deleteIfExists(tempFile.resolveSibling(getOldVersionPath(tempFile)));
    Files.delete(tempFile);//from   w  ww  . ja  v  a 2  s.c  o m
}

From source file:stroom.headless.TestHeadless.java

@Ignore
public void test() throws Exception {
    String newTempDir = null;//from   w w  w . j  av a2s .  c  o m

    try {
        // Let tests update the database
        //            StroomProperties.setOverrideProperty("stroom.jpaHbm2DdlAuto", "update", "test");
        //            StroomProperties.setOverrideProperty("stroom.connectionTesterClassName",
        //                    "stroom.entity.server.util.StroomConnectionTesterOkOnException", "test");

        newTempDir = FileUtil.getTempDir().getCanonicalPath() + File.separator + "headless";
        StroomProperties.setOverrideProperty("stroom.temp", newTempDir, StroomProperties.Source.TEST);

        // Make sure the new temp directory is empty.
        final File tmpDir = new File(newTempDir);
        if (tmpDir.isDirectory()) {
            FileUtils.deleteDirectory(tmpDir);
        }

        final String dir = StroomProcessTestFileUtil.getTestResourcesDir().getCanonicalPath() + File.separator
                + "TestHeadless";

        final String inputDirPath = dir + File.separator + "input";
        final String outputDirPath = dir + File.separator + "output";
        new File(inputDirPath).mkdir();
        new File(outputDirPath).mkdir();

        final String configFilePath = dir + File.separator + "config.zip";
        final String configUnzippedDirPath = dir + File.separator + "configUnzipped";
        final String inputFilePath = inputDirPath + File.separator + "001.zip";
        final String inputUnzippedDirPath = dir + File.separator + "inputUnzipped";
        final String outputFilePath = outputDirPath + File.separator + "output";
        final String expectedOutputFilePath = dir + File.separator + "expectedOutput";

        // Clear out any files from previous runs
        Files.deleteIfExists(new File(inputFilePath).toPath());
        Files.deleteIfExists(new File(configFilePath).toPath());

        // build the input zip file from the source files
        // the zip files created are transient and are ignored by git. They
        // are left in place to make it
        // easier to see the actual file when debugging the test
        final File inputZipFile = new File(inputFilePath);
        ZipUtil.zip(inputZipFile, new File(inputUnzippedDirPath));

        // build the config zip file from the source files
        // the zip files created are transient and are ignored by git. They
        // are left in place to make it
        // easier to see the actual file when debugging the test
        final File configZipFile = new File(configFilePath);
        ZipUtil.zip(configZipFile, new File(configUnzippedDirPath));

        final Headless headless = new Headless();

        headless.setConfig(configFilePath);
        headless.setInput(inputDirPath);
        headless.setOutput(outputFilePath);
        headless.setTmp(newTempDir);
        headless.run();

        final List<String> expectedLines = Files.readAllLines(new File(expectedOutputFilePath).toPath(),
                Charset.defaultCharset());
        final List<String> outputLines = Files.readAllLines(new File(outputFilePath).toPath(),
                Charset.defaultCharset());

        // same number of lines output as expected
        Assert.assertEquals(expectedLines.size(), outputLines.size());

        // make sure all lines are present in both
        Assert.assertEquals(new HashSet<String>(expectedLines), new HashSet<String>(outputLines));

        // content should exactly match expected file
        ComparisonHelper.compareFiles(new File(expectedOutputFilePath), new File(outputFilePath));

    } finally {
        StroomProperties.removeOverrides();
    }
}

From source file:ch.ledcom.jpreseed.UsbCreatorTest.java

@Before
@After
public void deleteNewBootImg() throws IOException {
    Files.deleteIfExists(NEW_IMAGE);
}

From source file:org.openlmis.fulfillment.service.OrderFileStorage.java

@Override
public void delete(Order order) {
    try {//  ww w. ja v  a 2  s.co  m
        Files.deleteIfExists(getOrderAsPath(order));
    } catch (IOException exp) {
        throw new OrderStorageException(exp, ERROR_IO, exp.getMessage());
    }
}