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

The following examples show how to use org.apache.commons.io.FileUtils#forceDelete() . 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: TestFilePrivateKeyDataProvider.java    From java-license-manager with Apache License 2.0 6 votes vote down vote up
@Test
public void testKeyFile01() throws IOException
{
    final String fileName = "testKeyFile01.key";
    File file = new File(fileName);

    if(file.exists())
    {
        FileUtils.forceDelete(file);
    }

    FilePrivateKeyDataProvider provider = new FilePrivateKeyDataProvider(fileName);

    assertNotNull("The key file should not be null.", provider.getPrivateKeyFile());
    assertEquals("The key file is not correct.", file.getAbsoluteFile(), provider.getPrivateKeyFile());
    assertNotEquals("The paths should not be the same.", fileName, provider.getPrivateKeyFile().getPath());
    assertTrue("The paths should end the same.", provider.getPrivateKeyFile().getPath().endsWith(fileName));
}
 
Example 2
Source File: ShutdownManager.java    From hub-detect with Apache License 2.0 6 votes vote down vote up
public void cleanup(File directory, List<File> skip) throws IOException {
    IOException exception = null;
    for (final File file : directory.listFiles()) {
        try {
            if (skip.contains(file)) {
                logger.debug("Skipping cleanup for: " + file.getAbsolutePath());
            } else {
                logger.debug("Cleaning up: " + file.getAbsolutePath());
                FileUtils.forceDelete(file);
            }
        } catch (final IOException ioe) {
            exception = ioe;
        }
    }

    if (null != exception) {
        throw exception;
    }
}
 
Example 3
Source File: SpringMvcTest.java    From swagger-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Override
@BeforeMethod
   protected void setUp() throws Exception {
   	extensions = new ArrayList<SwaggerExtension>(SwaggerExtensions.getExtensions());
   	super.setUp();

       try {
           FileUtils.deleteDirectory(swaggerOutputDir);
           FileUtils.forceDelete(docOutput);
       } catch (Exception e) {
           //ignore
       }

       File testPom = new File(getBasedir(), "target/test-classes/plugin-config-springmvc.xml");
       mojo = (ApiDocumentMojo) lookupMojo("generate", testPom);
   }
 
Example 4
Source File: DeleteUpgradeOperation.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void execute(final String site) throws UpgradeException {
    for (String path : paths) {
        try {
            Path pathToDelete = Paths.get(getRepositoryPath(site).getParent().toAbsolutePath().toString(), path);
            File f = pathToDelete.toFile();
            if (f.exists()) {
                FileUtils.forceDelete(f);
            }
        } catch (Exception e) {
            throw new UpgradeException("Error deleting path " + path + " to path for repo " +
                    (StringUtils.isEmpty(site) ? "global" : site), e);
        }
    }

    commitAllChanges(site);

}
 
Example 5
Source File: WatchDirTest.java    From n2o-framework with Apache License 2.0 6 votes vote down vote up
/**
 * проверить что работает перезапуск
 * <p/>
 * не реагирует на события
 * запуск
 * реагирует на события
 * остановка
 * не реагирует на события
 * запуск
 * реагирует на события
 *
 */
@Test
@Ignore
public void testRestartMonitoring() throws Exception
{
    FileUtils.touch(new File(path.toString()));
    verify(listener, timeout(100).never()).fileCreated(eq(path));

    reset(listener);
    watchDir.start();

    FileUtils.forceDelete(new File(path.toString()));
    verify(listener, timeout(100).atLeast(1)).fileDeleted(eq(path));

    reset(listener);
    watchDir.stop();

    FileUtils.touch(new File(path.toString()));
    verify(listener, timeout(100).never()).fileCreated(eq(path));
}
 
