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

The following examples show how to use org.apache.commons.vfs2.FileObject#copyFrom() . 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: ProviderWriteTests.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * Tests file copy to and from the same file system type. This was a problem w/ FTP.
 */
public void testCopySameFileSystem() throws Exception {
    final FileObject scratchFolder = createScratchFolder();

    // Create direct child of the test folder
    final FileObject file = scratchFolder.resolveFile("file1.txt");
    assertFalse(file.exists());

    // Create the source file
    final String content = "Here is some sample content for the file.  Blah Blah Blah.";
    final OutputStream os = file.getContent().getOutputStream();
    try {
        os.write(content.getBytes("utf-8"));
    } finally {
        os.close();
    }

    assertSameContent(content, file);

    // Make sure we can copy the new file to another file on the same filesystem
    final FileObject fileCopy = scratchFolder.resolveFile("file1copy.txt");
    assertFalse(fileCopy.exists());
    fileCopy.copyFrom(file, Selectors.SELECT_SELF);

    assertSameContent(content, fileCopy);
}
 
Example 2
Source File: JobEntryTalendJobExec.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
private URL[] prepareJarFiles( FileObject zipFile ) throws Exception {

    // zip:file:///tmp/foo.zip
    FileInputList fileList = FileInputList.createFileList( this, new String[] { "zip:" + zipFile.toString(), },
      new String[] { ".*\\.jar$", }, // Include mask: only jar files
      new String[] { ".*classpath\\.jar$", }, // Exclude mask: only jar files
      new String[] { "Y", }, // File required
      new boolean[] { true, } ); // Search sub-directories

    List<URL> files = new ArrayList<URL>();

    // Copy the jar files in the temp folder...
    //
    for ( FileObject file : fileList.getFiles() ) {
      FileObject jarfilecopy =
        KettleVFS.createTempFile(
          file.getName().getBaseName(), ".jar", environmentSubstitute( "${java.io.tmpdir}" ) );
      jarfilecopy.copyFrom( file, new AllFileSelector() );
      files.add( jarfilecopy.getURL() );
    }

    return files.toArray( new URL[files.size()] );
  }
 
Example 3
Source File: VFSFileProvider.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
/**
 * @param file
 * @param toPath
 * @param overwrite
 * @return
 * @throws FileException
 */
@Override
public VFSFile copy( VFSFile file, String toPath, boolean overwrite ) throws FileException {
  try {
    FileObject fileObject = KettleVFS
      .getFileObject( file.getPath(), new Variables(), VFSHelper.getOpts( file.getPath(), file.getConnection() ) );
    FileObject copyObject =
      KettleVFS.getFileObject( toPath, new Variables(), VFSHelper.getOpts( file.getPath(), file.getConnection() ) );
    copyObject.copyFrom( fileObject, Selectors.SELECT_SELF );
    if ( file instanceof VFSDirectory ) {
      return VFSDirectory
        .create( copyObject.getParent().getPublicURIString(), fileObject, file.getConnection(), file.getDomain() );
    } else {
      return VFSFile
        .create( copyObject.getParent().getPublicURIString(), fileObject, file.getConnection(), file.getDomain() );
    }
  } catch ( KettleFileException | FileSystemException e ) {
    throw new FileException();
  }
}
 
Example 4
Source File: ResourceService.java    From spoofax with Apache License 2.0 6 votes vote down vote up
@Override public File localFile(FileObject resource, FileObject dir) {
    if(resource instanceof LocalFile) {
        return FileUtils.toFile(resource);
    }

    final File localDir = localPath(dir);
    if(localDir == null) {
        throw new MetaborgRuntimeException("Replication directory " + dir
            + " is not on the local filesystem, cannot get local file for " + resource);
    }
    try {
        dir.createFolder();

        final FileObject copyLoc;
        if(resource.getType() == FileType.FOLDER) {
            copyLoc = dir;
        } else {
            copyLoc = ResourceUtils.resolveFile(dir, resource.getName().getBaseName());
        }
        copyLoc.copyFrom(resource, new AllFileSelector());

        return localDir;
    } catch(FileSystemException e) {
        throw new MetaborgRuntimeException("Could not get local file for " + resource, e);
    }
}
 
