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

The following examples show how to use org.apache.commons.io.FileUtils#deleteQuietly() . 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: GatewayTestDriver.java    From knox with Apache License 2.0 6 votes vote down vote up
public void cleanup() throws Exception {
  stop();
  if ( config != null ) {
    FileUtils.deleteQuietly( new File( config.getGatewayTopologyDir() ) );
    FileUtils.deleteQuietly( new File( config.getGatewayConfDir() ) );
    FileUtils.deleteQuietly( new File( config.getGatewaySecurityDir() ) );
    FileUtils.deleteQuietly( new File( config.getGatewayDeploymentDir() ) );
    FileUtils.deleteQuietly( new File( config.getGatewayDataDir() ) );
  }

  for( Service service : services.values() ) {
    service.server.stop();
  }
  services.clear();

  if(ldap != null) {
    ldap.stop(true);
  }
}
 
Example 2
Source File: RocksDbHdfsState.java    From jstorm with Apache License 2.0 6 votes vote down vote up
private void removeObsoleteLocalCheckpoints(long successBatchId) {
    File cpRootDir = new File(rocksDbCheckpointDir);
    for (String cpDir : cpRootDir.list()) {
        try {
            long cpId = JStormUtils.parseLong(cpDir);
            if (cpId < successBatchId)
                FileUtils.deleteQuietly(new File(rocksDbCheckpointDir + "/" + cpDir));
        } catch (Throwable e) {
            File file = new File(rocksDbCheckpointDir + "/" + cpDir);
            // If existing more thant one hour, remove the unexpected file
            if (System.currentTimeMillis() - file.lastModified() > 60 * 60 * 1000) {
                LOG.debug("Unexpected file-" + cpDir + " in local checkpoint dir, " + rocksDbCheckpointDir, e);
                FileUtils.deleteQuietly(file);
            }
        }
    }
}
 
Example 3
Source File: FFmpeg.java    From youtubedl-android with GNU General Public License v3.0 6 votes vote down vote up
private void initFFmpeg(Context appContext, File ffmpegDir) throws YoutubeDLException {
    File ffmpegLib = new File(binDir, ffmpegLibName);
    // using size of lib as version
    String ffmpegSize = String.valueOf(ffmpegLib.length());
    if (!ffmpegDir.exists() || shouldUpdateFFmpeg(appContext, ffmpegSize)) {
        FileUtils.deleteQuietly(ffmpegDir);
        ffmpegDir.mkdirs();
        try {
            ZipUtils.unzip(ffmpegLib, ffmpegDir);
        } catch (Exception e) {
            FileUtils.deleteQuietly(ffmpegDir);
            throw new YoutubeDLException("failed to initialize", e);
        }
        updateFFmpeg(appContext, ffmpegSize);
    }
}
 
Example 4
Source File: KafkaEmbedded.java    From eagle with Apache License 2.0 6 votes vote down vote up
public KafkaEmbedded(Integer kafkaPort, Integer zookeeperPort) {
    try {
        zk = new ZookeeperEmbedded(zookeeperPort);
        zk.start();

        this.port = null != kafkaPort ? kafkaPort : InstanceSpec.getRandomPort();
        logDir = new File(System.getProperty("java.io.tmpdir"), "kafka/logs/kafka-test-" + kafkaPort);
        FileUtils.deleteQuietly(logDir);

        KafkaConfig config = buildKafkaConfig(zk.getConnectionString());
        kafka = new KafkaServerStartable(config);
        kafka.startup();
    } catch (Exception ex) {
        throw new RuntimeException("Could not start test broker", ex);
    }
}
 
Example 5
Source File: AsciidocConverterTest.java    From swagger2markup with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithSeparatedDefinitions() throws IOException, URISyntaxException {
    //Given
    Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_petstore.yaml").toURI());
    Path outputDirectory = Paths.get("build/test/asciidoc/generated");
    FileUtils.deleteQuietly(outputDirectory.toFile());

    //When
    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
            .withSeparatedDefinitions()
            .build();
    Swagger2MarkupConverter.from(file).withConfig(config).build()
            .toFolder(outputDirectory);

    //Then
    String[] files = outputDirectory.toFile().list();
    expectedFiles.add("definitions");
    assertThat(files).hasSize(5).containsAll(expectedFiles);

    Path definitionsDirectory = outputDirectory.resolve("definitions");
    String[] definitions = definitionsDirectory.toFile().list();
    assertThat(definitions).hasSize(5).containsAll(
            asList("Category.adoc", "Order.adoc", "Pet.adoc", "Tag.adoc", "User.adoc"));
}
 
