Java Code Examples for org.apache.commons.vfs2.FileObject#delete()

The following examples show how to use org.apache.commons.vfs2.FileObject#delete() . 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: DistributedCacheUtilImplTest.java    From pentaho-hadoop-shims with Apache License 2.0 6 votes vote down vote up
@Test
public void findFiles_vfs() throws Exception {
  DistributedCacheUtilImpl ch = new DistributedCacheUtilImpl();

  FileObject testFolder = DistributedCacheTestUtil.createTestFolderWithContent();

  try {
    // Simply test we can find the jar files in our test folder
    List<String> jars = ch.findFiles( testFolder, "jar" );
    assertEquals( 4, jars.size() );

    // Look for all files and folders
    List<String> all = ch.findFiles( testFolder, null );
    assertEquals( 15, all.size() );
  } finally {
    testFolder.delete( new AllFileSelector() );
  }
}
 
Example 2
Source File: JobEntryFTPSGetIT.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
@Test
public void downloadFile_WhenDestinationIsSetViaVariable() throws Exception {
  final String myVar = "my-var";
  final String expectedDownloadedFilePath = ramDir + "/" + FtpsServer.SAMPLE_FILE;

  JobEntryFTPSGet job = createCommonJob();
  job.setVariable( myVar, ramDir );
  job.setTargetDirectory( String.format( "${%s}", myVar ) );

  FileObject downloaded = KettleVFS.getFileObject( expectedDownloadedFilePath );
  assertFalse( downloaded.exists() );
  try {
    job.execute( new Result(), 1 );
    downloaded = KettleVFS.getFileObject( expectedDownloadedFilePath );
    assertTrue( downloaded.exists() );
  } finally {
    downloaded.delete();
  }
}
 
Example 3
Source File: FSManager.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
public void deleteFile(final String relativePath) {
  for (Accept accept : Accept.values()) {
    final String path = getAbsolutePath(relativePath, accept);
    LOG.info("Delete {}", path);

    try {
      final FileObject fileObject = fsManager.resolveFile(MEM_PREFIX + path);

      if (fileObject.exists()) {
        fileObject.delete();
      }
    } catch (IOException ignore) {
      // ignore exception
    }
  }
}
 
Example 4
Source File: DistributedCacheUtilImplOSDependentTest.java    From pentaho-hadoop-shims with Apache License 2.0 6 votes vote down vote up
@Test
public void stageForCache_destination_exists() throws Exception {
  DistributedCacheUtilImpl ch = new DistributedCacheUtilImpl();

  Configuration conf = new Configuration();
  FileSystem fs = DistributedCacheTestUtil.getLocalFileSystem( conf );

  FileObject source = DistributedCacheTestUtil.createTestFolderWithContent();
  try {
    Path root = new Path( "bin/test/stageForCache_destination_exists" );
    Path dest = new Path( root, "dest" );

    fs.mkdirs( dest );
    assertTrue( fs.exists( dest ) );
    assertTrue( fs.getFileStatus( dest ).isDir() );

    DistributedCacheTestUtil.stageForCacheTester( ch, source, fs, root, dest, 6, 9 );
  } finally {
    source.delete( new AllFileSelector() );
  }
}
 
Example 5
Source File: ProviderCacheStrategyTests.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * Test the on_call strategy
 */
public void testOnCallCache() throws Exception {
    final FileObject scratchFolder = getWriteFolder();
    if (FileObjectUtils.isInstanceOf(getBaseFolder(), RamFileObject.class)
            || scratchFolder.getFileSystem() instanceof VirtualFileSystem) {
        // cant check ram filesystem as every manager holds its own ram filesystem data
        return;
    }

    scratchFolder.delete(Selectors.EXCLUDE_SELF);

    final DefaultFileSystemManager fs = createManager();
    fs.setCacheStrategy(CacheStrategy.ON_CALL);
    fs.init();
    final FileObject foBase2 = getBaseTestFolder(fs);

    final FileObject cachedFolder = foBase2.resolveFile(scratchFolder.getName().getPath());

    FileObject[] fos = cachedFolder.getChildren();
    assertContainsNot(fos, "file1.txt");

    scratchFolder.resolveFile("file1.txt").createFile();

    fos = cachedFolder.getChildren();
    assertContains(fos, "file1.txt");
}
 