Example 5
Source File: TestRunCelosServerModeEmbedded.java    From celos with Apache License 2.0 5 votes vote down vote up
public void copyRemoteDefaultsToLocal(String username, URI defaultsDirUri)
        throws URISyntaxException, FileSystemException {
    JScpWorker worker = new JScpWorker(username);
    if (defaultsDirUri != null) {
        FileObject remoteDefaultsDir = worker.getFileObjectByUri(defaultsDirUri);
        if (remoteDefaultsDir.exists()) {
            FileObject localDefaultsDir = worker.getFileObjectByUri(getCelosDefaultsDir());
            localDefaultsDir.copyFrom(remoteDefaultsDir, Selectors.SELECT_CHILDREN);
        }
    }
}
 
Example 6
Source File: WorkflowFilesDeployer.java    From celos with Apache License 2.0 5 votes vote down vote up
private void deployJSFile(URI dirUri, String fileName) throws URISyntaxException, IOException {
    if (dirUri != null) {
        URI fileUri = getTargetJsFileUri(dirUri);
        File localFile = new File(config.getDeployDir(), fileName);

        if (localFile.exists()) {
            parser.validateJsSyntax(new FileReader(localFile), localFile.getName());

            FileObject sftpFile = jScpWorker.getFileObjectByUri(fileUri);
            FileObject localFileObject = jScpWorker.getFileObjectByUri(localFile.getAbsolutePath());
            sftpFile.copyFrom(localFileObject, Selectors.SELECT_SELF);
        }
    }
}
 
Example 7
Source File: SftpFileTransferLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenUploadFileUsingApacheVfs_thenSuccess() throws IOException {
    FileSystemManager manager = VFS.getManager();
    FileObject local = manager.resolveFile(System.getProperty("user.dir") + "/" + localFile);
    FileObject remote = manager.resolveFile("sftp://" + username + ":" + password + "@" + remoteHost + "/" + remoteDir + "vfsFile.txt");
    remote.copyFrom(local, Selectors.SELECT_SELF);
    local.close();
    remote.close();
}
 
Example 8
Source File: SftpFileTransferLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenDownloadFileUsingApacheVfs_thenSuccess() throws IOException {
    FileSystemManager manager = VFS.getManager();
    FileObject local = manager.resolveFile(System.getProperty("user.dir") + "/" + localDir + "vfsFile.txt");
    FileObject remote = manager.resolveFile("sftp://" + username + ":" + password + "@" + remoteHost + "/" + remoteFile);
    local.copyFrom(remote, Selectors.SELECT_SELF);
    local.close();
    remote.close();
}
 
Example 9
Source File: CopyTask.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Handles an out-of-date file.
 *
 * @param srcFile The source FileObject.
 * @param destFile The destination FileObject.
 */
@Override
protected void handleOutOfDateFile(final FileObject srcFile, final FileObject destFile) throws FileSystemException {
    log("Copying " + srcFile.getPublicURIString() + " to " + destFile.getPublicURIString());
    destFile.copyFrom(srcFile, Selectors.SELECT_SELF);
    if (preserveLastModified && srcFile.getFileSystem().hasCapability(Capability.GET_LAST_MODIFIED)
            && destFile.getFileSystem().hasCapability(Capability.SET_LAST_MODIFIED_FILE)) {
        final long lastModTime = srcFile.getContent().getLastModifiedTime();
        destFile.getContent().setLastModifiedTime(lastModTime);
    }
}
 
Example 10
Source File: DefaultFileReplicator.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a local copy of the file, and all its descendants.
 *
 * @param srcFile The file to copy.
 * @param selector The FileSelector.
 * @return the created File.
 * @throws FileSystemException if an error occurs copying the file.
 */
@Override
public File replicateFile(final FileObject srcFile, final FileSelector selector) throws FileSystemException {
    final String basename = srcFile.getName().getBaseName();
    final File file = allocateFile(basename);

    // Copy from the source file
    final FileObject destFile = getContext().toFileObject(file);
    destFile.copyFrom(srcFile, selector);

    return file;
}
 
