Java Code Examples for java.nio.file.Files#delete()

The following examples show how to use java.nio.file.Files#delete() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RaftStorageDirectory.java    From incubator-ratis with Apache License 2.0 6 votes vote down vote up
public static LogPathAndIndex processOnePath(Path path) throws IOException {
  for (Pattern pattern : Arrays.asList(CLOSED_SEGMENT_REGEX, OPEN_SEGMENT_REGEX)) {
    Matcher matcher = pattern.matcher(path.getFileName().toString());
    if (matcher.matches()) {
      if (pattern == OPEN_SEGMENT_REGEX && Files.size(path) == 0L) {
        Files.delete(path);
        LOG.info("Delete zero size file " + path);
        return null;
      }
      final long startIndex = Long.parseLong(matcher.group(1));
      final long endIndex = matcher.groupCount() == 2 ?
          Long.parseLong(matcher.group(2)) : RaftLog.INVALID_LOG_INDEX;
      return new LogPathAndIndex(path, startIndex, endIndex);
    }
  }
  return null;
}
 
Example 2
Source File: DownloadRemoteIndexTaskTest.java    From archiva with Apache License 2.0 6 votes vote down vote up
@Before
public void initialize()
    throws Exception
{
    Path cfgFile = Paths.get("target/appserver-base/conf/archiva.xml");
    if (Files.exists(cfgFile)) {
        Files.delete(cfgFile);
    }
    try {
        repositoryRegistry.removeRepository( "test-repo-re" );
    } catch (Exception e) {
        // Ignore
    }
    server = new Server( );
    serverConnector = new ServerConnector( server, new HttpConnectionFactory());
    server.addConnector( serverConnector );
    createContext( server, Paths.get( "src/test/" ) );
    this.server.start();
    this.port = serverConnector.getLocalPort();
    log.info( "start server on port {}", this.port );
}
 
Example 3
Source File: SpecialCBinariesTest.java    From incubator-datasketches-java with Apache License 2.0 6 votes vote down vote up
static void byteArrToFile(byte[] byteArr, String fileName) throws Exception {
  String userDir = System.getProperty("user.dir");
  String fullPathName = userDir + "/src/test/resources/" + fileName;
  File file = new File(fullPathName);
  if (file.exists()) { Files.delete(file.toPath()); }
  assertTrue(file.createNewFile());
  assertTrue(file.setWritable(true, false));
  assertTrue(file.isFile());

  try (WritableMapHandle wmh
      = WritableMemory.map(file, 0, byteArr.length, ByteOrder.nativeOrder())) {
    WritableMemory wmem = wmh.get();
    wmem.putByteArray(0, byteArr, 0, byteArr.length);
    wmh.force();
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example 4
Source File: LargeFileAvailable.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private static void createLargeFile(long filesize,
                                    File file) throws Exception {
    // Recreate a large file as a sparse file if possible
    Files.delete(file.toPath());

    try (FileChannel fc =
         FileChannel.open(file.toPath(),
                          CREATE_NEW, WRITE, SPARSE)) {
        ByteBuffer bb = ByteBuffer.allocate(1).put((byte)1);
        bb.rewind();
        int rc = fc.write(bb, filesize - 1);

        if (rc != 1) {
            throw new RuntimeException("Failed to write 1 byte"
                                       + " to the large file");
        }
    }
    return;
}
 
Example 5
Source File: ZipTest.java    From turbine with Apache License 2.0 5 votes vote down vote up
@Test
public void zipFileCommentsAreSupported() throws Exception {
  Path path = temporaryFolder.newFile("test.jar").toPath();
  Files.delete(path);
  try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(path))) {
    createEntry(zos, "hello", "world".getBytes(UTF_8));
    zos.setComment("this is a comment");
  }
  assertThat(actual(path)).isEqualTo(expected(path));
}
 
Example 6
Source File: FilterConfigController.java    From kafka-webview with MIT License 5 votes vote down vote up
/**
 * POST deletes the selected filter.
 */