Example 6
Source File: CustomRamProviderTest.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 *
 * Checks root folder exists
 *
 * @throws FileSystemException
 */
@Test
public void testRootFolderExists() throws FileSystemException {
    final FileObject root = manager.resolveFile("ram:///", defaultRamFso);
    assertTrue(root.getType().hasChildren());

    try {
        root.delete();
        fail();
    } catch (final FileSystemException e) {
        // Expected
    }

}
 
Example 7
Source File: ProviderRandomReadWriteTests.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Sets up a scratch folder for the test to use.
 */
protected FileObject createScratchFolder() throws Exception {
    final FileObject scratchFolder = getWriteFolder();

    // Make sure the test folder is empty
    scratchFolder.delete(Selectors.EXCLUDE_SELF);
    scratchFolder.createFolder();

    return scratchFolder;
}
 
Example 8
Source File: IndexTaskContext.java    From spoofax with Apache License 2.0 5 votes vote down vote up
private void deleteIndexFile(FileObject file) {
    try {
        file.delete();
    } catch(Exception e) {
        logger.error("Deleting index file {} failed, please delete the file manually", e, file);
    }
}
 
Example 9
Source File: Webdav4VersioningTests.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Sets up a scratch folder for the test to use.
 */
protected FileObject createScratchFolder() throws Exception {
    final FileObject scratchFolder = getWriteFolder();

    // Make sure the test folder is empty
    scratchFolder.delete(Selectors.EXCLUDE_SELF);
    scratchFolder.createFolder();

    return scratchFolder;
}
 
Example 10
Source File: ProviderWriteAppendTests.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Sets up a scratch folder for the test to use.
 */
protected FileObject createScratchFolder() throws Exception {
    final FileObject scratchFolder = getWriteFolder();

    // Make sure the test folder is empty
    scratchFolder.delete(Selectors.EXCLUDE_SELF);
    scratchFolder.createFolder();

    return scratchFolder;
}
 
Example 11
Source File: ConstraintContext.java    From spoofax with Apache License 2.0 5 votes vote down vote up
private void deleteContextFile(FileObject file) {
    try {
        file.delete();
    } catch(FileSystemException e) {
        logger.warn("Deleting context {} failed: {}", file, e.getMessage());
    }
}
 
Example 12
Source File: JobEntrySFTPIT.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
@Test
public void getFile_WhenDestinationIsSetViaVariable() throws Exception {
  final String localDir = TestUtils.createTempDir();
  KettleVFS.getFileObject( localDir ).createFolder();

  final String myVar = "my-var";

  final String sftpDir = "job-entry-sftp-test";
  final String fileName = "file.txt";

  uploadFile( sftpDir, fileName );

  JobEntrySFTP job = new JobEntrySFTP();
  job.setVariable( myVar, localDir );

  Job parent = mock( Job.class );
  when( parent.isStopped() ).thenReturn( false );
  job.setParentJob( parent );
  job.setLogLevel( LogLevel.NOTHING );

  job.setUserName( server.getUsername() );
  job.setPassword( server.getPassword() );
  job.setServerName( "localhost" );
  job.setServerPort( Integer.toString( server.getPort() ) );
  job.setScpDirectory( sftpDir );
  job.setTargetDirectory( String.format( "${%s}", myVar ) );

  job.execute( new Result(), 1 );

  FileObject downloaded = KettleVFS.getFileObject( localDir + "/" + fileName );
  assertTrue( downloaded.exists() );
  downloaded.delete();
}
 
Example 13
Source File: TextFileOutputTest.java    From hop with Apache License 2.0 5 votes vote down vote up
private FileObject createTemplateFile( String content ) throws IOException {
  FileObject f2 = createTemplateFile();
  if ( content == null ) {
    f2.delete();
  } else {
    try ( OutputStreamWriter fw = new OutputStreamWriter( f2.getContent().getOutputStream() ) ) {
      fw.write( content );
    }
  }
  return f2;
}
 