Example 11
Source File: ProviderWriteTests.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Tests overwriting a file on the same file system.
 */
public void testCopyFromOverwriteSameFileSystem() throws Exception {
    final FileObject scratchFolder = createScratchFolder();

    // Create direct child of the test folder
    final FileObject file = scratchFolder.resolveFile("file1.txt");
    assertFalse(file.exists());

    // Create the source file
    final String content = "Here is some sample content for the file.  Blah Blah Blah.";
    final OutputStream os = file.getContent().getOutputStream();
    try {
        os.write(content.getBytes("utf-8"));
    } finally {
        os.close();
    }

    assertSameContent(content, file);

    // Make sure we can copy the new file to another file on the same filesystem
    final FileObject fileCopy = scratchFolder.resolveFile("file1copy.txt");
    assertFalse(fileCopy.exists());
    fileCopy.copyFrom(file, Selectors.SELECT_SELF);

    assertSameContent(content, fileCopy);

    // Make sure we can copy the same new file to the same target file on the same filesystem
    assertTrue(fileCopy.exists());
    fileCopy.copyFrom(file, Selectors.SELECT_SELF);

    assertSameContent(content, fileCopy);
}
 
Example 12
Source File: ProviderWriteTests.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Tests create-delete-create-a-file sequence on the same file system.
 */
public void testCreateDeleteCreateSameFileSystem() throws Exception {
    final FileObject scratchFolder = createScratchFolder();

    // Create direct child of the test folder
    final FileObject file = scratchFolder.resolveFile("file1.txt");
    assertFalse(file.exists());

    // Create the source file
    final String content = "Here is some sample content for the file.  Blah Blah Blah.";
    final OutputStream os = file.getContent().getOutputStream();
    try {
        os.write(content.getBytes("utf-8"));
    } finally {
        os.close();
    }

    assertSameContent(content, file);

    // Make sure we can copy the new file to another file on the same filesystem
    final FileObject fileCopy = scratchFolder.resolveFile("file1copy.txt");
    assertFalse(fileCopy.exists());
    fileCopy.copyFrom(file, Selectors.SELECT_SELF);

    assertSameContent(content, fileCopy);

    // Delete the file.
    assertTrue(fileCopy.exists());
    assertTrue(fileCopy.delete());

    // Make sure we can copy the same new file to the same target file on the same filesystem
    assertFalse(fileCopy.exists());
    fileCopy.copyFrom(file, Selectors.SELECT_SELF);

    assertSameContent(content, fileCopy);
}
 
Example 13
Source File: ProviderWriteAppendTests.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Tests create-delete-create-a-file sequence on the same file system.
 */
public void testAppendContent() throws Exception {
    final FileObject scratchFolder = createScratchFolder();

    // Create direct child of the test folder
    final FileObject file = scratchFolder.resolveFile("file1.txt");
    assertFalse(file.exists());

    // Create the source file
    final String content = "Here is some sample content for the file.  Blah Blah Blah.";
    final String contentAppend = content + content;

    final OutputStream os = file.getContent().getOutputStream();
    try {
        os.write(content.getBytes("utf-8"));
    } finally {
        os.close();
    }
    assertSameContent(content, file);

    // Append to the new file
    final OutputStream os2 = file.getContent().getOutputStream(true);
    try {
        os2.write(content.getBytes("utf-8"));
    } finally {
        os2.close();
    }
    assertSameContent(contentAppend, file);

    // Make sure we can copy the new file to another file on the same filesystem
    final FileObject fileCopy = scratchFolder.resolveFile("file1copy.txt");
    assertFalse(fileCopy.exists());
    fileCopy.copyFrom(file, Selectors.SELECT_SELF);

    assertSameContent(contentAppend, fileCopy);

    // Delete the file.
    assertTrue(fileCopy.exists());
    assertTrue(fileCopy.delete());
}
 
Example 14
Source File: Shell.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Does a 'cp' command.
 */
