下面列出了怎么用com.google.common.io.RecursiveDeleteOption的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testJavaConstructorWithDeps() throws Exception {
InstanceConfig config = createJavaInstanceConfig(FunctionDetails.Runtime.JAVA);
Path dir = Files.createTempDirectory("test-empty-dir");
assertTrue(Files.exists(dir));
try {
int numFiles = 3;
for (int i = 0; i < numFiles; i++) {
Path file = Files.createFile(Paths.get(dir.toAbsolutePath().toString(), "file-" + i));
assertTrue(Files.exists(file));
}
factory = createProcessRuntimeFactory(dir.toAbsolutePath().toString());
verifyJavaInstance(config, dir);
} finally {
MoreFiles.deleteRecursively(dir, RecursiveDeleteOption.ALLOW_INSECURE);
}
}
private void cleanupFunctionFiles(FunctionRuntimeInfo functionRuntimeInfo) {
Function.Instance instance = functionRuntimeInfo.getFunctionInstance();
FunctionMetaData functionMetaData = instance.getFunctionMetaData();
// clean up function package
File pkgDir = new File(
workerConfig.getDownloadDirectory(),
getDownloadPackagePath(functionMetaData, instance.getInstanceId()));
if (pkgDir.exists()) {
try {
MoreFiles.deleteRecursively(
Paths.get(pkgDir.toURI()), RecursiveDeleteOption.ALLOW_INSECURE);
} catch (IOException e) {
log.warn("Failed to delete package for function: {}",
FunctionCommon.getFullyQualifiedName(functionMetaData.getFunctionDetails()), e);
}
}
}
public void deleteFastSyncState() {
// Make sure downloader is stopped before we start cleaning up its dependencies
worldStateDownloader.cancel();
try {
taskCollection.close();
if (fastSyncDataDirectory.toFile().exists()) {
// Clean up this data for now (until fast sync resume functionality is in place)
MoreFiles.deleteRecursively(fastSyncDataDirectory, RecursiveDeleteOption.ALLOW_INSECURE);
}
} catch (final IOException e) {
LOG.error("Unable to clean up fast sync state", e);
}
}
@TearDown(Level.Invocation)
public void tearDown() throws Exception {
ethProtocolManager.stop();
ethProtocolManager.awaitStop();
pendingRequests.close();
storageProvider.close();
MoreFiles.deleteRecursively(tempDir, RecursiveDeleteOption.ALLOW_INSECURE);
}
public void close() {
stop();
try {
MoreFiles.deleteRecursively(config.workDir(), RecursiveDeleteOption.ALLOW_INSECURE);
} catch (final IOException e) {
LOG.info("Failed to clean up temporary file: {}", config.workDir(), e);
}
}
@Override
@SuppressWarnings("UnstableApiUsage")
public void close() {
stop();
try {
MoreFiles.deleteRecursively(homeDirectory, RecursiveDeleteOption.ALLOW_INSECURE);
} catch (final IOException e) {
LOG.info("Failed to clean up temporary file: {}", homeDirectory, e);
}
}
public static void recursivelyDeleteDirectories(final List<File> directories) {
for (File tmpDirectory : directories) {
try {
MoreFiles.deleteRecursively(tmpDirectory.toPath(), RecursiveDeleteOption.ALLOW_INSECURE);
} catch (IOException e) {
LOG.error("Failed to delete directory: " + tmpDirectory.getAbsolutePath(), e);
throw new RuntimeException(e);
}
}
}
@AfterEach
public final void clearCache() throws IOException {
if (Files.exists(TEST_WORK_DIRECTORY)) {
MoreFiles.deleteDirectoryContents(TEST_WORK_DIRECTORY,RecursiveDeleteOption.ALLOW_INSECURE);
}
System.clearProperty(FilesUtils.LEMMINX_WORKDIR_KEY);
FilesUtils.resetDeployPath();
}
@AfterClass
public static void cleanUp() {
try {
// Mac's APFS fails with InsecureRecursiveDeleteException without ALLOW_INSECURE.
// Still safe as this test does not use symbolic links
if (outputDirectory != null) {
MoreFiles.deleteRecursively(outputDirectory, RecursiveDeleteOption.ALLOW_INSECURE);
}
} catch (IOException ex) {
// no big deal
}
}
public static void deleteRecursivelyIfExists(Path path) {
try {
if (path.toFile().exists()) {
MoreFiles.deleteRecursively(path, RecursiveDeleteOption.ALLOW_INSECURE);
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@VisibleForTesting
static void deleteCopiedPython(String pythonExePath) {
// The path returned from gcloud points to the "python.exe" binary. Delete it from the path.
String pythonHome = pythonExePath.replaceAll("[pP][yY][tT][hH][oO][nN]\\.[eE][xX][eE]$", "");
boolean endsWithPythonExe = !pythonHome.equals(pythonExePath);
if (endsWithPythonExe) { // just to be safe
try {
MoreFiles.deleteRecursively(Paths.get(pythonHome), RecursiveDeleteOption.ALLOW_INSECURE);
} catch (IOException e) {
// not critical to remove a temp directory
}
}
}
/**
* Delete all the contents of a path recursively.
*
* <p>First we try to delete securely. In case the FileSystem doesn't support it,
* delete it insecurely.
*/
public static void deleteRecursively(Path path) throws IOException {
try {
MoreFiles.deleteRecursively(path);
} catch (InsecureRecursiveDeleteException ignore) {
logger.atWarning().log("Secure delete not supported. Deleting '%s' insecurely.", path);
MoreFiles.deleteRecursively(path, RecursiveDeleteOption.ALLOW_INSECURE);
}
}
@Test
public void testJavaConstructorWithEmptyDir() throws Exception {
InstanceConfig config = createJavaInstanceConfig(FunctionDetails.Runtime.JAVA);
Path dir = Files.createTempDirectory("test-empty-dir");
assertTrue(Files.exists(dir));
try {
factory = createProcessRuntimeFactory(dir.toAbsolutePath().toString());
verifyJavaInstance(config, dir);
} finally {
MoreFiles.deleteRecursively(dir, RecursiveDeleteOption.ALLOW_INSECURE);
}
}
/**
* Deletes the file or directory at the given path recursively, allowing insecure delete according
* to {@code allowInsecureDelete}.
*
* @see RecursiveDeleteOption#ALLOW_INSECURE
*/
public void deleteRecursively(File file, boolean allowInsecureDelete) throws IOException {
if (allowInsecureDelete) {
MoreFiles.deleteRecursively(file.toPath(), RecursiveDeleteOption.ALLOW_INSECURE);
} else {
MoreFiles.deleteRecursively(file.toPath());
}
}
public RuntimeDecompiler(File outputPath) {
this.outputPath = outputPath;
if (this.outputPath.exists()) {
try {
MoreFiles.deleteRecursively(this.outputPath.toPath(), RecursiveDeleteOption.ALLOW_INSECURE);
} catch (IOException ex) {
this.logger.debug("Error cleaning output directory: {}", ex.getMessage());
}
}
}
public ExtensionClassExporter(MixinEnvironment env) {
this.decompiler = this.initDecompiler(env, new File(Constants.DEBUG_OUTPUT_DIR, ExtensionClassExporter.EXPORT_JAVA_DIR));
try {
MoreFiles.deleteRecursively(this.classExportDir.toPath(), RecursiveDeleteOption.ALLOW_INSECURE);
} catch (IOException ex) {
ExtensionClassExporter.logger.debug("Error cleaning class output directory: {}", ex.getMessage());
}
}
private static void cleanupDirectory(@Nullable Path directory) throws IOException {
if (directory == null) {
return;
}
if (Files.exists(directory)) {
try {
MoreFiles.deleteRecursively(directory, RecursiveDeleteOption.ALLOW_INSECURE);
} catch (IOException e) {
throw new IOException("Cannot clean '" + directory + "'", e);
}
}
Files.createDirectories(directory);
}
private static void createOutputDirectory(Path dir) throws IOException {
if (Files.exists(dir)) {
try {
MoreFiles.deleteRecursively(dir, RecursiveDeleteOption.ALLOW_INSECURE);
} catch (IOException e) {
throw new IOException("Cannot clean output directory '" + dir + "'", e);
}
}
Files.createDirectories(dir);
}
@Test
public void whenRootFolderIsDeletedThenInvalidateAll() throws Exception {
Path root = tmp.getRoot().resolve("root");
Files.createDirectory(root);
DirectoryListCache cache = DirectoryListCache.of(root);
Path dir = root.resolve("dir");
Files.createDirectory(dir);
Files.createFile(dir.resolve("file"));
cache.put(
ImmutableDirectoryListKey.of(Paths.get("")),
ImmutableDirectoryList.of(
ImmutableSortedSet.of(),
ImmutableSortedSet.of(Paths.get("dir")),
ImmutableSortedSet.of()));
cache.put(
ImmutableDirectoryListKey.of(Paths.get("dir")),
ImmutableDirectoryList.of(
ImmutableSortedSet.of(Paths.get("dir/file")),
ImmutableSortedSet.of(),
ImmutableSortedSet.of()));
MoreFiles.deleteRecursively(root, RecursiveDeleteOption.ALLOW_INSECURE);
WatchmanPathEvent event =
WatchmanPathEvent.of(AbsPath.of(root), Kind.DELETE, RelPath.of(Paths.get("dir/file")));
FileHashCacheEvent.InvalidationStarted started = FileHashCacheEvent.invalidationStarted();
cache.getInvalidator().onInvalidationStart(started);
cache.getInvalidator().onFileSystemChange(event);
cache.getInvalidator().onInvalidationFinish(FileHashCacheEvent.invalidationFinished(started));
// should invalidate root properly
Optional<DirectoryList> dlist = cache.get(ImmutableDirectoryListKey.of(Paths.get("")));
assertFalse(dlist.isPresent());
dlist = cache.get(ImmutableDirectoryListKey.of(Paths.get("dir")));
assertFalse(dlist.isPresent());
}
/**
* Cleans the AIRSONIC_HOME directory used for tests. (Does not delete the folder itself)
*/
public static void cleanAirsonicHomeForTest() throws IOException {
Path airsonicHomeDir = Paths.get(airsonicHomePathForTest());
MoreFiles.deleteDirectoryContents(airsonicHomeDir, RecursiveDeleteOption.ALLOW_INSECURE);
}
public void cleanUp() throws IOException {
keyValueStorage.close();
MoreFiles.deleteRecursively(storageDirectory, RecursiveDeleteOption.ALLOW_INSECURE);
}
@AfterAll
static void afterAll() throws IOException {
support.after();
MoreFiles.deleteRecursively(baseDataDir, RecursiveDeleteOption.ALLOW_INSECURE);
}
@AfterAll
static void afterAll() throws IOException {
support.after();
MoreFiles.deleteRecursively(baseDataDir, RecursiveDeleteOption.ALLOW_INSECURE);
}
@AfterAll
static void afterAll() throws IOException {
support.after();
MoreFiles.deleteRecursively(baseDataDir, RecursiveDeleteOption.ALLOW_INSECURE);
}
@Test
public void testXSDCache() throws IOException, BadLocationException {
String xsdPath = tempDirUri.getPath() + "/tag.xsd";
String xmlPath = tempDirUri.toString() + "/tag.xml";
// Create a XSD file in the temp directory
String xsd = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n" + //
"<xs:schema\r\n" + //
" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\r\n" + //
" elementFormDefault=\"qualified\">\r\n" + //
" <xs:element name=\"root\">\r\n" + //
" <xs:complexType>\r\n" + //
" <xs:sequence>\r\n" + //
" <xs:element name=\"tag\"/>\r\n" + //
" </xs:sequence>\r\n" + //
" </xs:complexType>\r\n" + //
" </xs:element>\r\n" + //
"</xs:schema>";
createFile(xsdPath, xsd);
// Open completion in a XML which is bound to the XML Schema
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n" + //
"<root\r\n" + //
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n" + //
" xsi:noNamespaceSchemaLocation=\"tag.xsd\">\r\n" + //
" | " + // <-- completion must provide tag
"</root>";
XMLAssert.testCompletionFor(xml, null, xmlPath, 5 /* region, endregion, cdata, comment, tag */,
c("tag", "<tag></tag>"));
// Open again the completion to use the cache
XMLAssert.testCompletionFor(xml, null, xmlPath, null, c("tag", "<tag></tag>"));
// Change the content of the XSD on the file system
xsd = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n" + //
"<xs:schema\r\n" + //
" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\r\n" + //
" elementFormDefault=\"qualified\">\r\n" + //
" <xs:element name=\"root\">\r\n" + //
" <xs:complexType>\r\n" + //
" <xs:sequence>\r\n" + //
" <xs:element name=\"label\"/>\r\n" + // <-- change tag by label
" </xs:sequence>\r\n" + //
" </xs:complexType>\r\n" + //
" </xs:element>\r\n" + //
"</xs:schema>";
updateFile(xsdPath, xsd);
XMLAssert.testCompletionFor(xml, null, xmlPath, 5 /* region, endregion, cdata, comment, label */,
c("label", "<label></label>"));
// Open again the completion to use the cache
XMLAssert.testCompletionFor(xml, null, xmlPath, 5, c("label", "<label></label>"));
// delete the XSD file
MoreFiles.deleteRecursively(new File(xsdPath).toPath(), RecursiveDeleteOption.ALLOW_INSECURE);
// Completion must be empty
XMLAssert.testCompletionFor(xml, null, xmlPath, 4 /* region, endregion, cdata, comment */);
// recreate the XSD file
createFile(xsdPath, xsd);
XMLAssert.testCompletionFor(xml, null, xmlPath, 5 /* region, endregion, cdata, comment, label */,
c("label", "<label></label>"));
XMLAssert.testCompletionFor(xml, null, xmlPath, 5 /* region, endregion, cdata, comment, label */,
c("label", "<label></label>"));
}
private static void deleteTempDirIfExists() throws IOException {
File tempDir = new File(tempDirUri);
if (tempDir.exists()) {
MoreFiles.deleteRecursively(tempDir.toPath(), RecursiveDeleteOption.ALLOW_INSECURE);
}
}
@AfterClass
public static void cleanUp() throws IOException {
// Mac's APFS fails with InsecureRecursiveDeleteException without ALLOW_INSECURE.
// Still safe as this test does not use symbolic links
MoreFiles.deleteRecursively(outputDirectory, RecursiveDeleteOption.ALLOW_INSECURE);
}
@AfterClass
public static void cleanUp() throws IOException {
// Mac's APFS fails with InsecureRecursiveDeleteException without ALLOW_INSECURE.
// Still safe as this test does not use symbolic links
MoreFiles.deleteRecursively(outputDirectory, RecursiveDeleteOption.ALLOW_INSECURE);
}
/** Download and install a new Cloud SDK. */
public Path install(
final ProgressListener progressListener, final ConsoleListener consoleListener)
throws IOException, InterruptedException, SdkInstallerException, CommandExecutionException,
CommandExitException {
FileResourceProvider fileResourceProvider =
fileResourceProviderFactory.newFileResourceProvider();
// Cleanup, remove old downloaded archive if exists
if (Files.isRegularFile(fileResourceProvider.getArchiveDestination())) {
logger.info("Removing stale archive: " + fileResourceProvider.getArchiveDestination());
Files.delete(fileResourceProvider.getArchiveDestination());
}
// Cleanup, remove old SDK directory if exists
if (Files.exists(fileResourceProvider.getArchiveExtractionDestination())) {
logger.info(
"Removing stale install: " + fileResourceProvider.getArchiveExtractionDestination());
MoreFiles.deleteRecursively(
fileResourceProvider.getArchiveExtractionDestination(),
RecursiveDeleteOption.ALLOW_INSECURE);
}
progressListener.start("Installing Cloud SDK", installerFactory != null ? 300 : 200);
// download and verify
Downloader downloader =
downloaderFactory.newDownloader(
fileResourceProvider.getArchiveSource(),
fileResourceProvider.getArchiveDestination(),
progressListener.newChild(100));
downloader.download();
if (!Files.isRegularFile(fileResourceProvider.getArchiveDestination())) {
throw new SdkInstallerException(
"Download succeeded but valid archive not found at "
+ fileResourceProvider.getArchiveDestination());
}
try {
// extract and verify
extractorFactory
.newExtractor(
fileResourceProvider.getArchiveDestination(),
fileResourceProvider.getArchiveExtractionDestination(),
progressListener.newChild(100))
.extract();
if (!Files.isDirectory(fileResourceProvider.getExtractedSdkHome())) {
throw new SdkInstallerException(
"Extraction succeeded but valid sdk home not found at "
+ fileResourceProvider.getExtractedSdkHome());
}
} catch (UnknownArchiveTypeException e) {
// fileResourceProviderFactory.newFileResourceProvider() creates a fileResourceProvider that
// returns either .tar.gz or .zip for getArchiveDestination().
throw new RuntimeException(e);
}
// install if necessary
if (installerFactory != null) {
installerFactory
.newInstaller(
fileResourceProvider.getExtractedSdkHome(),
progressListener.newChild(100),
consoleListener)
.install();
}
// verify final state
if (!Files.isRegularFile(fileResourceProvider.getExtractedGcloud())) {
throw new SdkInstallerException(
"Installation succeeded but gcloud executable not found at "
+ fileResourceProvider.getExtractedGcloud());
}
progressListener.done();
return fileResourceProvider.getExtractedSdkHome();
}
private void cleanUp(final Path target) throws IOException {
MoreFiles.deleteRecursively(target, RecursiveDeleteOption.ALLOW_INSECURE);
}