Java Code Examples for org.apache.commons.io.FileUtils.deleteDirectory()

The following are Jave code examples for showing how to use deleteDirectory() of the org.apache.commons.io.FileUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: dremio-oss   File: LocalSyncableFileSystem.java   View Source Code Vote up 8 votes
@Override
public boolean delete(Path path, boolean b) throws IOException {
  path = localize(path);
  File file = new File(path.toString());
  if (b) {
    if (file.isDirectory()) {
      FileUtils.deleteDirectory(file);
    } else {
      file.delete();
    }
  } else if (file.isDirectory()) {
    throw new IOException("Cannot delete directory");
  }
  file.delete();
  return true;
}
 
Example 2
Project: accumulo-delimited-ingest   File: DelimitedIngestMiniClusterTest.java   View Source Code Vote up 6 votes
@BeforeClass
public static void startMiniCluster() throws Exception {
  File targetDir = new File(System.getProperty("user.dir"), "target");
  File macDir = new File(targetDir, DelimitedIngestMiniClusterTest.class.getSimpleName() + "_cluster");
  if (macDir.exists()) {
    FileUtils.deleteDirectory(macDir);
  }
  MiniAccumuloConfigImpl config = new MiniAccumuloConfigImpl(macDir, ROOT_PASSWORD);
  config.setNumTservers(1);
  config.setInstanceName(INSTANCE_NAME);
  config.setSiteConfig(Collections.singletonMap("fs.file.impl", RawLocalFileSystem.class.getName()));
  config.useMiniDFS(true);
  MAC = new MiniAccumuloClusterImpl(config);
  MAC.start();
  FS = FileSystem.get(MAC.getMiniDfs().getConfiguration(0));

  ARGS = new DelimitedIngestArguments();
  ARGS.setUsername("root");
  ARGS.setPassword(ROOT_PASSWORD);
  ARGS.setInstanceName(INSTANCE_NAME);
  ARGS.setZooKeepers(MAC.getZooKeepers());
  ARGS.setConfiguration(MAC.getMiniDfs().getConfiguration(0));
}
 
Example 3
Project: airsonic   File: TestCaseUtils.java   View Source Code Vote up 6 votes
/**
 * Cleans the AIRSONIC_HOME directory used for tests.
 *
 * @throws IOException
   */
public static void cleanAirsonicHomeForTest() throws IOException {

  File airsonicHomeDir = new File(airsonicHomePathForTest());
  if (airsonicHomeDir.exists() && airsonicHomeDir.isDirectory()) {
    System.out.println("Delete airsonic home (ie. "+airsonicHomeDir.getAbsolutePath()+").");
    try {
      FileUtils.deleteDirectory(airsonicHomeDir);
    } catch (IOException e) {
      System.out.println("Error while deleting airsonic home.");
      e.printStackTrace();
      throw e;
    }
  }

}
 
Example 4
Project: directory-mavibot   File: PersistedBTreeTransactionTest.java   View Source Code Vote up 6 votes
@After
public void cleanup() throws IOException
{
    btreeNoTransactions.close();
    btreeWithTransactions.close();

    recordManagerNoTxn.close();
    recordManagerTxn.close();
    
    assertTrue( recordManagerNoTxn.isContextOk() );
    assertTrue( recordManagerTxn.isContextOk() );

    if ( dataDirNoTxn.exists() )
    {
        FileUtils.deleteDirectory( dataDirNoTxn );
    }

    if ( dataDirWithTxn.exists() )
    {
        FileUtils.deleteDirectory( dataDirWithTxn );
    }
}
 
Example 5
Project: goobi-viewer-indexer   File: Utils.java   View Source Code Vote up 5 votes
/**
 * 
 * @param path {@link File}
 * @return boolean
 */
