Example usage for java.nio.file Files delete

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

Introduction

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

Prototype

public static void delete(Path path) throws IOException 

Source Link

Document

Deletes a file.

Usage

From source file:fr.pilato.elasticsearch.crawler.fs.test.integration.FsCrawlerImplAllParametersIT.java

@Test
public void test_remove_deleted_disabled() throws Exception {
    Fs fs = startCrawlerDefinition().setRemoveDeleted(false).build();
    startCrawler(getCrawlerName(), fs, endCrawlerDefinition(getCrawlerName()), null);

    // We should have two docs first
    countTestHelper(getCrawlerName(), null, 2, currentTestResourceDir);

    // We remove a file
    logger.info(" ---> Removing file deleted_roottxtfile.txt");
    Files.delete(currentTestResourceDir.resolve("deleted_roottxtfile.txt"));

    // We expect to have two files
    countTestHelper(getCrawlerName(), null, 2, currentTestResourceDir);
}

From source file:org.apache.nifi.controller.TemplateManager.java

/**
 * Removes the template with the given ID.
 *
 * @param id the ID of the template to remove
 * @throws NullPointerException if the argument is null
 * @throws IllegalStateException if no template exists with the given ID
 * @throws IOException if template could not be removed
 *///from   w w  w  .  ja  va 2  s. c o m
public void removeTemplate(final String id) throws IOException, IllegalStateException {
    writeLock.lock();
    try {
        final Template removed = templateMap.remove(requireNonNull(id));

        // ensure the template exists
        if (removed == null) {
            throw new IllegalStateException("No template with ID " + id + " exists");
        } else {

            try {
                // remove the template from the archive directory
                final Path path = directory.resolve(removed.getDetails().getId() + ".template");
                Files.delete(path);
            } catch (final NoSuchFileException e) {
                logger.warn(String.format(
                        "Template file for template %s not found when attempting to remove. Continuing...",
                        id));
            } catch (final IOException e) {
                logger.error(String.format("Unable to remove template file for template %s.", id));

                // since the template file existed and we were unable to remove it, rollback
                // by returning it to the template map
                templateMap.put(id, removed);

                // rethrow
                throw e;
            }
        }
    } finally {
        writeLock.unlock();
    }
}

From source file:fr.gael.dhus.sync.impl.ODataProductSynchronizer.java

/** Downloads a product. */
private void downloadProduct(Product p) throws IOException, InterruptedException {
    // Creates a client producer that produces HTTP Basic auth aware clients
    HttpAsyncClientProducer cliprod = new HttpAsyncClientProducer() {
        @Override//from  www .  ja v  a  2s  .c  o  m
        public CloseableHttpAsyncClient generateClient() {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(AuthScope.ANY),
                    new UsernamePasswordCredentials(serviceUser, servicePass));
            CloseableHttpAsyncClient res = HttpAsyncClients.custom()
                    .setDefaultCredentialsProvider(credsProvider).build();
            res.start();
            return res;
        }
    };

    // Asks the Incoming manager for a download path
    Path dir = Paths.get(INCOMING_MANAGER.getNewIncomingPath().toURI());
    Path tmp_pd = dir.resolve(p.getIdentifier() + ".part"); // Temporary names
    Path tmp_ql = dir.resolve(p.getIdentifier() + "-ql.part");
    Path tmp_tn = dir.resolve(p.getIdentifier() + "-tn.part");
    // These files will be moved once download is complete

    InterruptibleHttpClient http_client = new InterruptibleHttpClient(cliprod);
    DownloadResult pd_res = null, ql_res = null, tn_res = null;
    try {
        long delta = System.currentTimeMillis();
        pd_res = downloadValidateRename(http_client, tmp_pd, p.getOrigin());
        logODataPerf(p.getOrigin(), System.currentTimeMillis() - delta);

        // Sets download info in the product (not written in the db here)
        p.setPath(pd_res.data.toUri().toURL());
        p.setDownloadablePath(pd_res.data.toString());
        p.setDownloadableType(pd_res.dataType);
        p.setDownloadableSize(pd_res.dataSize);

        // Downloads and sets the quicklook and thumbnail (if any)
        if (p.getQuicklookFlag()) {
            // Failing at downloading a quicklook must not abort the download!
            try {
                ql_res = downloadValidateRename(http_client, tmp_ql, p.getQuicklookPath());
                p.setQuicklookPath(ql_res.data.toString());
                p.setQuicklookSize(ql_res.dataSize);
            } catch (IOException ex) {
                LOGGER.error("Failed to download quicklook at " + p.getQuicklookPath(), ex);
            }
        }
        if (p.getThumbnailFlag()) {
            // Failing at downloading a thumbnail must not abort the download!
            try {
                tn_res = downloadValidateRename(http_client, tmp_tn, p.getThumbnailPath());
                p.setThumbnailPath(tn_res.data.toString());
                p.setThumbnailSize(tn_res.dataSize);
            } catch (IOException ex) {
                LOGGER.error("Failed to download thumbnail at " + p.getThumbnailPath(), ex);
            }
        }
    } catch (Exception ex) {
        // Removes downloaded files if an error occured
        if (pd_res != null) {
            Files.delete(pd_res.data);
        }
        if (ql_res != null) {
            Files.delete(ql_res.data);
        }
        if (tn_res != null) {
            Files.delete(tn_res.data);
        }
        throw ex;
    }
}

