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

The following examples show how to use org.apache.commons.vfs2.FileObject#moveTo() . 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: MoveTask.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * Handles a single source file.
 */
@Override
protected void handleOutOfDateFile(final FileObject srcFile, final FileObject destFile) throws FileSystemException {
    if (!tryRename || !srcFile.canRenameTo(destFile)) {
        super.handleOutOfDateFile(srcFile, destFile);

        log("Deleting " + srcFile.getPublicURIString());
        srcFile.delete(Selectors.SELECT_SELF);
    } else {
        log("Rename " + srcFile.getPublicURIString() + " to " + destFile.getPublicURIString());
        srcFile.moveTo(destFile);
        if (!isPreserveLastModified()
                && destFile.getFileSystem().hasCapability(Capability.SET_LAST_MODIFIED_FILE)) {
            destFile.getContent().setLastModifiedTime(System.currentTimeMillis());
        }
    }
}
 
Example 2
Source File: VFSFileProvider.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
/**
 * @param file
 * @param newPath
 * @param overwrite
 * @return
 */
private VFSFile doMove( VFSFile file, String newPath, boolean overwrite ) {
  try {
    FileObject fileObject = KettleVFS
      .getFileObject( file.getPath(), new Variables(), VFSHelper.getOpts( file.getPath(), file.getConnection() ) );
    FileObject renameObject = KettleVFS
      .getFileObject( newPath, new Variables(), VFSHelper.getOpts( file.getPath(), file.getConnection() ) );
    if ( overwrite && renameObject.exists() ) {
      renameObject.delete();
    }
    fileObject.moveTo( renameObject );
    if ( file instanceof VFSDirectory ) {
      return VFSDirectory.create( renameObject.getParent().getPublicURIString(), renameObject, file.getConnection(),
        file.getDomain() );
    } else {
      return VFSFile.create( renameObject.getParent().getPublicURIString(), renameObject, file.getConnection(),
        file.getDomain() );
    }
  } catch ( KettleFileException | FileSystemException e ) {
    return null;
  }
}
 
Example 3
Source File: KettleFileRepository.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
private ObjectId renameObject( ObjectId id, RepositoryDirectoryInterface newDirectory, String newName,
  String extension ) throws KettleException {
  try {
    // In case of a root object, the ID is the same as the relative filename...
    //
    FileObject fileObject = KettleVFS.getFileObject( calcDirectoryName( null ) + id.getId() );

    // Same name, different folder?
    if ( Utils.isEmpty( newName ) ) {
      newName = calcObjectName( id );
    }
    // The new filename can be anywhere so we re-calculate a new ID...
    //
    String newFilename = calcDirectoryName( newDirectory ) + newName + extension;

    FileObject newObject = KettleVFS.getFileObject( newFilename );
    fileObject.moveTo( newObject );

    return new StringObjectId( calcObjectId( newDirectory, newName, extension ) );
  } catch ( Exception e ) {
    throw new KettleException( "Unable to rename object with ID [" + id + "] to [" + newName + "]", e );
  }

}
 
Example 4
Source File: ProviderRenameTests.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
private void moveFile(final FileObject scratchFolder, final FileObject file, final String content)
        throws FileSystemException, Exception {
    final FileObject fileMove = scratchFolder.resolveFile("file1move.txt");
    assertFalse(fileMove.exists());

    file.moveTo(fileMove);

    assertFalse(file.exists());
    assertTrue(fileMove.exists());

    assertSameContent(content, fileMove);

    // Delete the file.
    assertTrue(fileMove.exists());
    assertTrue(fileMove.delete());
}
 
Example 5
Source File: VFSNotebookRepo.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void save(Note note, AuthenticationInfo subject) throws IOException {
  LOGGER.info("Saving note " + note.getId() + " to " + buildNoteFileName(note));
  // write to tmp file first, then rename it to the {note_name}_{note_id}.zpln
  FileObject noteJson = rootNotebookFileObject.resolveFile(
      buildNoteTempFileName(note), NameScope.DESCENDENT);
  OutputStream out = null;
  try {
    out = noteJson.getContent().getOutputStream(false);
    IOUtils.write(note.toJson().getBytes(conf.getString(ConfVars.ZEPPELIN_ENCODING)), out);
  } finally {
    if (out != null) {
      out.close();
    }
  }
  noteJson.moveTo(rootNotebookFileObject.resolveFile(
      buildNoteFileName(note), NameScope.DESCENDENT));
}
 