Example 6
Source File: DefaultTopologyService.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
public void deployTopology(Topology t){

  try {
    File temp = new File(topologiesDirectory.getAbsolutePath() + "/" + t.getName() + ".xml.temp");
    Marshaller mr = jaxbContext.createMarshaller();

    mr.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    mr.marshal(t, temp);

    File topology = new File(topologiesDirectory.getAbsolutePath() + "/" + t.getName() + ".xml");
    if(!temp.renameTo(topology)) {
      FileUtils.forceDelete(temp);
      throw new IOException("Could not rename temp file");
    }

    // This code will check if the topology is valid, and retrieve the errors if it is not.
    TopologyValidator validator = new TopologyValidator( topology.getAbsolutePath() );
    if( !validator.validateTopology() ){
      throw new SAXException( validator.getErrorString() );
    }


  } catch (JAXBException | SAXException | IOException e) {
    auditor.audit(Action.DEPLOY, t.getName(), ResourceType.TOPOLOGY, ActionOutcome.FAILURE);
    log.failedToDeployTopology(t.getName(), e);
  }
  reloadTopologies();
}
 
Example 7
Source File: TestFlumeEventAvroEventSerializer.java    From mt-flume with Apache License 2.0 5 votes vote down vote up
@Test
public void testAvroSerializer()
    throws FileNotFoundException, IOException {

  createAvroFile(TESTFILE, null);
  validateAvroFile(TESTFILE);
  FileUtils.forceDelete(TESTFILE);
}
 
Example 8
Source File: RheaKVTestCluster.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
protected void shutdown() throws IOException {
    System.out.println("RheaKVTestCluster shutdown ...");
    for (RheaKVStore store : stores) {
        store.shutdown();
    }
    if (this.tempDbPath != null) {
        System.out.println("removing dir: " + this.tempDbPath);
        FileUtils.forceDelete(new File(this.tempDbPath));
    }
    if (this.tempRaftPath != null) {
        System.out.println("removing dir: " + this.tempRaftPath);
        FileUtils.forceDelete(new File(this.tempRaftPath));
    }
    System.out.println("RheaKVTestCluster shutdown complete");
}
 
Example 9
Source File: AbstractProjectsManagerBasedTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@After
public void cleanUp() throws Exception {
	JavaLanguageServerPlugin.setPreferencesManager(oldPreferenceManager);
	projectsManager = null;
	Platform.removeLogListener(logListener);
	logListener = null;
	WorkspaceHelper.deleteAllProjects();
	FileUtils.forceDelete(getWorkingProjectDirectory());
	Job.getJobManager().setProgressProvider(null);
	JobHelpers.waitForJobsToComplete();
}
 