From source file:com.upplication.s3fs.util.AmazonS3ClientMock.java

@Override
public void deleteObject(String bucketName, String key) throws AmazonClientException {
    Path bucket = find(bucketName);
    Path resolve = bucket.resolve(key);
    if (Files.exists(resolve))
        try {/* w w  w .  j av  a 2  s .c  om*/
            Files.delete(resolve);
        } catch (IOException e) {
            throw new AmazonServiceException("Problem deleting mock object: ", e);
        }
    else {
        resolve = bucket.resolve(key.replaceAll("/", "%2F"));
        if (Files.exists(resolve))
            try {
                Files.delete(resolve);
            } catch (IOException e) {
                throw new AmazonServiceException("Problem deleting mock object: ", e);
            }
    }
}

From source file:io.lavagna.web.api.CardDataController.java

@ExpectPermission(Permission.CREATE_FILE)
@RequestMapping(value = "/api/card/{cardId}/file", method = RequestMethod.POST)
@ResponseBody// w ww .j  a v a2  s.co m
public List<String> uploadFiles(@PathVariable("cardId") int cardId,
        @RequestParam("files") List<MultipartFile> files, User user, HttpServletResponse resp)
        throws IOException {

    LOG.debug("Files uploaded: {}", files.size());

    if (!ensureFileSize(files)) {
        resp.setStatus(422);
        return Collections.emptyList();
    }

    List<String> digests = new ArrayList<>();
    for (MultipartFile file : files) {
        Path p = Files.createTempFile("lavagna", "upload");
        try (InputStream fileIs = file.getInputStream()) {
            Files.copy(fileIs, p, StandardCopyOption.REPLACE_EXISTING);
            String digest = DigestUtils.sha256Hex(Files.newInputStream(p));
            String contentType = file.getContentType() != null ? file.getContentType()
                    : "application/octet-stream";
            boolean result = cardDataService.createFile(file.getOriginalFilename(), digest, file.getSize(),
                    cardId, Files.newInputStream(p), contentType, user, new Date()).getLeft();
            if (result) {
                LOG.debug("file uploaded! size: {}, original name: {}, content-type: {}", file.getSize(),
                        file.getOriginalFilename(), file.getContentType());
                digests.add(digest);
            }
        } finally {
            Files.delete(p);
            LOG.debug("deleted temp file {}", p);
        }
    }
    eventEmitter.emitUploadFile(cardRepository.findBy(cardId).getColumnId(), cardId);
    return digests;
}

From source file:org.codice.ddf.platform.migratable.impl.PlatformMigratableTest.java

/** Verifies that when an optional file is missing the version upgrade import still succeeds. */
@Test/* w  ww .jav a 2  s .c o  m*/
public void testDoVersionUpgradeImportOptionalFileNotExported() throws IOException {
    // Setup export
    Path exportDir = tempDir.getRoot().toPath().toRealPath();

    // Delete etc/users.properties. This file is optional, so it will not generate
    // an error during export.
    Files.delete(ddfHome.resolve("etc").resolve("users.properties").toRealPath());
    List<Path> optionalFilesExported = OPTIONAL_SYSTEM_FILES.stream()
            .filter(p -> !p.equals(Paths.get("etc", "users.properties"))).collect(Collectors.toList());

    doExport(exportDir);

    // Setup import
    setup(DDF_IMPORTED_HOME, DDF_IMPORTED_TAG, IMPORTING_PRODUCT_VERSION);

    PlatformMigratable iPlatformMigratable = spy(new PlatformMigratable());
    when(iPlatformMigratable.getVersion()).thenReturn("3.0");
    List<Migratable> iMigratables = Arrays.asList(iPlatformMigratable);
    ConfigurationMigrationManager iConfigurationMigrationManager = new ConfigurationMigrationManager(
            iMigratables, systemService);

    MigrationReport importReport = iConfigurationMigrationManager.doImport(exportDir, this::print);

    // Verify import
    assertThat("The import report has errors.", importReport.hasErrors(), is(false));
    assertThat("The import report has warnings.", importReport.hasWarnings(), is(false));
    assertThat("Import was not successful.", importReport.wasSuccessful(), is(true));
    verifyKeystoresImported();
    verifyServiceWrapperImported();
}

