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

The following are Jave code examples for showing how to use deleteQuietly() 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: atlas   File: PrepareBundleInfoTask.java   View Source Code Vote up 6 votes
private void generateBundleListCfg(AppVariantContext appVariantContext) throws IOException {
    List<String> bundleLists = AtlasBuildContext.awbBundleMap.keySet().stream().map(key -> {
        return "lib/armeabi/" + key;
    }).sorted().collect(Collectors.toList());
    File outputFile = new File(appVariantContext.getScope().getGlobalScope().getOutputsDir(), "bundleList.cfg");
    FileUtils.deleteQuietly(outputFile);
    outputFile.getParentFile().mkdirs();
    FileUtils.writeLines(outputFile, bundleLists);

    appVariantContext.bundleListCfg = outputFile;
    //Set the bundle dependencies

    List<BundleInfo> bundleInfos = new ArrayList<>();
    AtlasBuildContext.awbBundleMap.values().stream().forEach(new Consumer<AwbBundle>() {
        @Override
        public void accept(AwbBundle awbBundle) {
            bundleInfos.add(awbBundle.bundleInfo);
        }
    });

}
 
Example 2
Project: osc-core   File: X509TrustManagerFactory.java   View Source Code Vote up 6 votes
@Override
public void replaceInternalCertificate(File zipFile, boolean doReboot) throws Exception {
    // Disabling reboot for testing.

    if (zipFile == null) {
        throw new Exception(getString(EXCEPTION_KEYPAIR_ZIP_MALFORMED));
    }

    Map<String, File> files = unzipFilePair(zipFile);
    File pKeyFile = files.get(KEY);
    File chainFile = files.get(CERT_CHAIN);
    // File not needed any more.
    FileUtils.deleteQuietly(zipFile);

    replaceInternalCertificate(pKeyFile, chainFile, doReboot);
}
 
Example 3
Project: Apache-Spark-2x-for-Java-Developers   File: SparkWordCount.java   View Source Code Vote up 6 votes
public static void main(String[] args) throws Exception {
	System.out.println(System.getProperty("hadoop.home.dir"));
	String inputPath = args[0];
	String outputPath = args[1];
	FileUtils.deleteQuietly(new File(outputPath));

	JavaSparkContext sc = new JavaSparkContext("local", "sparkwordcount");

	JavaRDD<String> rdd = sc.textFile(inputPath);

	JavaPairRDD<String, Integer> counts = rdd
			.flatMap(x -> Arrays.asList(x.split(" ")).iterator())
			.mapToPair(x -> new Tuple2<String, Integer>((String) x, 1))
			.reduceByKey((x, y) -> x + y);

	counts.saveAsTextFile(outputPath);
	sc.close();
}
 
Example 4
Project: springrestdoc   File: SwaggerToAsciiDocMarkdownConfluence.java   View Source Code Vote up 6 votes
@Test
public void test() throws URISyntaxException {
    //Given
    Path file = Paths.get(SwaggerToAsciiDocMarkdownConfluence.class.getResource(resource).toURI());
    Path outputDirectory = Paths.get(BUILD_SWAGGER_2_MARKUP_PATH + outputPath);
    FileUtils.deleteQuietly(outputDirectory.toFile());

    //When
    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
            .withPathsGroupedBy(GroupBy.TAGS)
            .withOutputLanguage(Language.EN)
            .withMarkupLanguage(markupLanguage)
            .build();

    Swagger2MarkupConverter.from(file)
            .withConfig(config)
            .build()
            .toFolder(outputDirectory);
}
 
Example 5
Project: csap-core   File: Metrics_Publish_Test.java   View Source Code Vote up 6 votes
@Before
public void setUp ()
		throws Exception {

	logger.info( Boot_Container_Test.TC_HEAD + "Deleting: "
			+ csapApp.getHttpdIntegration().getHttpdWorkersFile().getParentFile().getAbsolutePath() );

	Application.setJvmInManagerMode( false );
	csapApp.setAutoReload( false );

	FileUtils.deleteQuietly( csapApp.getHttpdIntegration().getHttpdWorkersFile().getParentFile() );

	// String path =
	// Bootstrap.getThreadContextLoader().getResource("clusterConfig.js").getPath();
	// logger.info(GlobalContextTest.TC_HEAD +
	// "Loading test configuration: \n" + path);
	// File testConfig = new File(path);
	// csapApp.parseConfig(false, testConfig);
}
 
Example 6
Project: CustomWorldGen   File: ResourcePackRepository.java   View Source Code Vote up 6 votes
/**
 * Keep only the 10 most recent resources packs, delete the others
 */