public static boolean deleteDirectory(Path path) {
    if (Files.isDirectory(path)) {
        try {
            FileUtils.deleteDirectory(path.toFile());
            return true;
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }

    return false;
}
 
Example 6
Project: iosched-reader   File: DiskLruCacheTest.java   View Source Code Vote up 5 votes
/** @see <a href="https://github.com/JakeWharton/DiskLruCache/issues/2">Issue #2</a> */
@Test public void aggressiveClearingHandlesEdit() throws Exception {
  set("a", "a", "a");
  DiskLruCache.Editor a = cache.get("a").edit();
  FileUtils.deleteDirectory(cacheDir);
  a.set(1, "a2");
  a.commit();
}
 
Example 7
Project: oxygen-git-plugin   File: GItAccessStagedFilesTest.java   View Source Code Vote up 5 votes
@After
public void freeResources() {
	gitAccess.close();
	File dirToDelete = new File(LOCAL_TEST_REPOSITPRY);
	try {
		FileUtils.deleteDirectory(dirToDelete);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 8
Project: iaac4j.aliyun   File: GitLoader.java   View Source Code Vote up 5 votes
/**
 * 从指定的git仓库地址(目前仅支持http和https)和文件名获取资源,通过UsernameCredential支持鉴权
 * @return 资源的字符串
 * @throws Exception 资源不存在或网络不通
 */
@Override
public String load() throws Exception {
    //本地临时目录,用户存放clone的代码
    String tempDirPath = localPath + "/iaac.aliyun.tmp_" + new Date().getTime();
    File tempDir = new File(tempDirPath);
    tempDir.mkdirs();
    String result = null;
    try {
        CloneCommand clone = Git.cloneRepository();
        clone.setURI(url);
        clone.setBranch(this.branch);
        clone.setDirectory(tempDir);

        //设置鉴权
        if (this.credential != null) {
            UsernamePasswordCredentialsProvider usernamePasswordCredentialsProvider = new
                    UsernamePasswordCredentialsProvider(this.credential.getUsername(), this.credential.getPassword());
            //git仓库地址
            clone.setCredentialsProvider(usernamePasswordCredentialsProvider);
        }
        //执行clone
        Git git = clone.call();
        //从本地路径中获取指定的文件
        File file = new File(tempDir.getAbsolutePath() + "/" + this.fileName);
        //返回文件的字符串
        result = FileUtils.readFileToString(file, "utf-8");
    } catch (Exception e) {
        throw e;
    } finally {
        //清除本地的git临时目录
        FileUtils.deleteDirectory(tempDir);
    }
    return result;
}
 
Example 9
Project: Cognizant-Intelligent-Test-Scripter   File: FileOptions.java   View Source Code Vote up 5 votes
public static void moveDirectory(String source, String destination) {
    File sourceFile = new File(source);
    File destFile = new File(destination);
    try {
        if (sourceFile.exists()) {
            FileUtils.copyDirectoryToDirectory(sourceFile, destFile.getParentFile());
            FileUtils.deleteDirectory(sourceFile);
        }
    } catch (IOException ex) {
        Logger.getLogger(FileOptions.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example 10
Project: bootstrap   File: TAbstractSeleniumTest.java   View Source Code Vote up 5 votes
@SuppressWarnings("unchecked")
@Test
public void testScreenShotIOE() throws URISyntaxException, IOException {
	try {
		Mockito.when(mockDriver.getScreenshotAs(ArgumentMatchers.any(OutputType.class)))
				.thenReturn(new File(Thread.currentThread().getContextClassLoader().getResource("log4j2.json").toURI()).getParentFile());
		screenshot("test.png");
		Assert.assertFalse(new File(baseDir, "sc/test.png").exists());
	} finally {
		FileUtils.deleteDirectory(new File(baseDir, "sc"));
	}
}
 
Example 11
Project: CloudNet   File: CommandClearCache.java   View Source Code Vote up 5 votes
@Override
public void onExecuteCommand(CommandSender sender, String[] args)
{
    try{

        FileUtils.deleteDirectory(new File("local/cache"));
        Files.createDirectories(Paths.get("local/cache/web_templates"));
        Files.createDirectories(Paths.get("local/cache/web_plugins"));

    }catch (Exception ex){
        ex.printStackTrace();
    }

    sender.sendMessage("The Cache was cleared!");
}
 
Example 12
Project: xtf   File: LogCleaner.java   View Source Code Vote up 5 votes
/**
 * Cleans pod logs directories.
 *
 * <p>
 * In case of {@link IOException}, the exception is logged and ignored.
 * </p>
 */
public static void cleanPodLogDirectories() {
	final File podLogsDir = OpenshiftUtil.getPodLogsDir().toFile();
	log.info("action=clean-pod-logs status=START dir={}", podLogsDir.getAbsolutePath());
	try {
		if (podLogsDir.exists()) {
			FileUtils.deleteDirectory(podLogsDir);
		}
		podLogsDir.mkdirs();
		log.info("action=clean-pod-logs status=FINISH dir={}", podLogsDir.getAbsolutePath());
	} catch (IOException e) {
		log.error("action=clean-pod-logs status=ERROR dir={}", podLogsDir.getAbsolutePath(), e);
	}
}
 
Example 13
Project: hadoop-oss   File: TestShell.java   View Source Code Vote up 5 votes
@Test
public void testBinWinUtilsNotAFile() throws Throwable {
  try {
    File bin = new File(methodDir, "bin");
    File winutils = new File(bin, WINUTILS_EXE);
    winutils.mkdirs();
    assertWinutilsResolveFailed(methodDir, E_NOT_EXECUTABLE_FILE);
  } finally {
    FileUtils.deleteDirectory(methodDir);
  }
}
 
Example 14
Project: TextDisplayer   File: ClearGui.java   View Source Code Vote up 5 votes
private void clear() {
    boolean failed = false;

    TextDisplayerMod.getInstance().getLoader().getMessages().clear();
    try {
        FileUtils.deleteDirectory(TextDisplayerMod.getInstance().getLoader().getMainDir());
    } catch (IOException ex) {
        failed = true;
    }

    log(failed ? "Failed to clear all display messages" : "Removed all display messages!");
    displayPrevious(failed ? "Failed to clear messages!" : "&aSuccesfully removed all messages!");
}
 
Example 15
Project: traildb-java   File: TrailDBTest.java   View Source Code Vote up 5 votes
@After
public void tearDown() throws IOException {

    // Clear the TrailDB files/directories created for the tests.
    final File f = new File(this.path + ".tdb");
    if (f.exists() && !f.isDirectory()) {
        f.delete();
    }
    FileUtils.deleteDirectory(new File(this.path));
    this.db.close();
}
 
Example 16
Project: AthenaX   File: EmbeddedZooKeeper.java   View Source Code Vote up 4 votes
@Override
public void close() throws IOException {
  zookeeper.shutdown();
  factory.shutdown();
  FileUtils.deleteDirectory(tmpDir);
}
 
Example 17
Project: flow-platform   File: PluginServiceImpl.java   View Source Code Vote up 4 votes
private void pushArtifactsToLocalRepo(Plugin plugin) {
    try {

        String latestGitTag = plugin.getTag();

        Path cachePath = gitCachePath(plugin);

        // default outputs is dist folder
        Path artifactPath = Paths.get(cachePath.toString(), DIST);

        // create tmp folder to store build outputs
        Path tmp = Paths.get(gitCacheWorkspace.toString(), "tmp");
        if (!tmp.toFile().exists()) {
            Files.createDirectories(tmp);
        }

        // move artifacts to tmp folder
        Path actPath = Paths.get(tmp.toString(), DIST);
        if (actPath.toFile().exists()) {
            FileUtils.deleteDirectory(actPath.toFile());
        }
        FileUtils.moveDirectory(artifactPath.toFile(), actPath.toFile());

        Path localPath = gitRepoPath(plugin);

        // init git and push tags
        JGitUtil.init(actPath, false);
        JGitUtil.remoteSet(actPath, LOCAL_REMOTE, localPath.toString());
        Git git = Git.open(actPath.toFile());

        git.add()
            .addFilepattern(".")
            .call();

        git.commit()
            .setMessage("add build outputs")
            .call();

        git.tag()
            .setName(plugin.getTag())
            .setMessage("add " + plugin.getTag())
            .call();

        JGitUtil.push(actPath, LOCAL_REMOTE, latestGitTag);
        // set currentTag latestTag
        plugin.setCurrentTag(latestGitTag);
        updatePluginStatus(plugin, INSTALLED);

        // delete path
        FileUtils.deleteDirectory(actPath.toFile());
    } catch (Throwable e) {

    }

}
 
Example 18
Project: obevo   File: HsqlDeployerTest.java   View Source Code Vote up 4 votes
@Test
public void testDeploy() throws Exception {
    DbEnvironment env = DbEnvironmentFactory.getInstance().readOneFromSourcePath("./src/test/resources/platforms/hsql");
    DbDeployerAppContext context = env.buildAppContext("sa", "");

    context.setupEnvInfra();
    context.cleanEnvironment();
    context.deploy();
    // do a clean and deploy again to ensure that the clean functionality works
    context.cleanEnvironment();
    context.deploy();

    this.setup();
    // simple test to assert that the table has been created
    int result;
    Connection conn = context.getDataSource().getConnection();
    try {
        result = this.jdbc.queryForInt(conn, "select count(*) from SCHEMA1.TABLE_A");
        assertEquals(3, result);
        result = this.jdbc.queryForInt(conn, "select count(*) from SCHEMA1.VIEW1");
        assertEquals(3, result);
        // String columnListSql =
        // "select name from syscolumns where id in (select id from sysobjects where name = 'TEST_TABLE')";
        // List<String> columnsInTestTable = db2JdbcTemplate.query(columnListSql, new SingleColumnRowMapper<String>());
        // Assert.assertEquals(Lists.mutable.with("ID", "STRING", "MYNEWCOL"), FastList.newList(columnsInTestTable));
    } finally {
        DbUtils.closeQuietly(conn);
    }


    // Test out reverse engineering
    AquaRevengArgs args = new AquaRevengArgs();
    args.setDbSchema("SCHEMA1");
    args.setGenerateBaseline(false);
    //args.setJdbcUrl("jdbc:hsqldb:hsql://localhost:9092/myserver");
    args.setJdbcUrl(env.getJdbcUrl());
    args.setUsername("sa");
    args.setPassword("");

    File outputDir = new File("./target/outputRevengNew");
    FileUtils.deleteDirectory(outputDir);
    args.setOutputPath(outputDir);

    env.getPlatform().getDdlReveng().reveng(args);
}
 
Example 19
Project: csap-core   File: Source_Control_Test.java   View Source Code Vote up 4 votes
@Ignore // requires a legit id for checkout
@Test
public void verify_svn_checkout_of_service ()
		throws Exception {

	String rawPass = scmPass;
	assertThat( rawPass ).isNotEqualTo( "FIXME" ).as( "Update the password" );

	String svnBranch = "trunk";
	String svcName = "TestCheckoutFolder";

	File svnCheckoutFolder = new File( Application.BUILD_DIR + svcName );
	FileUtils.deleteDirectory( svnCheckoutFolder );
	// InstanceConfig instanceConfig=
	// csapApp.getServiceInstance("CsAgent_8011");
	ServiceInstance instanceConfig = new ServiceInstance();
	instanceConfig.setScmLocation( "https://svn.yourcompany.com/svn/csap/trunk/public/javaProjects/BootReference" );
	instanceConfig.setScm( SourceControlManager.ScmProvider.svn.key );

	String encryptedPass = encryptor.encrypt( rawPass ); // immediately

	// BufferedWriter outputWriter = new BufferedWriter(new
	// OutputStreamWriter(System.out));
	// OutputFileMgr outputManager = new OutputFileMgr(
	// csapApp.getProcessingDir(),
	// "unitTestFor" + this.getClass().getSimpleName() );
	StringWriter sw = new StringWriter();
	BufferedWriter stringWriter = new BufferedWriter( sw );

	sourceControlManager.checkOutFolder( scmUserid, encryptedPass, svnBranch, svcName,
		instanceConfig, stringWriter );

	assertThat( svnCheckoutFolder )
		.as( "checkout folder created" )
		.exists();

	assertTrue( "SVn Checkout folder created",
		svnCheckoutFolder.exists() );
	// FileUtils.deleteDirectory(svnCheckoutFolder);
	stringWriter.flush();
	String results = sw.toString();
	logger.info( "output messages: {}", results );

	assertThat( results )
		.as( "svn messages" )
		.contains(
			"Checking out: https://svn.yourcompany.com/svn/csap/trunk/public/javaProjects/BootReference" );

}
 
Example 20
Project: amanda   File: FileSystemStorageServiceTest.java   View Source Code Vote up 4 votes
@Test
public void testDelete() throws IOException {
    String pathStr = "F:\\Development\\DevProjects\\amanda\\upload-dir\\2016\\06";
    Path path = Paths.get(pathStr);
    FileUtils.deleteDirectory(path.toFile());
}