From source file:org.roda.core.storage.AbstractStorageServiceTest.java

@Test(enabled = false)
protected void testBinaryContent(Binary binary, ContentPayload providedPayload)
        throws IOException, GenericException {
    // check if content is the same
    assertTrue(IOUtils.contentEquals(providedPayload.createInputStream(),
            binary.getContent().createInputStream()));

    Path tempFile = Files.createTempFile("test", ".tmp");
    Files.copy(binary.getContent().createInputStream(), tempFile, StandardCopyOption.REPLACE_EXISTING);

    // check size in bytes
    assertEquals(Long.valueOf(Files.size(tempFile)), binary.getSizeInBytes());

    if (binary.getContentDigest() != null) {
        for (Entry<String, String> entry : binary.getContentDigest().entrySet()) {
            String digest = FSUtils.computeContentDigest(tempFile, entry.getKey());
            assertEquals(digest, entry.getValue());
        }//w  ww  .  j  ava  2  s  .c  o  m
    }

    // delete temp file
    Files.delete(tempFile);
}

From source file:org.codice.ddf.security.migratable.impl.SecurityMigratableTest.java

/** Verifies that when no PDP file exists, the version upgrade import succeeds. */
@Test/*from  w w  w  .j a va  2  s .  c  o  m*/
public void testDoVersionUpgradeImportWhenNoPdpFileExists() throws IOException {
    // Setup export
    Path exportDir = tempDir.getRoot().toPath().toRealPath();

    // Remove PDP file
    Path xacmlPolicy = ddfHome.resolve(PDP_POLICIES_DIR).resolve(XACML_POLICY);
    Files.delete(xacmlPolicy);

    // Perform export
    doExport(exportDir);

    // Setup import
    setup(DDF_IMPORTED_HOME, DDF_IMPORTED_TAG, IMPORTING_PRODUCT_VERSION);

    SecurityMigratable iSecurityMigratable = spy(new SecurityMigratable());
    when(iSecurityMigratable.getVersion()).thenReturn("3.0");
    List<Migratable> iMigratables = Arrays.asList(iSecurityMigratable);
    ConfigurationMigrationManager iConfigurationMigrationManager = new ConfigurationMigrationManager(
            iMigratables, systemService);

    MigrationReport importReport = iConfigurationMigrationManager.doImport(exportDir, this::print);

    // Verify import
    verify(iSecurityMigratable).doVersionUpgradeImport(any(ImportMigrationContext.class));
    assertThat("The import report has errors.", importReport.hasErrors(), is(false));
    assertThat("The import report has warnings.", importReport.hasWarnings(), is(false));
    assertThat("Import was not successful.", importReport.wasSuccessful(), is(true));
    Path policy = ddfHome.resolve(SECURITY_POLICIES_DIR).resolve("configurations.policy").toRealPath();
    assertThat(String.format("%s does not exist.", policy), policy.toFile().exists(), is(true));
    assertThat(String.format("%s was not imported.", policy), verifyImported(policy), is(true));
    verifyCrlImported();
}

From source file:org.matonto.etl.rest.impl.DelimitedRestImpl.java

private void deleteDirectory(Path dir) throws IOException {
    if (Files.exists(dir)) {
        Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
            @Override/* ww  w  .  ja v a 2 s.  c  o  m*/
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.delete(file);
                return CONTINUE;
            }

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

From source file:nextflow.fs.dx.DxFileSystemProvider.java

/**
 * Implements the *copy* operation using the DnaNexus API *clone*
 *
 *
 * <p>// www . ja  v a2 s. c o m
 * See clone https://wiki.dnanexus.com/API-Specification-v1.0.0/Cloning#API-method%3A-%2Fclass-xxxx%2Fclone
 *
 * @param source
 * @param target
 * @param options
 * @throws IOException
 */

@Override
public void copy(Path source, Path target, CopyOption... options) throws IOException {

    List<CopyOption> opts = Arrays.asList(options);
    boolean targetExists = Files.exists(target);

    if (targetExists) {
        if (Files.isRegularFile(target)) {
            if (opts.contains(StandardCopyOption.REPLACE_EXISTING)) {
                Files.delete(target);
            } else {
                throw new FileAlreadyExistsException("Copy failed -- target file already exists: " + target);
            }

        } else if (Files.isDirectory(target)) {
            target = target.resolve(source.getFileName());
        } else {
            throw new UnsupportedOperationException();
        }
    }

    String name1 = source.getFileName().toString();
    String name2 = target.getFileName().toString();
    if (!name1.equals(name2)) {
        throw new UnsupportedOperationException(
                "Copy to a file with a different name is not supported: " + source.toString());
    }

    final DxPath dxSource = toDxPath(source);
    final DxFileSystem dxFileSystem = dxSource.getFileSystem();
    dxFileSystem.fileCopy(dxSource, toDxPath(target));
}