private void cp(final String[] cmd) throws Exception {
    if (cmd.length < 3) {
        throw new Exception("USAGE: cp <src> <dest>");
    }

    final FileObject src = mgr.resolveFile(cwd, cmd[1]);
    FileObject dest = mgr.resolveFile(cwd, cmd[2]);
    if (dest.exists() && dest.getType() == FileType.FOLDER) {
        dest = dest.resolveFile(src.getName().getBaseName());
    }

    dest.copyFrom(src, Selectors.SELECT_ALL);
}
 
Example 15
Source File: AbstractFileObject.java    From commons-vfs with Apache License 2.0 4 votes vote down vote up
/**
 * Moves (rename) the file to another one.
 *
 * @param destFile The target FileObject.
 * @throws FileSystemException if an error occurs.
 */
@Override
public void moveTo(final FileObject destFile) throws FileSystemException {
    if (canRenameTo(destFile)) {
        if (!getParent().isWriteable()) {
            throw new FileSystemException("vfs.provider/rename-parent-read-only.error", getName(),
                    getParent().getName());
        }
    } else {
        if (!isWriteable()) {
            throw new FileSystemException("vfs.provider/rename-read-only.error", getName());
        }
    }

    if (destFile.exists() && !isSameFile(destFile)) {
        destFile.deleteAll();
        // throw new FileSystemException("vfs.provider/rename-dest-exists.error", destFile.getName());
    }

    if (canRenameTo(destFile)) {
        // issue rename on same filesystem
        try {
            attach();
            // remember type to avoid attach
            final FileType srcType = getType();

            doRename(destFile);

            FileObjectUtils.getAbstractFileObject(destFile).handleCreate(srcType);
            destFile.close(); // now the destFile is no longer imaginary. force reattach.

            handleDelete(); // fire delete-events. This file-object (src) is like deleted.
        } catch (final RuntimeException re) {
            throw re;
        } catch (final Exception exc) {
            throw new FileSystemException("vfs.provider/rename.error", exc, getName(), destFile.getName());
        }
    } else {
        // different fs - do the copy/delete stuff

        destFile.copyFrom(this, Selectors.SELECT_SELF);

        if ((destFile.getType().hasContent()
                && destFile.getFileSystem().hasCapability(Capability.SET_LAST_MODIFIED_FILE)
                || destFile.getType().hasChildren()
                        && destFile.getFileSystem().hasCapability(Capability.SET_LAST_MODIFIED_FOLDER))
                && fileSystem.hasCapability(Capability.GET_LAST_MODIFIED)) {
            destFile.getContent().setLastModifiedTime(this.getContent().getLastModifiedTime());
        }

        deleteSelf();
    }

}
 
Example 16
Source File: ProviderWriteTests.java    From commons-vfs with Apache License 2.0 4 votes vote down vote up
/**
 * Check listeners are notified of changes.
 */
public void testListener() throws Exception {
    final FileObject baseFile = createScratchFolder();

    final FileObject child = baseFile.resolveFile("newfile.txt");
    assertFalse(child.exists());

    final FileSystem fs = baseFile.getFileSystem();
    final TestListener listener = new TestListener(child);
    fs.addListener(child, listener);
    try {
        // Create as a folder
        listener.addCreateEvent();
        child.createFolder();
        listener.assertFinished();

        // Create the folder again. Should not get an event.
        child.createFolder();

        // Delete
        listener.addDeleteEvent();
        child.delete();
        listener.assertFinished();

        // Delete again. Should not get an event
        child.delete();

        // Create as a file
        listener.addCreateEvent();
        child.createFile();
        listener.assertFinished();

        // Create the file again. Should not get an event
        child.createFile();

        listener.addDeleteEvent();
        child.delete();

        // Create as a file, by writing to it.
        listener.addCreateEvent();
        child.getContent().getOutputStream().close();
        listener.assertFinished();

        // Recreate the file by writing to it
        child.getContent().getOutputStream().close();

        // Copy another file over the top
        final FileObject otherChild = baseFile.resolveFile("folder1");
        otherChild.createFolder();
        listener.addDeleteEvent();
        listener.addCreateEvent();
        child.copyFrom(otherChild, Selectors.SELECT_SELF);
        listener.assertFinished();

    } finally {
        fs.removeListener(child, listener);
    }
}