Example 6
Source File: BaseBulkUploadBackgroundJobActor.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
private StorageDetails uploadResultToCloud(
    BulkUploadProcess bulkUploadProcess,
    List<Map<String, Object>> successList,
    List<Map<String, Object>> failureList,
    Map<String, String> outputColumnsMap,
    String[] outputColumnsOrder)
    throws IOException {

  String objKey = generateObjectKey(bulkUploadProcess);
  File file = null;
  try {
    file = getFileHandle(bulkUploadProcess.getObjectType(), bulkUploadProcess.getId());
    writeResultsToFile(file, successList, failureList, outputColumnsMap, outputColumnsOrder);
    CloudStorageUtil.upload(
        CloudStorageType.AZURE,
        bulkUploadProcess.getObjectType(),
        objKey,
        file.getAbsolutePath());
    return new StorageDetails(
        CloudStorageType.AZURE.getType(), bulkUploadProcess.getObjectType(), objKey);
  } catch (Exception ex) {
    ProjectLogger.log(
        "Exception occurred while uploading file to cloud.:: " + ex.getMessage(), ex);
  } finally {
    FileUtils.deleteQuietly(file);
  }
  return null;
}
 
Example 7
Source File: WorkerSave.java    From arx with Apache License 2.0 5 votes vote down vote up
@Override
public void run(final IProgressMonitor arg0) throws InvocationTargetException,
                                                    InterruptedException {

    arg0.beginTask(Resources.getMessage("WorkerSave.0"), 8); //$NON-NLS-1$
    File temp = null;
    try {
        temp = File.createTempFile("arx", "deid");
        final FileOutputStream f = new FileOutputStream(temp);
        final ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(f));
        zip.setLevel(Deflater.BEST_SPEED);
        model.createConfig(); 
        writeMetadata(model, zip);
        arg0.worked(1);
        writeModel(model, zip);
        arg0.worked(1);
        writeInput(model, zip);
        arg0.worked(1);
        writeOutput(model, zip);
        arg0.worked(1);
        writeConfiguration(model, zip);
        arg0.worked(1);
        final Map<String, Integer> map = writeLattice(model, zip);
        arg0.worked(1);
        writeClipboard(model, map, zip);
        arg0.worked(1);
        writeFilter(model, zip);
        zip.close();
        arg0.worked(1);
        FileUtils.copyFile(temp, new File(path));
        FileUtils.deleteQuietly(temp);
    } catch (final Exception e) {
        error = e;
        arg0.done();
        FileUtils.deleteQuietly(temp);
        return;
    }

    arg0.done();
}
 
Example 8
Source File: BadUrlTest.java    From knox with Apache License 2.0 5 votes vote down vote up
@AfterClass
public static void tearDownAfterClass() {
  try {
    gatewayServer.stop();
  } catch (final Exception e) {
    e.printStackTrace(System.err);
  }

  /* Cleanup the created files */
  FileUtils.deleteQuietly(topoDir);
}
 
Example 9
Source File: GatewayAppFuncTest.java    From knox with Apache License 2.0 5 votes vote down vote up
@AfterClass
public static void tearDownAfterClass() throws Exception {
  LOG_ENTER();
  gateway.stop();
  driver.cleanup();
  FileUtils.deleteQuietly( new File( config.getGatewayHomeDir() ) );
  LOG_EXIT();
}
 
Example 10
Source File: ClusterTest.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
protected void stopMinion() {
  assertNotNull(_minionStarter, "Minion is not started");
  try {
    _minionStarter.stop();
  } catch (Exception e) {
    LOGGER.error("Encountered exception while stopping minion {}", e.getMessage());
  }
  FileUtils.deleteQuietly(new File(Minion.DEFAULT_INSTANCE_BASE_DIR));
  _minionStarter = null;
}
 
Example 11
Source File: SaslAuthenticateTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@AfterClass
public static void stopMiniKdc() {
    System.clearProperty("java.security.auth.login.config");
    System.clearProperty("java.security.krb5.conf");
    if (kdc != null) {
        kdc.stop();
    }
    FileUtils.deleteQuietly(kdcDir);
    FileUtils.deleteQuietly(kerberosWorkDir);
    assertFalse(kdcDir.exists());
    assertFalse(kerberosWorkDir.exists());
}
 
Example 12
Source File: SerializedBytesQueriesTest.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void setUp()
    throws Exception {
  FileUtils.deleteQuietly(INDEX_DIR);

  buildSegment();
  ImmutableSegment immutableSegment = ImmutableSegmentLoader.load(new File(INDEX_DIR, SEGMENT_NAME), ReadMode.mmap);
  _indexSegment = immutableSegment;
  _indexSegments = Arrays.asList(immutableSegment, immutableSegment);
}
 