Example 6
Source File: OldVFSNotebookRepo.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void save(Note note, AuthenticationInfo subject) throws IOException {
  LOG.info("Saving note:" + note.getId());
  String json = note.toJson();

  FileObject rootDir = getRootDir();

  FileObject noteDir = rootDir.resolveFile(note.getId(), NameScope.CHILD);

  if (!noteDir.exists()) {
    noteDir.createFolder();
  }
  if (!isDirectory(noteDir)) {
    throw new IOException(noteDir.getName().toString() + " is not a directory");
  }

  FileObject noteJson = noteDir.resolveFile(".note.json", NameScope.CHILD);
  // false means not appending. creates file if not exists
  OutputStream out = noteJson.getContent().getOutputStream(false);
  out.write(json.getBytes(conf.getString(ConfVars.ZEPPELIN_ENCODING)));
  out.close();
  noteJson.moveTo(noteDir.resolveFile("note.json", NameScope.CHILD));
}
 
Example 7
Source File: VFSNotebookRepo.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
@Override
public void move(String noteId,
                 String notePath,
                 String newNotePath,
                 AuthenticationInfo subject) throws IOException {
  LOGGER.info("Move note " + noteId + " from " + notePath + " to " + newNotePath);
  FileObject fileObject = rootNotebookFileObject.resolveFile(
      buildNoteFileName(noteId, notePath), NameScope.DESCENDENT);
  FileObject destFileObject = rootNotebookFileObject.resolveFile(
      buildNoteFileName(noteId, newNotePath), NameScope.DESCENDENT);
  // create parent folder first, otherwise move operation will fail
  destFileObject.getParent().createFolder();
  fileObject.moveTo(destFileObject);
}
 
Example 8
Source File: VFSNotebookRepo.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
@Override
public void move(String folderPath, String newFolderPath,
                 AuthenticationInfo subject) throws IOException{
  LOGGER.info("Move folder from " + folderPath + " to " + newFolderPath);
  FileObject fileObject = rootNotebookFileObject.resolveFile(
      folderPath.substring(1), NameScope.DESCENDENT);
  FileObject destFileObject = rootNotebookFileObject.resolveFile(
      newFolderPath.substring(1), NameScope.DESCENDENT);
  // create parent folder first, otherwise move operation will fail
  destFileObject.getParent().createFolder();
  fileObject.moveTo(destFileObject);
}
 
Example 9
Source File: CustomRamProviderTest.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Tests VFS-625.
 * @throws FileSystemException
 */
@Test
public void testMoveFile() throws FileSystemException {
    final FileObject fileSource = manager.resolveFile("ram://virtual/source");
    fileSource.createFile();
    final FileObject fileDest = manager.resolveFile("ram://virtual/dest");
    Assert.assertTrue(fileSource.canRenameTo(fileDest));
    fileSource.moveTo(fileDest);
}
 
Example 10
Source File: SimpleVirtualFilesystem.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
private VirtualFile getFileFromHash(FileObject tempFile, StreamingXXHash64 hash64, String directory) throws
        FileSystemException {
    FileObject hashNameFile = this.fsManager.resolveFile(directory + filePathFromHash(hash64));
    if (hashNameFile.exists()) {
        tempFile.delete();
    } else {
        hashNameFile.createFile();
        tempFile.moveTo(hashNameFile);
    }
    return new SimpleVirtualFile(hashNameFile);
}
 