Example 14
Source File: KettleFileRepository.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public void deleteFile( String filename ) throws KettleException {
  try {
    FileObject fileObject = KettleVFS.getFileObject( filename );
    fileObject.delete();
  } catch ( Exception e ) {
    throw new KettleException( "Unable to delete file with name [" + filename + "]", e );
  }
}
 
Example 15
Source File: ActionCopyMoveResultFilenamesI.java    From hop with Apache License 2.0 4 votes vote down vote up
private boolean processFile( FileObject sourcefile, String destinationFolder, Result result, IWorkflowEngine<WorkflowMeta> parentWorkflow,
                             boolean deleteFile ) {
  boolean retval = false;

  try {
    if ( deleteFile ) {
      // delete file
      if ( sourcefile.delete() ) {
        if ( log.isDetailed() ) {
          logDetailed( BaseMessages.getString(
            PKG, "ActionCopyMoveResultFilenames.log.DeletedFile", sourcefile.toString() ) );
        }

        // Remove source file from result files list
        result.getResultFiles().remove( sourcefile.toString() );
        if ( log.isDetailed() ) {
          logDetailed( BaseMessages.getString(
            PKG, "ActionCopyMoveResultFilenames.RemovedFileFromResult", sourcefile.toString() ) );
        }

      } else {
        logError( BaseMessages.getString( PKG, "ActionCopyMoveResultFilenames.CanNotDeletedFile", sourcefile
          .toString() ) );
      }
    } else {
      // return destination short filename
      String shortfilename = getDestinationFilename( sourcefile.getName().getBaseName() );
      // build full destination filename
      String destinationFilename = destinationFolder + Const.FILE_SEPARATOR + shortfilename;
      FileObject destinationfile = HopVfs.getFileObject( destinationFilename );
      boolean filexists = destinationfile.exists();
      if ( filexists ) {
        if ( log.isDetailed() ) {
          logDetailed( BaseMessages.getString(
            PKG, "ActionCopyMoveResultFilenames.Log.FileExists", destinationFilename ) );
        }
      }
      if ( ( !filexists ) || ( filexists && isOverwriteFile() ) ) {
        if ( getAction().equals( "copy" ) ) {
          // Copy file
          FileUtil.copyContent( sourcefile, destinationfile );
          if ( log.isDetailed() ) {
            logDetailed( BaseMessages.getString(
              PKG, "ActionCopyMoveResultFilenames.log.CopiedFile", sourcefile.toString(), destinationFolder ) );
          }
        } else {
          // Move file
          sourcefile.moveTo( destinationfile );
          if ( log.isDetailed() ) {
            logDetailed( BaseMessages.getString(
              PKG, "ActionCopyMoveResultFilenames.log.MovedFile", sourcefile.toString(), destinationFolder ) );
          }
        }
        if ( isRemovedSourceFilename() ) {
          // Remove source file from result files list
          result.getResultFiles().remove( sourcefile.toString() );
          if ( log.isDetailed() ) {
            logDetailed( BaseMessages.getString(
              PKG, "ActionCopyMoveResultFilenames.RemovedFileFromResult", sourcefile.toString() ) );
          }
        }
        if ( isAddDestinationFilename() ) {
          // Add destination filename to Resultfilenames ...
          ResultFile resultFile =
            new ResultFile( ResultFile.FILE_TYPE_GENERAL, HopVfs.getFileObject(
              destinationfile.toString()), parentWorkflow.getWorkflowName(), toString() );
          result.getResultFiles().put( resultFile.getFile().toString(), resultFile );
          if ( log.isDetailed() ) {
            logDetailed( BaseMessages.getString(
              PKG, "ActionCopyMoveResultFilenames.AddedFileToResult", destinationfile.toString() ) );
          }
        }
      }
    }
    retval = true;
  } catch ( Exception e ) {
    logError( BaseMessages.getString( PKG, "ActionCopyMoveResultFilenames.Log.ErrorProcessing", e.toString() ) );
  }

  return retval;
}
 