Example 13
Source File: DistinctCountThetaSketchTest.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void setup()
    throws Exception {
  FileUtils.deleteQuietly(INDEX_DIR);

  File segmentFile = buildSegment(buildSchema());
  ImmutableSegment immutableSegment = ImmutableSegmentLoader.load(segmentFile, ReadMode.mmap);
  _indexSegment = immutableSegment;
  _indexSegments = Arrays.asList(immutableSegment, immutableSegment);
}
 
Example 14
Source File: TestSimpleFileProvderBackend.java    From incubator-sentry with Apache License 2.0 4 votes vote down vote up
@After
public void teardown() {
  if(baseDir != null) {
    FileUtils.deleteQuietly(baseDir);
  }
}
 
Example 15
Source File: TaskLogger.java    From scheduling with GNU Affero General Public License v3.0 4 votes vote down vote up
private void removeTaskLogFile() {
    FileAppender fileAppender = (FileAppender) taskLogAppender.getAppender(FILE_APPENDER_NAME);
    if (fileAppender != null && fileAppender.getFile() != null) {
        FileUtils.deleteQuietly(new File(fileAppender.getFile()));
    }
}
 
Example 16
Source File: FileManager.java    From file-manager with MIT License 4 votes vote down vote up
private void deleteFile() {
    if (currentFile==null) {
        showErrorMessage("No file selected for deletion.","Select File");
        return;
    }

    int result = JOptionPane.showConfirmDialog(
        gui,
        "Are you sure you want to delete this file?",
        "Delete File",
        JOptionPane.ERROR_MESSAGE
        );
    if (result==JOptionPane.OK_OPTION) {
        try {
            System.out.println("currentFile: " + currentFile);
            TreePath parentPath = findTreePath(currentFile.getParentFile());
            System.out.println("parentPath: " + parentPath);
            DefaultMutableTreeNode parentNode =
                (DefaultMutableTreeNode)parentPath.getLastPathComponent();
            System.out.println("parentNode: " + parentNode);

            boolean directory = currentFile.isDirectory();
            if (FileUtils.deleteQuietly(currentFile)) {
                if (directory) {
                    // delete the node..
                    TreePath currentPath = findTreePath(currentFile);
                    System.out.println(currentPath);
                    DefaultMutableTreeNode currentNode =
                        (DefaultMutableTreeNode)currentPath.getLastPathComponent();

                    treeModel.removeNodeFromParent(currentNode);
                }

                showChildren(parentNode);
            } else {
                String msg = "The file '" +
                    currentFile +
                    "' could not be deleted.";
                showErrorMessage(msg,"Delete Failed");
            }
        } catch(Throwable t) {
            showThrowable(t);
        }
    }
    gui.repaint();
}
 
Example 17
Source File: ServerBinaryDownloaderTest.java    From gocd with Apache License 2.0 4 votes vote down vote up
@After
public void tearDown() {
    FileUtils.deleteQuietly(new File(Downloader.AGENT_BINARY));
    FileUtils.deleteQuietly(DownloadableFile.AGENT.getLocalFile());
}
 
Example 18
Source File: HttpDownloader.java    From fdroidclient with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Get a remote file, checking the HTTP response code, if it has changed since
 * the last time a download was tried.
 * <p>
 * If the {@code ETag} does not match, it could be caused by the previous
 * download of the same file coming from a mirror running on a different
 * webserver, e.g. Apache vs Nginx.  {@code Content-Length} and
 * {@code Last-Modified} are used to check whether the file has changed since
 * those are more standardized than {@code ETag}.  Plus, Nginx and Apache 2.4
 * defaults use only those two values to generate the {@code ETag} anyway.
 * Unfortunately, other webservers and CDNs have totally different methods
 * for generating the {@code ETag}.  And mirrors that are syncing using a
 * method other than {@code rsync} could easily have different {@code Last-Modified}
 * times on the exact same file.  On top of that, some services like GitHub's
 * raw file support {@code raw.githubusercontent.com} and GitLab's raw file
 * support do not set the {@code Last-Modified} header at all.  So ultimately,
 * then {@code ETag} needs to be used first and foremost, then this calculated
 * {@code ETag} can serve as a common fallback.
 * <p>
 * In order to prevent the {@code ETag} from being used as a form of tracking
 * cookie, this code never sends the {@code ETag} to the server.  Instead, it
 * uses a {@code HEAD} request to get the {@code ETag} from the server, then
 * only issues a {@code GET} if the {@code ETag} has changed.
 * <p>
 * This uses a integer value for {@code Last-Modified} to avoid enabling the
 * use of that value as some kind of "cookieless cookie".  One second time
 * resolution should be plenty since these files change more on the time
 * space of minutes or hours.
 *
 * @see <a href="https://gitlab.com/fdroid/fdroidclient/issues/1708">update index from any available mirror</a>
 * @see <a href="http://lucb1e.com/rp/cookielesscookies">Cookieless cookies</a>
 */
