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:org.codice.ddf.security.migratable.impl.SecurityMigratableTest.java

/** Verifies that when no policy file exists, the export and import both succeed. */
@Test/*from ww  w .  ja  v a  2 s.  c  o m*/
public void testDoExportAndDoImportWhenNoPolicyFileExists() throws IOException {
    // Setup export
    Path exportDir = tempDir.getRoot().toPath().toRealPath();

    // Remove Policy file
    for (final String file : POLICY_FILES) {
        Path policy = ddfHome.resolve(SECURITY_POLICIES_DIR).resolve(file);
        Files.delete(policy);
    }

    // Perform export
    MigrationReport exportReport = doExport(exportDir);

    // Verify export
    assertThat("The export report has errors.", exportReport.hasErrors(), is(false));
    assertThat("The export report has warnings.", exportReport.hasWarnings(), is(false));
    assertThat("Export was not successful.", exportReport.wasSuccessful(), is(true));
    String exportedZipBaseName = String.format("%s-%s.dar", SUPPORTED_BRANDING, SUPPORTED_PRODUCT_VERSION);
    Path exportedZip = exportDir.resolve(exportedZipBaseName).toRealPath();
    assertThat("Export zip does not exist.", exportedZip.toFile().exists(), is(true));
    assertThat("Exported zip is empty.", exportedZip.toFile().length(), greaterThan(0L));

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

    SecurityMigratable iSecurityMigratable = new SecurityMigratable();
    List<Migratable> iMigratables = Arrays.asList(iSecurityMigratable);
    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));
    verifyPdpFilesImported();
    verifyCrlImported();
}

From source file:fr.duminy.jbackup.core.JBackupImplTest.java

private BackupConfiguration createConfiguration() throws IOException {
    ArchiveFactory archiveFactory = ZipArchiveFactory.INSTANCE;
    BackupConfiguration config = new BackupConfiguration();
    config.setName("test");
    Path targetDirectory = tempFolder.newFolder().toPath().toAbsolutePath();
    Files.delete(targetDirectory);
    config.setTargetDirectory(targetDirectory.toString());
    config.setArchiveFactory(archiveFactory);
    config.addSource(TestUtils.createSourceWithFiles(tempFolder, "source"));
    return config;
}

From source file:org.apache.taverna.databundle.TestDataBundles.java

@Test
public void newListItem() throws Exception {
    Path inputs = DataBundles.getInputs(dataBundle);
    Path list = DataBundles.getPort(inputs, "in1");
    DataBundles.createList(list);//from  w  w w.  jav a2  s.co  m
    Path item0 = DataBundles.newListItem(list);
    assertEquals(list, item0.getParent());
    assertTrue(item0.getFileName().toString().contains("0"));
    assertFalse(Files.exists(item0));
    DataBundles.setStringValue(item0, "test");

    Path item1 = DataBundles.newListItem(list);
    assertTrue(item1.getFileName().toString().contains("1"));
    // Because we've not actually created item1 yet
    assertEquals(item1, DataBundles.newListItem(list));
    DataBundles.setStringValue(item1, "test");

    // Check that DataBundles.newListItem can deal with gaps
    Files.delete(item0);
    Path item2 = DataBundles.newListItem(list);
    assertTrue(item2.getFileName().toString().contains("2"));

    // Check that non-numbers don't interfere
    Path nonumber = list.resolve("nonumber");
    Files.createFile(nonumber);
    item2 = DataBundles.newListItem(list);
    assertTrue(item2.getFileName().toString().contains("2"));

    // Check that extension is stripped
    Path five = list.resolve("5.txt");
    Files.createFile(five);
    Path item6 = DataBundles.newListItem(list);
    assertTrue(item6.getFileName().toString().contains("6"));
}

From source file:org.apache.openaz.xacml.std.pap.StdPDPGroup.java

/**
 * Copy one policy file into the Group's directory but do not change the configuration. This is one part
 * of a multi-step process of publishing policies. There may be multiple changes in the group (adding
 * multiple policies, deleting policies, changine root<->referenced) that must be done all at once, so we
 * just copy the file in preparation for a later "update whole group" operation.
 *
 * @param id/*from w w w  .ja  v  a 2 s. c  o m*/
 * @param name
 * @param isRoot
 * @param policy
 * @return
 * @throws org.apache.openaz.xacml.api.pap.PAPException
 */