Example 16
Source File: JobEntryCopyMoveResultFilenames.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
private boolean processFile( FileObject sourcefile, String destinationFolder, Result result, Job parentJob,
  boolean deleteFile ) {
  boolean retval = false;

  try {
    if ( deleteFile ) {
      // delete file
      if ( sourcefile.delete() ) {
        if ( log.isDetailed() ) {
          logDetailed( BaseMessages.getString(
            PKG, "JobEntryCopyMoveResultFilenames.log.DeletedFile", sourcefile.toString() ) );
        }

        // Remove source file from result files list
        result.getResultFiles().remove( sourcefile.toString() );
        if ( log.isDetailed() ) {
          logDetailed( BaseMessages.getString(
            PKG, "JobEntryCopyMoveResultFilenames.RemovedFileFromResult", sourcefile.toString() ) );
        }

      } else {
        logError( BaseMessages.getString( PKG, "JobEntryCopyMoveResultFilenames.CanNotDeletedFile", sourcefile
          .toString() ) );
      }
    } else {
      // return destination short filename
      String shortfilename = getDestinationFilename( sourcefile.getName().getBaseName() );
      // build full destination filename
      String destinationFilename = destinationFolder + Const.FILE_SEPARATOR + shortfilename;
      FileObject destinationfile = KettleVFS.getFileObject( destinationFilename, this );
      boolean filexists = destinationfile.exists();
      if ( filexists ) {
        if ( log.isDetailed() ) {
          logDetailed( BaseMessages.getString(
            PKG, "JobEntryCopyMoveResultFilenames.Log.FileExists", destinationFilename ) );
        }
      }
      if ( ( !filexists ) || ( filexists && isOverwriteFile() ) ) {
        if ( getAction().equals( "copy" ) ) {
          // Copy file
          FileUtil.copyContent( sourcefile, destinationfile );
          if ( log.isDetailed() ) {
            logDetailed( BaseMessages.getString(
              PKG, "JobEntryCopyMoveResultFilenames.log.CopiedFile", sourcefile.toString(), destinationFolder ) );
          }
        } else {
          // Move file
          sourcefile.moveTo( destinationfile );
          if ( log.isDetailed() ) {
            logDetailed( BaseMessages.getString(
              PKG, "JobEntryCopyMoveResultFilenames.log.MovedFile", sourcefile.toString(), destinationFolder ) );
          }
        }
        if ( isRemovedSourceFilename() ) {
          // Remove source file from result files list
          result.getResultFiles().remove( sourcefile.toString() );
          if ( log.isDetailed() ) {
            logDetailed( BaseMessages.getString(
              PKG, "JobEntryCopyMoveResultFilenames.RemovedFileFromResult", sourcefile.toString() ) );
          }
        }
        if ( isAddDestinationFilename() ) {
          // Add destination filename to Resultfilenames ...
          ResultFile resultFile =
            new ResultFile( ResultFile.FILE_TYPE_GENERAL, KettleVFS.getFileObject(
              destinationfile.toString(), this ), parentJob.getJobname(), toString() );
          result.getResultFiles().put( resultFile.getFile().toString(), resultFile );
          if ( log.isDetailed() ) {
            logDetailed( BaseMessages.getString(
              PKG, "JobEntryCopyMoveResultFilenames.AddedFileToResult", destinationfile.toString() ) );
          }
        }
      }
    }
    retval = true;
  } catch ( Exception e ) {
    logError( BaseMessages.getString( PKG, "JobEntryCopyMoveResultFilenames.Log.ErrorProcessing", e.toString() ) );
  }

  return retval;
}
 