Example 10
Source File: GFileUtils.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void forceDelete(File file) {
    try {
        FileUtils.forceDelete(file);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 11
Source File: PinotDataBufferTest.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
@Test
public void testPinotByteBuffer()
    throws Exception {
  try (PinotDataBuffer buffer = PinotByteBuffer.allocateDirect(BUFFER_SIZE, ByteOrder.BIG_ENDIAN)) {
    testPinotDataBuffer(buffer);
  }
  try (PinotDataBuffer buffer = PinotByteBuffer.allocateDirect(BUFFER_SIZE, ByteOrder.LITTLE_ENDIAN)) {
    testPinotDataBuffer(buffer);
  }
  try (RandomAccessFile randomAccessFile = new RandomAccessFile(TEMP_FILE, "rw")) {
    randomAccessFile.setLength(FILE_OFFSET + BUFFER_SIZE);
    try (PinotDataBuffer buffer = PinotByteBuffer
        .loadFile(TEMP_FILE, FILE_OFFSET, BUFFER_SIZE, ByteOrder.BIG_ENDIAN)) {
      testPinotDataBuffer(buffer);
    }
    try (PinotDataBuffer buffer = PinotByteBuffer
        .loadFile(TEMP_FILE, FILE_OFFSET, BUFFER_SIZE, ByteOrder.LITTLE_ENDIAN)) {
      testPinotDataBuffer(buffer);
    }
    try (PinotDataBuffer buffer = PinotByteBuffer
        .mapFile(TEMP_FILE, false, FILE_OFFSET, BUFFER_SIZE, ByteOrder.BIG_ENDIAN)) {
      testPinotDataBuffer(buffer);
    }
    try (PinotDataBuffer buffer = PinotByteBuffer
        .mapFile(TEMP_FILE, false, FILE_OFFSET, BUFFER_SIZE, ByteOrder.LITTLE_ENDIAN)) {
      testPinotDataBuffer(buffer);
    }
  } finally {
    FileUtils.forceDelete(TEMP_FILE);
  }
}
 
Example 12
Source File: GFileUtils.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void forceDelete(File file) {
    try {
        FileUtils.forceDelete(file);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 13
Source File: TestFilePrivateKeyDataProvider.java    From java-license-manager with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetEncryptedPrivateKeyData04() throws IOException
{
    final String fileName = "testGetEncryptedPrivateKeyData04.key";
    File file = new File(fileName);

    if(file.exists())
    {
        FileUtils.forceDelete(file);
    }

    byte[] data = new byte[] {0x51, 0x12, 0x23};

    FileUtils.writeByteArrayToFile(file, data);

    try
    {
        FilePrivateKeyDataProvider provider = new FilePrivateKeyDataProvider(file);

        byte[] returnedData = provider.getEncryptedPrivateKeyData();

        assertNotNull("The data should not be null.", returnedData);
        assertArrayEquals("The data is not correct.", data, returnedData);
    }
    finally
    {
        FileUtils.forceDelete(file);
    }
}
 
Example 14
Source File: HodFindApplicationTest.java    From find with MIT License 4 votes vote down vote up
@AfterClass
public static void destroy() throws IOException {
    FileUtils.forceDelete(new File(TEST_DIR));
}
 
Example 15
Source File: GearSpecManager.java    From Plugin with MIT License 4 votes vote down vote up
private static Boolean updateInstallProjectSettingsForJar(GearSpec selectedSpec, Module module){
    //Get build file
    File buildFile = new File(new File(module.getModuleFilePath()).getParentFile().getAbsolutePath() + Utils.pathSeparator() + "build.gradle");

    if (buildFile.exists()){
        //Create comment string
        String commentString = "\n/////////////////////\n" +
                "// Gears Dependencies\n" +
                "/////////////////////";

        try {
            //Read the build file
            String buildFileString = FileUtils.readFileToString(buildFile);

            //Create new addition
            String dependencyString = "\ndependencies{compile fileTree(dir: '../Gears/Jars/"+selectedSpec.getName()+"/"+selectedSpec.getVersion()+"', include: ['*.jar'])}";

            //If the build file doesn't contain the jar dependency, go ahead and add it
            if (!buildFileString.contains(dependencyString)){
                int commentIndex = buildFileString.lastIndexOf(commentString);

                //If the comment exists...
                if (commentIndex != -1){
                    buildFileString = buildFileString.concat(dependencyString);
                }
                else {
                    buildFileString = buildFileString.concat(commentString+dependencyString);
                }

                //Write changes to settings.gradle
                FileUtils.forceDelete(buildFile);
                FileUtils.write(buildFile, buildFileString);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
    else {
        return false;
    }



    return true;
}
 
Example 16
Source File: TestConsoleLicenseGenerator.java    From java-license-manager with Apache License 2.0 4 votes vote down vote up
@Test
public void testInitializeLicenseCreator03() throws Exception
{
    this.resetLicenseCreator();

    String fileName = "testInitializeLicenseCreator03.properties";
    File file = new File(fileName);
    if(file.exists())
    {
        FileUtils.forceDelete(file);
    }

    FileUtils.writeStringToFile(
        file,
        "io.oddsource.java.licensing.privateKeyFile=testInitializeLicenseCreator03.key\r\n" +
        "io.oddsource.java.licensing.privateKeyPassword=testPassword03",
        StandardCharsets.UTF_8
    );

    this.console.setCli(
        EasyMock.createMockBuilder(CommandLine.class).withConstructor().
            addMockedMethod("hasOption", String.class).
            addMockedMethod("getOptionValue", String.class).
            createStrictMock()
    );

    EasyMock.expect(this.console.getCli().hasOption("config")).andReturn(true);
    EasyMock.expect(this.console.getCli().getOptionValue("config")).andReturn(fileName);

    EasyMock.replay(this.console.getCli(), this.device);

    try
    {
        this.console.initializeLicenseCreator();
        fail("Expected exception FileNotFoundException.");
    }
    catch(FileNotFoundException expected)
    {
    }
    finally
    {
        this.resetLicenseCreator();

        FileUtils.forceDelete(file);

        EasyMock.verify(this.console.getCli());
    }
}
 
Example 17
Source File: MSF4JDependencyResolverJob.java    From msf4j with Apache License 2.0 4 votes vote down vote up
private IWorkspaceRoot resourceAlteration() throws IOException, CoreException, JavaModelException {
	// Renaming generated folder structure to match with WSO2
	// conventional directory structure
	IWorkspaceRoot workspace = ResourcesPlugin.getWorkspace().getRoot();
	IProject project = workspace.getProject(msf4jArtifactModel.getProjectName());
	msf4jArtifactModel.setProject(project);
	IFolder resourceFolder = ProjectUtils.getWorkspaceFolder(msf4jArtifactModel.getProject(), SRC_DIRECTORY,
			MAIN_DIRECTORY);
	File resourcePhysicalFolder = resourceFolder.getRawLocation().makeAbsolute().toFile();
	File newResourcePhysicalFolder = new File(
			resourcePhysicalFolder.getParent() + File.separator + RESOURCES_DIRECTORY);
	resourcePhysicalFolder.renameTo(newResourcePhysicalFolder);

	IFolder sourceFolder = ProjectUtils.getWorkspaceFolder(msf4jArtifactModel.getProject(), SRC_DIRECTORY,
			GEN_DIRECTORY);
	File sourcePhysicalFolder = sourceFolder.getRawLocation().makeAbsolute().toFile();
	File newSourcePhysicalFolder = new File(sourcePhysicalFolder.getParent() + File.separator + MAIN_DIRECTORY);
	sourcePhysicalFolder.renameTo(newSourcePhysicalFolder);

	// Moving src/resources to src/main
	resourceFolder = ProjectUtils.getWorkspaceFolder(msf4jArtifactModel.getProject(), SRC_DIRECTORY,
			RESOURCES_DIRECTORY);
	resourcePhysicalFolder = resourceFolder.getRawLocation().makeAbsolute().toFile();
	sourceFolder = ProjectUtils.getWorkspaceFolder(msf4jArtifactModel.getProject(), SRC_DIRECTORY, MAIN_DIRECTORY);
	sourcePhysicalFolder = sourceFolder.getRawLocation().makeAbsolute().toFile();
	FileUtils.moveDirectoryToDirectory(resourcePhysicalFolder, sourcePhysicalFolder, true);

	// Adding Java support to the source folder src/main/java
	// delete the project target folder
	IFolder targetFolder = ProjectUtils.getWorkspaceFolder(msf4jArtifactModel.getProject(),
			MSF4JArtifactConstants.TRGET_DIRECTORY);
	targetFolder.delete(true, new NullProgressMonitor());
	IFolder mainFolder = ProjectUtils.getWorkspaceFolder(msf4jArtifactModel.getProject(), SRC_DIRECTORY,
			MAIN_DIRECTORY, JAVA_DIRECTORY);
	JavaUtils.addJavaSupportAndSourceFolder(msf4jArtifactModel.getProject(), mainFolder);

	// removing the webapps folder generated by the tool
	IFolder webAppFolder = ProjectUtils.getWorkspaceFolder(msf4jArtifactModel.getProject(), SRC_DIRECTORY,
			MAIN_DIRECTORY, RESOURCES_DIRECTORY, WEBAPP_DIRECTORY);
	File webAppPhysicalFolder = webAppFolder.getRawLocation().makeAbsolute().toFile();
	if (webAppPhysicalFolder.exists()) {
		FileUtils.forceDelete(webAppPhysicalFolder);
	}

	// removing unnecessary classes generated by the tool
	IProject newMSF4JProject = workspace.getProject(msf4jArtifactModel.getProject().getName());
	String[] filesToBeDeleted = { NOT_FOUND_EXCEPTION_JAVA, API_ORIGIN_FILTER_JAVA, API_RESPONSE_MESSAGE_JAVA,
			API_EXCEPTION_JAVA };

	for (String fileToBeDeleted : filesToBeDeleted) {
		IResource originFilterFile = newMSF4JProject
				.getFile(SRC_DIRECTORY + File.separator + MAIN_DIRECTORY + File.separator + JAVA_DIRECTORY
						+ File.separator + msf4jArtifactModel.getPackageName().replace(".", File.separator)
						+ File.separator + API + File.separator + fileToBeDeleted);
		File fileToDelete = originFilterFile.getRawLocation().makeAbsolute().toFile();
		if (fileToDelete.exists()) {
			FileUtils.forceDelete(fileToDelete);
		}
	}
	ProjectUtils.addNatureToProject(project, false, MAVEN2_PROJECT_NATURE);
	ProjectUtils.addNatureToProject(project, false, MSF4J_PROJECT_NATURE);
	project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
	return workspace;
}
 
Example 18
Source File: KnoxCLITest.java    From knox with Apache License 2.0 4 votes vote down vote up
@Test
public void testRemoteConfigurationRegistryDeleteProviderConfig() throws Exception {
  outContent.reset();

  // Create a provider config
  final String providerConfigName = "my-provider-config.xml";
  final String providerConfigContent = "<gateway/>\n";

  final File testRoot = TestUtils.createTempDir(this.getClass().getName());
  try {
    final File testRegistry = new File(testRoot, "registryRoot");
    final File testProviderConfig = new File(testRoot, providerConfigName);

    final String[] createArgs = {"upload-provider-config", testProviderConfig.getAbsolutePath(),
                                 "--registry-client", "test_client",
                                 "--master", "master"};

    FileUtils.writeStringToFile(testProviderConfig, providerConfigContent, StandardCharsets.UTF_8);

    KnoxCLI cli = new KnoxCLI();
    Configuration config = new GatewayConfigImpl();
    // Configure a client for the test local filesystem registry implementation
    config.set("gateway.remote.config.registry.test_client", "type=LocalFileSystem;address=" + testRegistry);
    cli.setConf(config);

    // Run the test command
    int rc = cli.run(createArgs);

    // Validate the result
    assertEquals(0, rc);
    File registryFile = new File(testRegistry, "knox/config/shared-providers/" + providerConfigName);
    assertTrue(registryFile.exists());

    outContent.reset();

    // Delete the created provider config
    final String[] deleteArgs = {"delete-provider-config", providerConfigName,
                                 "--registry-client", "test_client",
                                 "--master", "master"};
    rc = cli.run(deleteArgs);
    assertEquals(0, rc);
    assertFalse(registryFile.exists());

    // Try to delete a provider config that does not exist
    rc = cli.run(new String[]{"delete-provider-config", "imaginary-providers.xml",
                              "--registry-client", "test_client",
                              "--master", "master"});
    assertEquals(0, rc);
  } finally {
    FileUtils.forceDelete(testRoot);
  }
}
 
Example 19
Source File: FileMetaDir.java    From jackrabbit-filevault with Apache License 2.0 4 votes vote down vote up
public void delete(String name) throws IOException {
    File file = new File(dir, name);
    FileUtils.forceDelete(file);
}
 
Example 20
Source File: AbstractRecordReaderTest.java    From incubator-pinot with Apache License 2.0 4 votes vote down vote up
@AfterClass
public void tearDown()
    throws Exception {
  FileUtils.forceDelete(_tempDir);
}