Example 11
Source File: KettleFileRepository.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
@Override
public ObjectId renameRepositoryDirectory( ObjectId id, RepositoryDirectoryInterface newParentDir, String newName ) throws KettleException {
  if ( newParentDir != null || newName != null ) {
    try {
      // In case of a root object, the ID is the same as the relative filename...
      RepositoryDirectoryInterface tree = loadRepositoryDirectoryTree();
      RepositoryDirectoryInterface dir = tree.findDirectory( id );

      if ( dir == null ) {
        throw new KettleException( "Could not find folder [" + id + "]" );
      }

      // If newName is null, keep the current name
      newName = ( newName != null ) ? newName : dir.getName();

      FileObject folder = KettleVFS.getFileObject( dir.getPath() );

      String newFolderName = null;

      if ( newParentDir != null ) {
        FileObject newParentFolder = KettleVFS.getFileObject( newParentDir.getPath() );

        newFolderName = newParentFolder.toString() + "/" + newName;
      } else {
        newFolderName = folder.getParent().toString() + "/" + newName;
      }

      FileObject newFolder = KettleVFS.getFileObject( newFolderName );
      folder.moveTo( newFolder );

      return new StringObjectId( dir.getObjectId() );
    } catch ( Exception e ) {
      throw new KettleException( "Unable to rename directory folder to [" + id + "]" );
    }
  }
  return ( id );
}
 
Example 12
Source File: SftpPut.java    From hop with Apache License 2.0 4 votes vote down vote up
protected void finishTheJob( FileObject file, String sourceData, FileObject destinationFolder ) throws HopException {
  try {
    switch ( meta.getAfterFTPS() ) {
      case JobEntrySFTPPUT.AFTER_FTPSPUT_DELETE:
        // Delete source file
        if ( !file.exists() ) {
          file.delete();
          if ( isDetailed() ) {
            logDetailed( BaseMessages.getString( PKG, "SFTPPut.Log.DeletedFile", sourceData ) );
          }
        }
        break;
      case JobEntrySFTPPUT.AFTER_FTPSPUT_MOVE:
        // Move source file
        FileObject destination = null;
        try {
          destination =
            HopVFS.getFileObject( destinationFolder.getName().getBaseName()
              + Const.FILE_SEPARATOR + file.getName().getBaseName(), this );
          file.moveTo( destination );
          if ( isDetailed() ) {
            logDetailed( BaseMessages.getString( PKG, "SFTPPut.Log.FileMoved", file, destination ) );
          }
        } finally {
          if ( destination != null ) {
            destination.close();
          }
        }
        break;
      default:
        if ( meta.isAddFilenameResut() ) {
          // Add this to the result file names...
          ResultFile resultFile =
            new ResultFile( ResultFile.FILE_TYPE_GENERAL, file, getPipelineMeta().getName(), getTransformName() );
          resultFile.setComment( BaseMessages.getString( PKG, "SFTPPut.Log.FilenameAddedToResultFilenames" ) );
          addResultFile( resultFile );
          if ( isDetailed() ) {
            logDetailed( BaseMessages.getString( PKG, "SFTPPut.Log.FilenameAddedToResultFilenames", sourceData ) );
          }
        }
        break;
    }
  } catch ( Exception e ) {
    throw new HopException( e );
  }
}
 
Example 13
Source File: JobEntryUnZip.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
/**
 * Moving or deleting source file.
 */
private void doUnzipPostProcessing( FileObject sourceFileObject, FileObject movetodir, String realMovetodirectory ) throws FileSystemException {
  if ( afterunzip == 1 ) {
    // delete zip file
    boolean deleted = sourceFileObject.delete();
    if ( !deleted ) {
      updateErrors();
      logError( BaseMessages.getString( PKG, "JobUnZip.Cant_Delete_File.Label", sourceFileObject.toString() ) );
    }
    // File deleted
    if ( log.isDebug() ) {
      logDebug( BaseMessages.getString( PKG, "JobUnZip.File_Deleted.Label", sourceFileObject.toString() ) );
    }
  } else if ( afterunzip == 2 ) {
    FileObject destFile = null;
    // Move File
    try {
      String destinationFilename = movetodir + Const.FILE_SEPARATOR + sourceFileObject.getName().getBaseName();
      destFile = KettleVFS.getFileObject( destinationFilename, this );

      sourceFileObject.moveTo( destFile );

      // File moved
      if ( log.isDetailed() ) {
        logDetailed( BaseMessages.getString(
          PKG, "JobUnZip.Log.FileMovedTo", sourceFileObject.toString(), realMovetodirectory ) );
      }
    } catch ( Exception e ) {
      updateErrors();
      logError( BaseMessages.getString(
        PKG, "JobUnZip.Cant_Move_File.Label", sourceFileObject.toString(), realMovetodirectory, e
          .getMessage() ) );
    } finally {
      if ( destFile != null ) {
        try {
          destFile.close();
        } catch ( IOException ex ) { /* Ignore */
        }
      }
    }
  }
}
 