private void deleteOldServerResourcesPacks()
{
    try
    {
        List<File> list = Lists.newArrayList(FileUtils.listFiles(this.dirServerResourcepacks, TrueFileFilter.TRUE, (IOFileFilter)null));
        Collections.sort(list, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
        int i = 0;

        for (File file1 : list)
        {
            if (i++ >= 10)
            {
                LOGGER.info("Deleting old server resource pack {}", new Object[] {file1.getName()});
                FileUtils.deleteQuietly(file1);
            }
        }
    }
    catch (IllegalArgumentException illegalargumentexception)
    {
        LOGGER.error("Error while deleting old server resource pack : {}", new Object[] {illegalargumentexception.getMessage()});
    }
}
 
Example 7
Project: hadoop   File: TestCgroupsLCEResourcesHandler.java   View Source Code Vote up 5 votes
@Test
public void testcheckAndDeleteCgroup() throws Exception {
  CgroupsLCEResourcesHandler handler = new CgroupsLCEResourcesHandler();
  handler.setConf(new YarnConfiguration());
  handler.initConfig();

  FileUtils.deleteQuietly(cgroupDir);
  // Test 0
  // tasks file not present, should return false
  Assert.assertFalse(handler.checkAndDeleteCgroup(cgroupDir));

  File tfile = new File(cgroupDir.getAbsolutePath(), "tasks");
  FileOutputStream fos = FileUtils.openOutputStream(tfile);
  File fspy = Mockito.spy(cgroupDir);

  // Test 1, tasks file is empty
  // tasks file has no data, should return true
  Mockito.stub(fspy.delete()).toReturn(true);
  Assert.assertTrue(handler.checkAndDeleteCgroup(fspy));

  // Test 2, tasks file has data
  fos.write("1234".getBytes());
  fos.close();
  // tasks has data, would not be able to delete, should return false
  Assert.assertFalse(handler.checkAndDeleteCgroup(fspy));
  FileUtils.deleteQuietly(cgroupDir);

}
 
Example 8
Project: hadoop   File: TestNameNodeRecovery.java   View Source Code Vote up 5 votes
/**
 * Create a test configuration that will exercise the initializeGenericKeys
 * code path.  This is a regression test for HDFS-4279.
 */
static void setupRecoveryTestConf(Configuration conf) throws IOException {
  conf.set(DFSConfigKeys.DFS_NAMESERVICES, "ns1");
  conf.set(DFSConfigKeys.DFS_HA_NAMENODE_ID_KEY, "nn1");
  conf.set(DFSUtil.addKeySuffixes(DFSConfigKeys.DFS_HA_NAMENODES_KEY_PREFIX,
    "ns1"), "nn1,nn2");
  String baseDir = System.getProperty(
      MiniDFSCluster.PROP_TEST_BUILD_DATA, "build/test/data") + "/dfs/";
  File nameDir = new File(baseDir, "nameR");
  File secondaryDir = new File(baseDir, "namesecondaryR");
  conf.set(DFSUtil.addKeySuffixes(DFSConfigKeys.
      DFS_NAMENODE_NAME_DIR_KEY, "ns1", "nn1"),
      nameDir.getCanonicalPath());
  conf.set(DFSUtil.addKeySuffixes(DFSConfigKeys.
      DFS_NAMENODE_CHECKPOINT_DIR_KEY, "ns1", "nn1"),
      secondaryDir.getCanonicalPath());
  conf.unset(DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY);
  conf.unset(DFSConfigKeys.DFS_NAMENODE_CHECKPOINT_DIR_KEY);
  FileUtils.deleteQuietly(nameDir);
  if (!nameDir.mkdirs()) {
    throw new RuntimeException("failed to make directory " +
      nameDir.getAbsolutePath());
  }
  FileUtils.deleteQuietly(secondaryDir);
  if (!secondaryDir.mkdirs()) {
    throw new RuntimeException("failed to make directory " +
      secondaryDir.getAbsolutePath());
  }
}
 
Example 9
Project: flume-release-1.7.0   File: TestLog.java   View Source Code Vote up 5 votes
@After
public void cleanup() throws Exception {
  if (log != null) {
    log.close();
  }
  FileUtils.deleteQuietly(checkpointDir);
  for (int i = 0; i < dataDirs.length; i++) {
    FileUtils.deleteQuietly(dataDirs[i]);
  }
}
 
Example 10
Project: hadoop-oss   File: TestShell.java   View Source Code Vote up 5 votes
@Test
public void testBinWinUtilsFound() throws Throwable {
  try {
    File bin = new File(methodDir, "bin");
    File winutils = new File(bin, WINUTILS_EXE);
    touch(winutils);
    assertEquals(winutils.getCanonicalPath(),
        getQualifiedBinInner(methodDir, WINUTILS_EXE).getCanonicalPath());
  } finally {
    FileUtils.deleteQuietly(methodDir);
  }
}
 
Example 11
Project: BaseClient   File: ResourcePackRepository.java   View Source Code Vote up 5 votes
private void func_183028_i()
{
    List<File> list = Lists.newArrayList(FileUtils.listFiles(this.dirServerResourcepacks, TrueFileFilter.TRUE, (IOFileFilter)null));
    Collections.sort(list, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
    int i = 0;

    for (File file1 : list)
    {
        if (i++ >= 10)
        {
            logger.info("Deleting old server resource pack " + file1.getName());
            FileUtils.deleteQuietly(file1);
        }
    }
}
 
Example 12
Project: DecompiledMinecraft   File: ResourcePackRepository.java   View Source Code Vote up 5 votes
private void func_183028_i()
{
    List<File> list = Lists.newArrayList(FileUtils.listFiles(this.dirServerResourcepacks, TrueFileFilter.TRUE, (IOFileFilter)null));
    Collections.sort(list, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
    int i = 0;

    for (File file1 : list)
    {
        if (i++ >= 10)
        {
            logger.info("Deleting old server resource pack " + file1.getName());
            FileUtils.deleteQuietly(file1);
        }
    }
}
 
Example 13
Project: csap-core   File: API_Model.java   View Source Code Vote up 4 votes
@Before
public void setUp() throws Exception {
	logger.info("Deleting: {}",
			csapApp.getHttpdIntegration().getHttpdWorkersFile().getParentFile().getAbsolutePath() );

	Application.setJvmInManagerMode( false );
	csapApp.setAutoReload( false );

	FileUtils.deleteQuietly( csapApp.getHttpdIntegration().getHttpdWorkersFile().getParentFile() );

	File csapApplicationDefinition = new File(
			getClass().getResource( "/org/csap/test/data/test_application_model.json" ).getPath() );

	logger.info("Loading application: {}" + csapApplicationDefinition );


	assertThat( csapApp.loadDefinitionForJunits( false, csapApplicationDefinition ) ).as( "No Errors or warnings" ).isTrue();
	StringBuffer parsingResults = csapApp.getLastTestParseResults() ;

	this.mockMvc = MockMvcBuilders.webAppContextSetup( this.wac ).build();
	csapApp.setTestMode( true );
}
 
Example 14
Project: dhus-core   File: FileSystemDataStoreTest.java   View Source Code Vote up 4 votes
@AfterClass
public void finalize_me()
{
  FileUtils.deleteQuietly (tmp);
  FileUtils.deleteQuietly (incoming_root);
}
 
Example 15
Project: invesdwin-context-r   File: ModifiedTempFileService.java   View Source Code Vote up 4 votes
@Override
protected void finalize() throws Throwable {
    super.finalize();
    FileUtils.deleteQuietly(folder);
}
 
Example 16
Project: dhus-core   File: HierarchicalDirectoryBuilderTest.java   View Source Code Vote up 4 votes
@AfterClass
public void finalize_me()
{
   logger.info ("Removing tmp files.");
   FileUtils.deleteQuietly (tmp);
}
 
Example 17
Project: flume-release-1.7.0   File: TestLog.java   View Source Code Vote up 4 votes
public void doTestReplayFailsWithAllEmptyLogMetaData(boolean useFastReplay)
    throws IOException, InterruptedException {
  // setup log with correct fast replay parameter
  log.close();
  log = new Log.Builder().setCheckpointInterval(1L)
                         .setMaxFileSize(MAX_FILE_SIZE)
                         .setQueueSize(CAPACITY)
                         .setCheckpointDir(checkpointDir)
                         .setLogDirs(dataDirs)
                         .setChannelName("testlog")
                         .setUseFastReplay(useFastReplay)
                         .build();
  log.replay();
  FlumeEvent eventIn = TestUtils.newPersistableEvent();
  long transactionID = ++this.transactionID;
  log.put(transactionID, eventIn);
  log.commitPut(transactionID);
  log.close();
  if (useFastReplay) {
    FileUtils.deleteQuietly(checkpointDir);
    Assert.assertTrue(checkpointDir.mkdir());
  }
  List<File> logFiles = Lists.newArrayList();
  for (int i = 0; i < dataDirs.length; i++) {
    logFiles.addAll(LogUtils.getLogs(dataDirs[i]));
  }
  Assert.assertTrue(logFiles.size() > 0);
  for (File logFile : logFiles) {
    File logFileMeta = Serialization.getMetaDataFile(logFile);
    Assert.assertTrue(logFileMeta.delete());
    Assert.assertTrue(logFileMeta.createNewFile());
  }
  log = new Log.Builder().setCheckpointInterval(1L)
                         .setMaxFileSize(MAX_FILE_SIZE)
                         .setQueueSize(CAPACITY)
                         .setCheckpointDir(checkpointDir)
                         .setLogDirs(dataDirs)
                         .setChannelName("testlog")
                         .setUseFastReplay(useFastReplay)
                         .build();
  try {
    log.replay();
    Assert.fail();
  } catch (IllegalStateException expected) {
    String msg = expected.getMessage();
    Assert.assertNotNull(msg);
    Assert.assertTrue(msg, msg.contains(".meta is empty, but log"));
  }
}
 
Example 18
Project: flume-release-1.7.0   File: TestUseRawLocalFileSystem.java   View Source Code Vote up 4 votes
@After
public void teardown() throws Exception {
  FileUtils.deleteQuietly(baseDir);
}
 
Example 19
Project: atlas   File: JarRefactor.java   View Source Code Vote up 4 votes
private void splitMainJar(List<File> result, File outJar, int index) throws IOException {
    boolean hasClass = false;
    File splitOutJar = new File(outJar.getParentFile(), FileNameUtils.getUniqueJarName(outJar) + "-" + (index + 1) + ".jar");
    File splitOutJarMain = new File(outJar.getParentFile(), FileNameUtils.getUniqueJarName(outJar) + "-" + (index) + ".jar");
    JarOutputStream jos = new JarOutputStream(
            new BufferedOutputStream(new FileOutputStream(splitOutJar)));
    JarOutputStream josMain = new JarOutputStream(
            new BufferedOutputStream(new FileOutputStream(splitOutJarMain)));
    JarFile jarFile = new JarFile(outJar);
    try {


        Enumeration<JarEntry> entryEnumeration = jarFile.entries();
        int i = 0;
        while (entryEnumeration.hasMoreElements()) {
            JarEntry jarEntry = entryEnumeration.nextElement();
            if (jarEntry.getName().endsWith(".class")) {
                i++;
                }
            if (i > MAX_CLASSES) {
                hasClass = true;
                copyStream(jarFile.getInputStream(jarEntry), jos, jarEntry, jarEntry.getName());
            } else {
                copyStream(jarFile.getInputStream(jarEntry), josMain, jarEntry, jarEntry.getName());
            }
        }
        IOUtils.closeQuietly(jos);
        IOUtils.closeQuietly(josMain);
        jarFile.close();
        if (!hasClass) {
            FileUtils.deleteQuietly(splitOutJar);
            return;
        } else {
            FileUtils.deleteQuietly(outJar);
            result.remove(outJar);
            result.add(splitOutJar);
            result.add(splitOutJarMain);
        }
        splitMainJar(result, splitOutJar, index + 1);
    }catch (Exception e){

    }finally {

    }

}
 
Example 20
Project: dcmrs-broker   File: CacheManager.java   View Source Code Vote up 4 votes
static void writeObject(Attributes obj, String txUid, String classUid)
		throws IOException
{
	String studyUid = obj.getString(Tag.StudyInstanceUID);
	String seriesUid = obj.getString(Tag.SeriesInstanceUID);
	String instanceUid = obj.getString(Tag.SOPInstanceUID);

	File dcmFile = buildFile(studyUid, seriesUid, instanceUid, "dcm");
	File tmpFile = buildFile(studyUid, seriesUid, instanceUid, "tmp");
	File errFile = buildFile(studyUid, seriesUid, instanceUid, "err");
	try {
		if (errFile.isFile()) {
			logger.info("Overwriting error file: {}", errFile);

			FileUtils.deleteQuietly(errFile);
		}

		FileUtils.touch(tmpFile); // Create parent directories if needed

		try (FileOutputStream fos = new FileOutputStream(tmpFile)) {
			if (UID.ImplicitVRLittleEndian.equals(txUid)) {
				// DicomOutputStream throws exception when writing dataset with LEI
				txUid = UID.ExplicitVRLittleEndian;
			}
			else if (UID.ExplicitVRBigEndianRetired.equals(txUid)) {
				// Should never happen, but just in case
				txUid = UID.ExplicitVRLittleEndian;

				logger.info("Trancoding dataset from big to "
							+ "little endian for: {}", dcmFile);
			}


			Attributes fmi = Attributes.createFileMetaInformation(instanceUid,
																  classUid,
																  txUid);

			DicomOutputStream dos = new DicomOutputStream(fos, txUid);
			dos.writeDataset(fmi, obj);
			dos.close();
		}

		Files.move(tmpFile.toPath(),
				   dcmFile.toPath(),
				   StandardCopyOption.ATOMIC_MOVE,
				   StandardCopyOption.REPLACE_EXISTING);
	}
	catch (Exception ex) {
		logger.warn("Unable save DICOM object to: " + dcmFile, ex);

		FileUtils.touch(errFile);
		FileUtils.deleteQuietly(tmpFile);
		FileUtils.deleteQuietly(dcmFile);

		if (ex instanceof IOException) {
			throw (IOException) ex;
		}
		else {
			throw new IOException(ex);
		}
	}
}