Example 17
Source File: ActionDeleteFile.java    From hop with Apache License 2.0 4 votes vote down vote up
public Result execute( Result previousResult, int nr ) {
  Result result = previousResult;
  result.setResult( false );

  if ( filename != null ) {
    String realFilename = getRealFilename();

    FileObject fileObject = null;
    try {
      fileObject = HopVfs.getFileObject( realFilename );

      if ( !fileObject.exists() ) {
        if ( isFailIfFileNotExists() ) {
          // File doesn't exist and fail flag is on.
          result.setResult( false );
          logError( BaseMessages.getString(
            PKG, "ActionDeleteFile.ERROR_0004_File_Does_Not_Exist", realFilename ) );
        } else {
          // File already deleted, no reason to try to delete it
          result.setResult( true );
          if ( log.isBasic() ) {
            logBasic( BaseMessages.getString( PKG, "ActionDeleteFile.File_Already_Deleted", realFilename ) );
          }
        }
      } else {
        boolean deleted = fileObject.delete();
        if ( !deleted ) {
          logError( BaseMessages.getString(
            PKG, "ActionDeleteFile.ERROR_0005_Could_Not_Delete_File", realFilename ) );
          result.setResult( false );
          result.setNrErrors( 1 );
        }
        if ( log.isBasic() ) {
          logBasic( BaseMessages.getString( PKG, "ActionDeleteFile.File_Deleted", realFilename ) );
        }
        result.setResult( true );
      }
    } catch ( Exception e ) {
      logError( BaseMessages.getString(
        PKG, "ActionDeleteFile.ERROR_0006_Exception_Deleting_File", realFilename, e.getMessage() ), e );
      result.setResult( false );
      result.setNrErrors( 1 );
    } finally {
      if ( fileObject != null ) {
        try {
          fileObject.close();
        } catch ( IOException ex ) { /* Ignore */
        }
      }
    }
  } else {
    logError( BaseMessages.getString( PKG, "ActionDeleteFile.ERROR_0007_No_Filename_Is_Defined" ) );
  }

  return result;
}
 
Example 18
Source File: FTPRemoteLocationExecutorDelegate.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Override
public void delete(String filePath) throws IOException {
  FileObject fileObject = resolveChild(filePath);
  fileObject.delete();
}
 
Example 19
Source File: JobEntryDeleteFile.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
public Result execute( Result previousResult, int nr ) {
  Result result = previousResult;
  result.setResult( false );

  //Set Embedded NamedCluter MetatStore Provider Key so that it can be passed to VFS
  if ( parentJobMeta.getNamedClusterEmbedManager() != null ) {
    parentJobMeta.getNamedClusterEmbedManager()
      .passEmbeddedMetastoreKey( this, parentJobMeta.getEmbeddedMetastoreProviderKey() );
  }

  if ( filename != null ) {
    String realFilename = getRealFilename();

    FileObject fileObject = null;
    try {
      fileObject = KettleVFS.getFileObject( realFilename, this );

      if ( !fileObject.exists() ) {
        if ( isFailIfFileNotExists() ) {
          // File doesn't exist and fail flag is on.
          result.setResult( false );
          logError( BaseMessages.getString(
            PKG, "JobEntryDeleteFile.ERROR_0004_File_Does_Not_Exist", realFilename ) );
        } else {
          // File already deleted, no reason to try to delete it
          result.setResult( true );
          if ( log.isBasic() ) {
            logBasic( BaseMessages.getString( PKG, "JobEntryDeleteFile.File_Already_Deleted", realFilename ) );
          }
        }
      } else {
        boolean deleted = fileObject.delete();
        if ( !deleted ) {
          logError( BaseMessages.getString(
            PKG, "JobEntryDeleteFile.ERROR_0005_Could_Not_Delete_File", realFilename ) );
          result.setResult( false );
          result.setNrErrors( 1 );
        }
        if ( log.isBasic() ) {
          logBasic( BaseMessages.getString( PKG, "JobEntryDeleteFile.File_Deleted", realFilename ) );
        }
        result.setResult( true );
      }
    } catch ( Exception e ) {
      logError( BaseMessages.getString(
        PKG, "JobEntryDeleteFile.ERROR_0006_Exception_Deleting_File", realFilename, e.getMessage() ), e );
      result.setResult( false );
      result.setNrErrors( 1 );
    } finally {
      if ( fileObject != null ) {
        try {
          fileObject.close();
        } catch ( IOException ex ) { /* Ignore */
        }
      }
    }
  } else {
    logError( BaseMessages.getString( PKG, "JobEntryDeleteFile.ERROR_0007_No_Filename_Is_Defined" ) );
  }

  return result;
}
 
Example 20
Source File: TextFileInputTest.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
private static void deleteVfsFile( String path ) throws Exception {
  FileObject fileObject = TestUtils.getFileObject( path );
  fileObject.close();
  fileObject.delete();
}