@Override
public void download() throws IOException, InterruptedException {
    // get the file size from the server
    HttpURLConnection tmpConn = getConnection();
    tmpConn.setRequestMethod("HEAD");

    int contentLength = -1;
    int statusCode = tmpConn.getResponseCode();
    tmpConn.disconnect();
    newFileAvailableOnServer = false;
    switch (statusCode) {
        case HttpURLConnection.HTTP_OK:
            String headETag = tmpConn.getHeaderField(HEADER_FIELD_ETAG);
            contentLength = tmpConn.getContentLength();
            if (!TextUtils.isEmpty(cacheTag)) {
                if (cacheTag.equals(headETag)) {
                    Utils.debugLog(TAG, urlString + " cached, not downloading: " + headETag);
                    return;
                } else {
                    String calcedETag = String.format("\"%x-%x\"",
                            tmpConn.getLastModified() / 1000, contentLength);
                    if (cacheTag.equals(calcedETag)) {
                        Utils.debugLog(TAG, urlString + " cached based on calced ETag, not downloading: " +
                                calcedETag);
                        return;
                    }
                }
            }
            newFileAvailableOnServer = true;
            break;
        case HttpURLConnection.HTTP_NOT_FOUND:
            notFound = true;
            return;
        default:
            Utils.debugLog(TAG, "HEAD check of " + urlString + " returned " + statusCode + ": "
                    + tmpConn.getResponseMessage());
    }

    boolean resumable = false;
    long fileLength = outputFile.length();
    if (fileLength > contentLength) {
        FileUtils.deleteQuietly(outputFile);
    } else if (fileLength == contentLength && outputFile.isFile()) {
        return; // already have it!
    } else if (fileLength > 0) {
        resumable = true;
    }
    setupConnection(resumable);
    Utils.debugLog(TAG, "downloading " + urlString + " (is resumable: " + resumable + ")");
    downloadFromStream(resumable);
    cacheTag = connection.getHeaderField(HEADER_FIELD_ETAG);
}
 
Example 19
Source File: TestInsertIntoTable.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
@Test
public void testInsertValuesPartitionedTable() throws Exception {
  final String table1 = "insertTable2";

  try (AutoCloseable c = enableIcebergTables()) {
    final String table1Create = String.format("CREATE TABLE %s.%s(id int, code int) partition by (code)",
        TEMP_SCHEMA, table1);
    test(table1Create);

    Thread.sleep(1001);

    test(String.format("INSERT INTO %s.%s VALUES(1, 1)", TEMP_SCHEMA, table1));
    Thread.sleep(1001);
    test(String.format("INSERT INTO %s.%s VALUES(1, 2)", TEMP_SCHEMA, table1));
    Thread.sleep(1001);
    test(String.format("INSERT INTO %s.%s VALUES(1, 3)", TEMP_SCHEMA, table1));
    Thread.sleep(1001);
    test(String.format("INSERT INTO %s.%s VALUES(1, 4)", TEMP_SCHEMA, table1));
    Thread.sleep(1001);
    test(String.format("INSERT INTO %s.%s VALUES(1, 5)", TEMP_SCHEMA, table1));

    // same data in table1 and table2
    testBuilder()
        .sqlQuery(String.format("select id, code from %s.%s", TEMP_SCHEMA, table1))
        .unOrdered()
        .baselineColumns("id", "code")
        .baselineValues(1, 1)
        .baselineValues(1, 2)
        .baselineValues(1, 3)
        .baselineValues(1, 4)
        .baselineValues(1, 5)
        .build()
        .run();

    List<Integer> valuesInCodeColumn = IntStream.range(1, 6).boxed().collect(Collectors.toList());

    File table1Folder = new File(getDfsTestTmpSchemaLocation(), table1);
    Table icebergTable1 = new HadoopTables(new Configuration()).load(table1Folder.getPath());
    List<Integer> partitionValues = StreamSupport.stream(icebergTable1.newScan().planFiles().spliterator(), false)
        .map(fileScanTask -> fileScanTask.file().partition())
        .map(structLike -> structLike.get(0, Integer.class))
        .collect(Collectors.toList());

    Assert.assertEquals(valuesInCodeColumn.size(), partitionValues.size());
    Assert.assertTrue(partitionValues.containsAll(valuesInCodeColumn));

  } finally {
    FileUtils.deleteQuietly(new File(getDfsTestTmpSchemaLocation(), table1));
  }
}
 
Example 20
Source File: Pipeline.java    From wisdom with Apache License 2.0 2 votes vote down vote up
/**
 * Method called on each event before the processing, deleting the error file is this file exists.
 *
 * @param watcher the watcher
 */
private void cleanupErrorFile(Watcher watcher) {
    File file = getErrorFileForWatcher(watcher);
    FileUtils.deleteQuietly(file);
}