public void copyPolicyToFile(String id, InputStream policy) throws PAPException {
    try {
        //
        // Copy the policy over
        //
        long num;
        Path policyFilePath = Paths.get(this.directory.toAbsolutePath().toString(), id);

        //
        // THERE IS A WEIRD PROBLEM ON WINDOWS...
        // The file is already "in use" when we try to access it.
        // Looking at the file externally while this is halted here does not show the file in use,
        // so there is no indication what is causing the problem.
        //
        // As a way to by-pass the issue, I simply check if the input and the existing file are identical
        // and generate an exception if they are not.
        //

        // if (Files.exists(policyFilePath)) {
        // // compare the
        // String incomingPolicyString = null;
        // try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
        // num = ByteStreams.copy(policy, os);
        // incomingPolicyString = new String(os.toByteArray(), "UTF-8");
        // }
        // String existingPolicyString = null;
        // try {
        // byte[] bytes = Files.readAllBytes(policyFilePath);
        // existingPolicyString = new String(bytes, "UTF-8");
        // } catch (Exception e) {
        // logger.error("Unable to read existing file '" + policyFilePath + "': " + e, e);
        // throw new PAPException("Unable to read policy file for comparison: " + e);
        // }
        // if (incomingPolicyString.equals(existingPolicyString)) {
        // throw new PAPException("Policy '" + policyFilePath +
        // "' does not match existing policy on server");
        // }
        // // input is same as existing file
        // return;
        // }

        Path policyFile;
        if (Files.exists(policyFilePath)) {
            policyFile = policyFilePath;
        } else {
            policyFile = Files.createFile(policyFilePath);
        }

        try (OutputStream os = Files.newOutputStream(policyFile)) {
            num = ByteStreams.copy(policy, os);
        }

        logger.info("Copied " + num + " bytes for policy " + name);

        for (PDPPolicy p : policies) {
            if (p.getId().equals(id)) {
                // we just re-copied/refreshed/updated the policy file for a policy that already exists in
                // this group
                logger.info("Policy '" + id + "' already exists in group '" + getId() + "'");
                return;
            }
        }

        // policy is new to this group
        StdPDPPolicy tempRootPolicy = new StdPDPPolicy(id, true, name, policyFile.toUri());
        if (!tempRootPolicy.isValid()) {
            try {
                Files.delete(policyFile);
            } catch (Exception ee) {
                logger.error("Policy was invalid, could NOT delete it.", ee);
            }
            throw new PAPException("Policy is invalid");
        }
        //
        // Add it in
        //
        this.policies.add(tempRootPolicy);
        //
        // We are changed
        //
        this.firePDPGroupChanged(this);

    } catch (IOException e) {
        logger.error("Failed to copyPolicyToFile: ", e);
        throw new PAPException("Failed to copy policy to file: " + e);
    }
}

From source file:org.apache.drill.test.framework.Utils.java

public static void deleteFile(String filename) {
    try {// w w  w.jav a 2 s.co  m
        Path path = FileSystems.getDefault().getPath(filename);
        Files.delete(path);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.bekwam.mavenpomupdater.MainViewController.java

public void doUpdate() {

    for (POMObject p : tblPOMS.getItems()) {

        if (log.isDebugEnabled()) {
            log.debug("[DO UPDATE] p=" + p.getAbsPath());
        }//  w w w  . j a va 2  s  .  com

        if (p.getParseError()) {
            if (log.isDebugEnabled()) {
                log.debug("[DO UPDATE] skipping update of p=" + p.getAbsPath()
                        + " because of a parse error on scanning");
            }
            continue;
        }

        if (!p.getUpdate()) {
            if (log.isDebugEnabled()) {
                log.debug("[DO UPDATE] skipping update of p=" + p.getAbsPath()
                        + " because user excluded it from update");
            }
            continue;
        }

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(false);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(p.getAbsPath());

            if (p.getParentVersion() != null && p.getParentVersion().length() > 0) {
                XPath xpath = XPathFactory.newInstance().newXPath();
                XPathExpression expression = xpath.compile("//project/parent/version/text()");
                Node node = (Node) expression.evaluate(doc, XPathConstants.NODE);

                if (StringUtils.isNotEmpty(tfNewVersion.getText())) {
                    node.setNodeValue(tfNewVersion.getText());
                } else { // editing individual table cells
                    node.setNodeValue(p.getParentVersion());
                }
            }

            if (p.getVersion() != null && p.getVersion().length() > 0) {
                XPath xpath = XPathFactory.newInstance().newXPath();
                XPathExpression expression = xpath.compile("//project/version/text()");
                Node node = (Node) expression.evaluate(doc, XPathConstants.NODE);

                if (StringUtils.isNotEmpty(tfNewVersion.getText())) {
                    node.setNodeValue(tfNewVersion.getText());
                } else { // editing individual table cells
                    node.setNodeValue(p.getVersion());
                }
            }

            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer();

            String workingFileName = p.getAbsPath() + ".mpu";
            FileWriter fw = new FileWriter(workingFileName);
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(fw);
            transformer.transform(source, result);
            fw.close();

            Path src = FileSystems.getDefault().getPath(workingFileName);
            Path target = FileSystems.getDefault().getPath(p.getAbsPath());

            Files.copy(src, target, StandardCopyOption.REPLACE_EXISTING);

            Files.delete(src);

        } catch (Exception exc) {
            log.error("error updating poms", exc);
        }
    }

    if (StringUtils.isNotEmpty(tfRootDir.getText())) {
        if (log.isDebugEnabled()) {
            log.debug("[DO UPDATE] issuing rescan command");
        }
        scan();
    } else {
        if (log.isDebugEnabled()) {
            log.debug("[DO UPDATE] did an update, but there is not value in root; clearing");
        }
        tblPOMS.getItems().clear();
    }
    tblPOMSDirty = false;
    tfNewVersion.setDisable(false);
}

From source file:org.apache.openaz.xacml.pdp.test.policy.TestPolicy.java

protected void removeRequests() {
    ////from   w  w w . j a va 2  s.com
    // Delete any existing request files that we generate. i.e. Have the Unknown in the file name.
    //
    try {
        Files.walkFileTree(Paths.get(this.directory.toString(), "requests"), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                //
                // Sanity check the file name
                //
                Matcher matcher = pattern.matcher(file.getFileName().toString());
                if (matcher.matches()) {
                    try {
                        //
                        // Pull what this request is supposed to be
                        //
                        String group = null;
                        int count = matcher.groupCount();
                        if (count >= 1) {
                            group = matcher.group(count - 1);
                        }
                        //
                        // Send it
                        //
                        if (group.equals("Unknown")) {
                            //
                            // Remove the file
                            //
                            Files.delete(file);
                        }
                    } catch (Exception e) {
                        logger.error(e);
                        e.printStackTrace();
                    }
                }
                return super.visitFile(file, attrs);
            }
        });
    } catch (IOException e) {
        logger.error("Failed to removeRequests from " + this.directory + " " + e);
    }
}