Example 14
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 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: SFTPPut.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
protected void finishTheJob( FileObject file, String sourceData, FileObject destinationFolder ) throws KettleException {
  try {
    switch ( meta.getAfterFTPS() ) {
      case JobEntrySFTPPUT.AFTER_FTPSPUT_DELETE:
        // Delete source file
        if ( !file.exists() ) {
          file.delete();
          if ( isDetailed() ) {
            logDetailed( BaseMessages.getString( PKG, "SFTPPut.Log.DeletedFile", sourceData ) );
          }
        }
        break;
      case JobEntrySFTPPUT.AFTER_FTPSPUT_MOVE:
        // Move source file
        FileObject destination = null;
        try {
          destination =
            KettleVFS.getFileObject( destinationFolder.getName().getBaseName()
              + Const.FILE_SEPARATOR + file.getName().getBaseName(), this );
          file.moveTo( destination );
          if ( isDetailed() ) {
            logDetailed( BaseMessages.getString( PKG, "SFTPPut.Log.FileMoved", file, destination ) );
          }
        } finally {
          if ( destination != null ) {
            destination.close();
          }
        }
        break;
      default:
        if ( meta.isAddFilenameResut() ) {
          // Add this to the result file names...
          ResultFile resultFile =
            new ResultFile( ResultFile.FILE_TYPE_GENERAL, file, getTransMeta().getName(), getStepname() );
          resultFile.setComment( BaseMessages.getString( PKG, "SFTPPut.Log.FilenameAddedToResultFilenames" ) );
          addResultFile( resultFile );
          if ( isDetailed() ) {
            logDetailed( BaseMessages.getString( PKG, "SFTPPut.Log.FilenameAddedToResultFilenames", sourceData ) );
          }
        }
        break;
    }
  } catch ( Exception e ) {
    throw new KettleException( e );
  }
}
 
Example 17
Source File: ActionUnZip.java    From hop with Apache License 2.0 4 votes vote down vote up
/**
 * Moving or deleting source file.
 */
private void doUnzipPostProcessing( FileObject sourceFileObject, FileObject movetodir, String realMovetodirectory ) throws FileSystemException {
  if ( afterunzip == 1 ) {
    // delete zip file
    boolean deleted = sourceFileObject.delete();
    if ( !deleted ) {
      updateErrors();
      logError( BaseMessages.getString( PKG, "JobUnZip.Cant_Delete_File.Label", sourceFileObject.toString() ) );
    }
    // File deleted
    if ( log.isDebug() ) {
      logDebug( BaseMessages.getString( PKG, "JobUnZip.File_Deleted.Label", sourceFileObject.toString() ) );
    }
  } else if ( afterunzip == 2 ) {
    FileObject destFile = null;
    // Move File
    try {
      String destinationFilename = movetodir + Const.FILE_SEPARATOR + sourceFileObject.getName().getBaseName();
      destFile = HopVfs.getFileObject( destinationFilename );

      sourceFileObject.moveTo( destFile );

      // File moved
      if ( log.isDetailed() ) {
        logDetailed( BaseMessages.getString(
          PKG, "JobUnZip.Log.FileMovedTo", sourceFileObject.toString(), realMovetodirectory ) );
      }
    } catch ( Exception e ) {
      updateErrors();
      logError( BaseMessages.getString(
        PKG, "JobUnZip.Cant_Move_File.Label", sourceFileObject.toString(), realMovetodirectory, e
          .getMessage() ) );
    } finally {
      if ( destFile != null ) {
        try {
          destFile.close();
        } catch ( IOException ex ) { /* Ignore */
        }
      }
    }
  }
}