@RequestMapping(path = "/delete/{id}", method = RequestMethod.POST)
public String delete(@PathVariable final Long id, final RedirectAttributes redirectAttributes) {
    // Retrieve it
    final Optional<Filter> filterOptional = filterRepository.findById(id);
    if (!filterOptional.isPresent()) {
        // Set flash message & redirect
        redirectAttributes.addFlashAttribute("FlashMessage", FlashMessage.newWarning("Unable to remove filter!"));
    } else {
        final Filter filter = filterOptional.get();
        try {
            // Delete any children
            final List<ViewToFilterEnforced> enforcedList = viewToFilterEnforcedRepository.findByFilterId(id);
            final List<ViewToFilterOptional> optionalList = viewToFilterOptionalRepository.findByFilterId(id);

            viewToFilterEnforcedRepository.deleteAll(enforcedList);
            viewToFilterOptionalRepository.deleteAll(optionalList);

            // Delete entity
            filterRepository.deleteById(id);

            // Delete jar from disk
            Files.delete(recordFilterPluginFactory.getPathForJar(filter.getJar()));
            redirectAttributes.addFlashAttribute("FlashMessage", FlashMessage.newSuccess("Deleted filter!"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // redirect to cluster index
    return "redirect:/configuration/filter";
}
 
Example 7
Source File: NameLimits.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
static boolean tryCreateFile(int len) throws IOException {
    Path name = generatePath(len);
    try {
        Files.createFile(name);
    } catch (IOException ioe) {
        System.err.format("Unable to create file of length %d (full path %d), %s%n",
            name.toString().length(), name.toAbsolutePath().toString().length(), ioe);
        return false;
    }
    Files.delete(name);
    return true;
}
 
Example 8
Source File: FileUtil.java    From algorithms-sedgewick-wayne with MIT License 5 votes vote down vote up
public static void deleteFile(String filePath) {
    try {
        Files.delete(Paths.get(filePath));
    } catch (IOException exception) {
        exception.printStackTrace();
    }
}
 
Example 9
Source File: DifferentFilesSshFetchTest.java    From gitflow-incremental-builder with MIT License 5 votes vote down vote up
@Test
@RunOnlyWhen(RunCondition.ON_TRAVIS_OR_FORCED)    // "pollutes" ssh-agent, default execution is only safe on Travis-CI
public void fetchWithPassphraseEncryptedKey() throws Exception {
    projectProperties.put(Property.useJschAgentProxy.name(), "true");
    writePrivateKey("id_rsa", TestServerType.SSH_PROTOCOL.getUserSecretEncrypted());
    Path unencryptedPrivateKeyPath = writePrivateKey("id_rsa_unencrypted", TestServerType.SSH_PROTOCOL.getUserSecret());
    ProcessUtils.startAndWaitForProcess("ssh-add", unencryptedPrivateKeyPath.toAbsolutePath().toString());
    Files.delete(unencryptedPrivateKeyPath);

    test();
}
 
Example 10
Source File: TestFileStore.java    From jsr203-hadoop with Apache License 2.0 5 votes vote down vote up
@Test
public void testHadoopFileStoreAttributeView() throws IOException {
  URI uri = clusterUri.resolve("/tmp/testFileStore");
  Path path = Paths.get(uri);
  if (Files.exists(path))
    Files.delete(path);
  assertFalse(Files.exists(path));
  Files.createFile(path);
  assertTrue(Files.exists(path));
  FileStore store1 = Files.getFileStore(path);
  assertNotNull(store1);

  Assert.assertNull(
      store1.getFileStoreAttributeView(FakeFileStoreAttributeView.class));
}
 
Example 11
Source File: CxxRawHeadersIntegrationTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void removingUsedHeaderAndReferenceToItCausesRebuild2() throws IOException {
  workspace.writeContentsToPath("int main() { return 1; }", "depfiles2/test/test.cpp");
  Files.delete(workspace.getPath("depfiles2/headers/used.h"));
  workspace.replaceFileContents("depfiles2/headers/BUCK", "\"used.h\",", "");
  runCommand("build", target2.toString()).assertSuccess();
  assertThat(
      workspace.getBuildLog().getLogEntry(compileTarget2).getSuccessType(),
      Matchers.equalTo(Optional.of(BuildRuleSuccessType.BUILT_LOCALLY)));
}
 
Example 12
Source File: FileHelpers.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
public static Path makeTempFilePath(boolean exists) throws IOException {
  Path result;
  if (System.getenv().containsKey("TEST_TMPDIR")) {
    result = Files.createTempFile(Paths.get(System.getenv("TEST_TMPDIR")), "", "json");
  } else {
    result = Files.createTempFile("", "json");
  }
  if (!exists) {
    Files.delete(result);
  }
  return result;
}
 
Example 13
Source File: DeleteInterference.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static void deleteFileTree(Path file) {
    try {
        if (Files.isDirectory(file)) {
            try (DirectoryStream<Path> stream = Files.newDirectoryStream(file)) {
                for (Path pa : stream) {
                    deleteFileTree(pa);
                }
            }
        }
        Files.delete(file);
    } catch (IOException ioe) {
        // ignore
    }
}
 
Example 14
Source File: TestDataBundles.java    From incubator-taverna-language with Apache License 2.0 5 votes vote down vote up
@Test(expected=FileAlreadyExistsException.class)
public void getIntermediatesFails() throws Exception {
    Path intermediates = DataBundles.getIntermediates(dataBundle);
    Files.delete(intermediates);
    Files.createFile(intermediates);
    DataBundles.getIntermediates(dataBundle);
}
 
Example 15
Source File: ReportingTruncateWorker.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
private int deleteOldExportCsvFiles() throws IOException {
    long now = System.currentTimeMillis();
    int counter = 0;
    try (DirectoryStream<Path> csvFolder = Files.newDirectoryStream(Paths.get(FileUtils.CSV_DIR), "*")) {
        for (Path csvFile : csvFolder) {
            if (csvFile.getFileName().toString().endsWith(CSVGenerator.EXPORT_CSV_EXTENSION)
                    && isOutdated(csvFile, now)) {
                counter++;
                Files.delete(csvFile);
            }
        }
    }
    return counter;
}
 
Example 16
Source File: HashMapSnapshot.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public SnapshotRecovery<T> recover() throws IOException {
    final File partialFile = getPartialFile();
    final File snapshotFile = getSnapshotFile();
    final boolean partialExists = partialFile.exists();
    final boolean snapshotExists = snapshotFile.exists();

    // If there is no snapshot (which is the case before the first snapshot is ever created), then just
    // return an empty recovery.
    if (!partialExists && !snapshotExists) {
        return SnapshotRecovery.emptyRecovery();
    }

    if (partialExists && snapshotExists) {
        // both files exist -- assume NiFi crashed/died while checkpointing. Delete the partial file.
        Files.delete(partialFile.toPath());
    } else if (partialExists) {
        // partial exists but snapshot does not -- we must have completed
        // creating the partial, deleted the snapshot
        // but crashed before renaming the partial to the snapshot. Just
        // rename partial to snapshot
        Files.move(partialFile.toPath(), snapshotFile.toPath());
    }

    if (snapshotFile.length() == 0) {
        logger.warn("{} Found 0-byte Snapshot file; skipping Snapshot file in recovery", this);
        return SnapshotRecovery.emptyRecovery();
    }

    // At this point, we know the snapshotPath exists because if it didn't, then we either returned null
    // or we renamed partialPath to snapshotPath. So just Recover from snapshotPath.
    try (final DataInputStream dataIn = new DataInputStream(new BufferedInputStream(new FileInputStream(snapshotFile)))) {
        // Ensure that the header contains the information that we expect and retrieve the relevant information from the header.
        final SnapshotHeader header = validateHeader(dataIn);

        final SerDe<T> serde = header.getSerDe();
        final int serdeVersion = header.getSerDeVersion();
        final int numRecords = header.getNumRecords();
        final long maxTransactionId = header.getMaxTransactionId();

        // Read all of the records that we expect to receive.
        for (int i = 0; i < numRecords; i++) {
            final T record = serde.deserializeRecord(dataIn, serdeVersion);
            if (record == null) {
                throw new EOFException();
            }

            final UpdateType updateType = serde.getUpdateType(record);
            if (updateType == UpdateType.DELETE) {
                logger.warn("While recovering from snapshot, found record with type 'DELETE'; this record will not be restored");
                continue;
            }

            logger.trace("Recovered from snapshot: {}", record);
            recordMap.put(serde.getRecordIdentifier(record), record);
        }

        // Determine the location of any swap files.
        final int numSwapRecords = dataIn.readInt();
        final Set<String> swapLocations = new HashSet<>();
        for (int i = 0; i < numSwapRecords; i++) {
            swapLocations.add(dataIn.readUTF());
        }
        this.swapLocations.addAll(swapLocations);

        logger.info("{} restored {} Records and {} Swap Files from Snapshot, ending with Transaction ID {}",
            new Object[] {this, numRecords, swapLocations.size(), maxTransactionId});

        return new StandardSnapshotRecovery<>(recordMap, swapLocations, snapshotFile, maxTransactionId);
    }
}
 
Example 17
Source File: PdfExporterV2.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public byte[] getBinaryData() throws IOException, InterruptedException, EMFUserError {

	final Path outputDir = Files.createTempDirectory("knowage-pdf-exporter-2");
	final Path outputFile = outputDir.resolve("output.pdf");

	Files.createDirectories(outputDir);

	BIObject document = DAOFactory.getBIObjectDAO().loadBIObjectById(documentId);
	int sheetCount = getSheetCount(document);
	int sheetWidth = getSheetWidth(document);
	int sheetHeight = getSheetHeight(document);

	String encodedUserId = Base64.encodeBase64String(userId.getBytes("UTF-8"));

	URI url = UriBuilder.fromUri(requestUrl).replaceQueryParam("outputType_description", "HTML").replaceQueryParam("outputType", "HTML")
			.replaceQueryParam("export", null).build();

	// Script
	String cockpitExportScriptPath = SingletonConfig.getInstance().getConfigValue(CONFIG_NAME_FOR_EXPORT_SCRIPT_PATH);
	Path exportScriptFullPath = Paths.get(cockpitExportScriptPath, SCRIPT_NAME);

	if (!Files.isRegularFile(exportScriptFullPath)) {
		String msg = String.format("Cannot find export script at \"%s\": did you set the correct value for %s configuration?", exportScriptFullPath,
				CONFIG_NAME_FOR_EXPORT_SCRIPT_PATH);
		IllegalStateException ex = new IllegalStateException(msg);
		logger.error(msg, ex);
		throw ex;
	}

	ProcessBuilder processBuilder = new ProcessBuilder("node", exportScriptFullPath.toString(), url.toString(), encodedUserId, outputDir.toString(),
			Integer.toString(sheetCount), Integer.toString(sheetWidth), Integer.toString(sheetHeight)/*, cockpitExportLogPath*/);

	Process exec = processBuilder.start();

	exec.waitFor();

	final List<InputStream> imagesInputStreams = new ArrayList<InputStream>();

	try {
		Files.walkFileTree(outputDir, new SheetImageFileVisitor(imagesInputStreams));

		if (imagesInputStreams.isEmpty()) {
			throw new IllegalStateException("No files in " + outputDir + ": see main log file of the AS");
		}

		PDFCreator.createPDF(imagesInputStreams, outputFile, false, false);
		ExportDetails details = new ExportDetails(getFrontpageDetails(pdfFrontPage, document), null);
		PDFCreator.addInformation(outputFile, details);

		try (InputStream is = Files.newInputStream(outputFile, StandardOpenOption.DELETE_ON_CLOSE)) {
			return IOUtils.toByteArray(is);
		}
	} finally {
		for (InputStream currImageinputStream : imagesInputStreams) {
			IOUtils.closeQuietly(currImageinputStream);
		}
		try {
			Files.delete(outputDir);
		} catch (Exception e) {
			// Yes, it's mute!
		}
	}
}
 
Example 18
Source File: TestFileTailSource.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Test
public void testTailFilesDeletion() throws Exception {
  File testDataDir = new File("target", UUID.randomUUID().toString());
  File testDataDir1 = new File(testDataDir, UUID.randomUUID().toString());
  File testDataDir2 = new File(testDataDir, UUID.randomUUID().toString());
  Assert.assertTrue(testDataDir1.mkdirs());
  Assert.assertTrue(testDataDir2.mkdirs());
  Path file1 = new File(testDataDir1, "log1.txt").toPath();
  Path file2 = new File(testDataDir2, "log2.txt").toPath();
  Files.write(file1, Arrays.asList("Hello"), UTF8);
  Files.write(file2, Arrays.asList("Hola"), UTF8);

  FileInfo fileInfo1 = new FileInfo();
  fileInfo1.fileFullPath = testDataDir.getAbsolutePath() + "/*/log*.txt";
  fileInfo1.fileRollMode = FileRollMode.REVERSE_COUNTER;
  fileInfo1.firstFile = "";
  fileInfo1.patternForToken = "";

  FileTailConfigBean conf = new FileTailConfigBean();
  conf.dataFormat = DataFormat.TEXT;
  conf.multiLineMainPattern = "";
  conf.batchSize = 25;
  conf.maxWaitTimeSecs = 1;
  conf.fileInfos = Arrays.asList(fileInfo1);
  conf.postProcessing = PostProcessingOptions.NONE;
  conf.dataFormatConfig.textMaxLineLen = 1024;

  FileTailSource source = new FileTailSource(conf, SCAN_INTERVAL);
  SourceRunner runner = new SourceRunner.Builder(FileTailDSource.class, source)
      .addOutputLane("lane").addOutputLane("metadata")
      .build();
  try {
    runner.runInit();
    StageRunner.Output output = runner.runProduce(null, 10);
    output = runner.runProduce(output.getNewOffset(), 10);
    Assert.assertTrue(output.getNewOffset().contains("log1.txt"));
    Assert.assertTrue(output.getNewOffset().contains("log2.txt"));
    Files.delete(file1);
    Files.delete(testDataDir1.toPath());
    output = runner.runProduce(output.getNewOffset(), 10);
    output = runner.runProduce(output.getNewOffset(), 10);
    Assert.assertFalse(output.getNewOffset().contains("log1.txt"));
    Assert.assertTrue(output.getNewOffset().contains("log2.txt"));
  } finally {
    runner.runDestroy();
  }
}
 
Example 19
Source File: StreamTest.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public void testWalkFollowLinkLoop() {
    if (!supportsLinks) {
        return;
    }

    // Loops.
    try {
        Path dir = testFolder.resolve("dir");
        Path linkdir = testFolder.resolve("linkDir");
        Path d1 = dir.resolve("d1");
        Path cause = d1.resolve("lnSelf");
        Files.createSymbolicLink(cause, d1);

        // loop in descendant.
        validateFileSystemLoopException(dir, cause);
        // loop in self
        validateFileSystemLoopException(d1, cause);
        // start from other place via link
        validateFileSystemLoopException(linkdir,
                linkdir.resolve(Paths.get("d1", "lnSelf")));
        Files.delete(cause);

        // loop to parent.
        cause = d1.resolve("lnParent");
        Files.createSymbolicLink(cause, dir);

        // loop should be detected at test/dir/d1/lnParent/d1
        validateFileSystemLoopException(d1, cause.resolve("d1"));
        // loop should be detected at link
        validateFileSystemLoopException(dir, cause);
        // loop should be detected at test/linkdir/d1/lnParent
        // which is test/dir we have visited via test/linkdir
        validateFileSystemLoopException(linkdir,
                linkdir.resolve(Paths.get("d1", "lnParent")));
        Files.delete(cause);

        // cross loop
        Path dir2 = testFolder.resolve("dir2");
        cause = dir2.resolve("lnDir");
        Files.createSymbolicLink(cause, dir);
        validateFileSystemLoopException(dir,
                dir.resolve(Paths.get("lnDir2", "lnDir")));
        validateFileSystemLoopException(dir2,
                dir2.resolve(Paths.get("lnDir", "lnDir2")));
        validateFileSystemLoopException(linkdir,
                linkdir.resolve(Paths.get("lnDir2", "lnDir")));
    } catch(IOException ioe) {
        fail("Unexpected IOException " + ioe);
    }
}
 
Example 20
Source File: StreamTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public void testWalkFollowLinkLoop() {
    if (!supportsLinks) {
        return;
    }

    // Loops.
    try {
        Path dir = testFolder.resolve("dir");
        Path linkdir = testFolder.resolve("linkDir");
        Path d1 = dir.resolve("d1");
        Path cause = d1.resolve("lnSelf");
        Files.createSymbolicLink(cause, d1);

        // loop in descendant.
        validateFileSystemLoopException(dir, cause);
        // loop in self
        validateFileSystemLoopException(d1, cause);
        // start from other place via link
        validateFileSystemLoopException(linkdir,
                linkdir.resolve(Paths.get("d1", "lnSelf")));
        Files.delete(cause);

        // loop to parent.
        cause = d1.resolve("lnParent");
        Files.createSymbolicLink(cause, dir);

        // loop should be detected at test/dir/d1/lnParent/d1
        validateFileSystemLoopException(d1, cause.resolve("d1"));
        // loop should be detected at link
        validateFileSystemLoopException(dir, cause);
        // loop should be detected at test/linkdir/d1/lnParent
        // which is test/dir we have visited via test/linkdir
        validateFileSystemLoopException(linkdir,
                linkdir.resolve(Paths.get("d1", "lnParent")));
        Files.delete(cause);

        // cross loop
        Path dir2 = testFolder.resolve("dir2");
        cause = dir2.resolve("lnDir");
        Files.createSymbolicLink(cause, dir);
        validateFileSystemLoopException(dir,
                dir.resolve(Paths.get("lnDir2", "lnDir")));
        validateFileSystemLoopException(dir2,
                dir2.resolve(Paths.get("lnDir", "lnDir2")));
        validateFileSystemLoopException(linkdir,
                linkdir.resolve(Paths.get("lnDir2", "lnDir")));
    } catch(IOException ioe) {
        fail("Unexpected IOException " + ioe);
    }
}