From source file:org.openremote.beehive.configuration.www.UsersAPI.java

private void removeTemporaryFiles(java.nio.file.Path directory) {
    if (directory == null) {
        return;//from   w w w  . j ava  2s.c  om
    }
    try {
        Files.walkFileTree(directory, new SimpleFileVisitor<java.nio.file.Path>() {
            @Override
            public FileVisitResult visitFile(java.nio.file.Path file, BasicFileAttributes attrs)
                    throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(java.nio.file.Path dir, IOException exc)
                    throws IOException {
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        log.error("Could not clean-up temporary folder used to create openremote.zip file", e);
    }
}

From source file:org.apache.solr.schema.TestManagedSchema.java

public void testPersistUniqueKey() throws Exception {
    assertSchemaResource(collection, "managed-schema");
    deleteCore();/*from   www. ja v a2 s.  c  om*/
    File managedSchemaFile = new File(tmpConfDir, "managed-schema");
    Files.delete(managedSchemaFile.toPath()); // Delete managed-schema so it won't block parsing a new schema
    System.setProperty("managed.schema.mutable", "true");
    initCore("solrconfig-managed-schema.xml", "schema-one-field-no-dynamic-field-unique-key.xml",
            tmpSolrHome.getPath());

    assertTrue(managedSchemaFile.exists());
    String managedSchemaContents = FileUtils.readFileToString(managedSchemaFile, "UTF-8");
    assertFalse(managedSchemaContents.contains("\"new_field\""));

    Map<String, Object> options = new HashMap<>();
    options.put("stored", "false");
    IndexSchema oldSchema = h.getCore().getLatestSchema();
    assertEquals("str", oldSchema.getUniqueKeyField().getName());
    String fieldName = "new_field";
    String fieldType = "string";
    SchemaField newField = oldSchema.newField(fieldName, fieldType, options);
    IndexSchema newSchema = oldSchema.addField(newField);
    assertEquals("str", newSchema.getUniqueKeyField().getName());
    h.getCore().setLatestSchema(newSchema);
    log.info("####close harness");
    h.close();
    log.info("####close harness end");
    initCore();

    assertTrue(managedSchemaFile.exists());
    FileInputStream stream = new FileInputStream(managedSchemaFile);
    managedSchemaContents = IOUtils.toString(stream, "UTF-8");
    stream.close(); // Explicitly close so that Windows can delete this file
    assertTrue(managedSchemaContents.contains("<field name=\"new_field\" type=\"string\" stored=\"false\"/>"));
    IndexSchema newNewSchema = h.getCore().getLatestSchema();
    assertNotNull(newNewSchema.getUniqueKeyField());
    assertEquals("str", newNewSchema.getUniqueKeyField().getName());
}

From source file:org.apache.openaz.xacml.std.pap.StdPDPGroup.java

public boolean removePolicy(PDPPolicy policy) {
    StdPDPPolicy currentPolicy = (StdPDPPolicy) this.getPolicy(policy.getId());
    if (currentPolicy == null) {
        logger.error("Policy " + policy.getId() + " does not exist.");
        return false;
    }/*  www .  ja  v a2 s.com*/
    try {
        //
        // Delete it on disk
        //
        Files.delete(Paths.get(currentPolicy.getLocation()));
        //
        // Remove it from our list
        //
        this.policies.remove(currentPolicy);
        //
        // We are changed
        //
        this.firePDPGroupChanged(this);
        return true;
    } catch (Exception e) {
        logger.error("Failed to delete policy " + policy);
    }
    return false;
}