Example usage for org.apache.commons.vfs2 FileObject moveTo

List of usage examples for org.apache.commons.vfs2 FileObject moveTo

Introduction

In this page you can find the example usage for org.apache.commons.vfs2 FileObject moveTo.

Prototype

void moveTo(FileObject destFile) throws FileSystemException;

Source Link

Document

Move this file.

Usage

From source file:org.wso2.carbon.transport.remotefilesystem.client.connector.contractimpl.VFSClientConnectorImpl.java

@Override
public void send(RemoteFileSystemMessage message) {
    FtpFileSystemConfigBuilder.getInstance().setPassiveMode(opts, true);
    String fileURI = connectorConfig.get(Constants.URI);
    String action = connectorConfig.get(Constants.ACTION);
    FileType fileType;/*from w  w w.  j a va2s  .  c  om*/
    ByteBuffer byteBuffer;
    InputStream inputStream = null;
    OutputStream outputStream = null;
    FileObject path = null;
    try {
        FileSystemManager fsManager = VFS.getManager();
        path = fsManager.resolveFile(fileURI, opts);
        fileType = path.getType();
        switch (action) {
        case Constants.CREATE:
            boolean isFolder = Boolean
                    .parseBoolean(connectorConfig.getOrDefault(Constants.CREATE_FOLDER, "false"));
            if (path.exists()) {
                throw new RemoteFileSystemConnectorException("File already exists: " + path.getName().getURI());
            }
            if (isFolder) {
                path.createFolder();
            } else {
                path.createFile();
            }
            break;
        case Constants.WRITE:
            if (!path.exists()) {
                path.createFile();
                path.refresh();
                fileType = path.getType();
            }
            if (fileType == FileType.FILE) {
                byteBuffer = message.getBytes();
                byte[] bytes = byteBuffer.array();
                if (connectorConfig.get(Constants.APPEND) != null) {
                    outputStream = path.getContent()
                            .getOutputStream(Boolean.parseBoolean(connectorConfig.get(Constants.APPEND)));
                } else {
                    outputStream = path.getContent().getOutputStream();
                }
                outputStream.write(bytes);
                outputStream.flush();
            }
            break;
        case Constants.DELETE:
            if (path.exists()) {
                int filesDeleted = path.delete(Selectors.SELECT_ALL);
                if (logger.isDebugEnabled()) {
                    logger.debug(filesDeleted + " files successfully deleted");
                }
            } else {
                throw new RemoteFileSystemConnectorException(
                        "Failed to delete file: " + path.getName().getURI() + " not found");
            }
            break;
        case Constants.COPY:
            if (path.exists()) {
                String destination = connectorConfig.get(Constants.DESTINATION);
                FileObject dest = fsManager.resolveFile(destination, opts);
                dest.copyFrom(path, Selectors.SELECT_ALL);
            } else {
                throw new RemoteFileSystemConnectorException(
                        "Failed to copy file: " + path.getName().getURI() + " not found");
            }
            break;
        case Constants.MOVE:
            if (path.exists()) {
                //TODO: Improve this to fix issue #331
                String destination = connectorConfig.get(Constants.DESTINATION);
                FileObject newPath = fsManager.resolveFile(destination, opts);
                FileObject parent = newPath.getParent();
                if (parent != null && !parent.exists()) {
                    parent.createFolder();
                }
                if (!newPath.exists()) {
                    path.moveTo(newPath);
                } else {
                    throw new RemoteFileSystemConnectorException("The file at " + newPath.getURL().toString()
                            + " already exists or it is a directory");
                }
            } else {
                throw new RemoteFileSystemConnectorException(
                        "Failed to move file: " + path.getName().getURI() + " not found");
            }
            break;
        case Constants.READ:
            if (path.exists()) {
                //TODO: Do not assume 'path' always refers to a file
                inputStream = path.getContent().getInputStream();
                byte[] bytes = toByteArray(inputStream);
                RemoteFileSystemMessage fileContent = new RemoteFileSystemMessage(ByteBuffer.wrap(bytes));
                remoteFileSystemListener.onMessage(fileContent);
            } else {
                throw new RemoteFileSystemConnectorException(
                        "Failed to read file: " + path.getName().getURI() + " not found");
            }
            break;
        case Constants.EXISTS:
            RemoteFileSystemMessage fileContent = new RemoteFileSystemMessage(Boolean.toString(path.exists()));
            remoteFileSystemListener.onMessage(fileContent);
            break;
        default:
            break;
        }
        remoteFileSystemListener.done();
    } catch (RemoteFileSystemConnectorException | IOException e) {
        remoteFileSystemListener.onError(e);
    } finally {
        if (path != null) {
            try {
                path.close();
            } catch (FileSystemException e) {
                //Do nothing.
            }
        }
        closeQuietly(inputStream);
        closeQuietly(outputStream);
    }
}

From source file:org.wso2.carbon.transport.remotefilesystem.server.RemoteFileSystemConsumer.java

/**
 * Do the post processing actions.// ww  w. j  a va  2s.c o  m
 *
 * @param file The file object which needs to be post processed
 * @param processSucceed Whether processing of file passed or not.
 */
synchronized void postProcess(FileObject file, boolean processSucceed)
        throws RemoteFileSystemConnectorException {
    String moveToDirectoryURI = null;
    FileType fileType = getFileType(file);
    if (processSucceed) {
        if (postProcessAction.equals(Constants.ACTION_MOVE)) {
            moveToDirectoryURI = fileProperties.get(Constants.MOVE_AFTER_PROCESS);
        }
    } else {
        if (postFailureAction.equals(Constants.ACTION_MOVE)) {
            moveToDirectoryURI = fileProperties.get(Constants.MOVE_AFTER_FAILURE);
        }
    }
    if (moveToDirectoryURI != null) {
        try {
            if (getFileType(fsManager.resolveFile(moveToDirectoryURI, fso)) == FileType.FILE) {
                moveToDirectoryURI = null;
                if (processSucceed) {
                    postProcessAction = Constants.ACTION_NONE;
                } else {
                    postFailureAction = Constants.ACTION_NONE;
                }
                log.warn("[" + serviceName + "] Cannot move file because provided location is not a folder."
                        + " File is kept at source.");
            }
        } catch (FileSystemException e) {
            remoteFileSystemListener.onError(new RemoteFileSystemConnectorException(
                    "Error occurred when resolving move destination file: "
                            + FileTransportUtils.maskURLPassword(listeningDirURI),
                    e));
        }
    }
    if (postProcessAction.equals(Constants.ACTION_NONE) && fileType == FileType.FOLDER) {
        return;
    }
    try {
        if (!(moveToDirectoryURI == null || fileType == FileType.FOLDER)) {
            FileObject moveToDirectory;
            String relativeName = file.getName().getURI().split(listeningDir.getName().getURI())[1];
            int index = relativeName.lastIndexOf(File.separator);
            moveToDirectoryURI += relativeName.substring(0, index);
            moveToDirectory = fsManager.resolveFile(moveToDirectoryURI, fso);
            String prefix;
            if (fileProperties.get(Constants.MOVE_TIMESTAMP_FORMAT) != null) {
                prefix = new SimpleDateFormat(fileProperties.get(Constants.MOVE_TIMESTAMP_FORMAT))
                        .format(new Date());
            } else {
                prefix = "";
            }
            //Forcefully create the folder(s) if does not exists
            String strForceCreateFolder = fileProperties.get(Constants.FORCE_CREATE_FOLDER);
            if (strForceCreateFolder != null && strForceCreateFolder.equalsIgnoreCase("true")
                    && !moveToDirectory.exists()) {
                moveToDirectory.createFolder();
            }
            FileObject destination = moveToDirectory.resolveFile(prefix + file.getName().getBaseName());
            if (log.isDebugEnabled()) {
                log.debug("Moving file: " + FileTransportUtils.maskURLPassword(file.getName().getBaseName()));
            }
            try {
                file.moveTo(destination);
                if (isFailRecord(file)) {
                    releaseFail(file);
                }
            } catch (FileSystemException e) {
                if (!isFailRecord(file)) {
                    markFailRecord(file);
                }
                remoteFileSystemListener.onError(new RemoteFileSystemConnectorException("[" + serviceName
                        + "] Error moving file: " + FileTransportUtils.maskURLPassword(file.toString()) + " to "
                        + FileTransportUtils.maskURLPassword(moveToDirectoryURI), e));
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Deleting file: " + FileTransportUtils.maskURLPassword(file.getName().getBaseName()));
            }
            try {
                if (!file.delete()) {
                    if (log.isDebugEnabled()) {
                        log.debug("Could not delete file: "
                                + FileTransportUtils.maskURLPassword(file.getName().getBaseName()));
                    }
                } else {
                    if (isFailRecord(file)) {
                        releaseFail(file);
                    }
                }
            } catch (FileSystemException e) {
                remoteFileSystemListener.onError(
                        new RemoteFileSystemConnectorException("[" + serviceName + "] Could not delete file: "
                                + FileTransportUtils.maskURLPassword(file.getName().getBaseName()), e));
            }
        }
    } catch (FileSystemException e) {
        if (!isFailRecord(file)) {
            markFailRecord(file);
            remoteFileSystemListener.onError(new RemoteFileSystemConnectorException(
                    "[" + serviceName + "] Error resolving directory to move file : "
                            + FileTransportUtils.maskURLPassword(moveToDirectoryURI),
                    e));
        }
    }
}

From source file:se.kth.hopsworks.zeppelin.notebook.repo.FSNotebookRepo.java

@Override
public void save(Note note) throws IOException {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setPrettyPrinting();//from www . java2s . c  o  m
    Gson gson = gsonBuilder.create();
    String json = gson.toJson(note);

    FileObject rootDir = getRootDir();

    FileObject projectDir = rootDir.resolveFile(this.project.getName(), NameScope.CHILD);
    if (!projectDir.exists()) {
        projectDir.createFolder();
    }
    if (!isDirectory(projectDir)) {
        throw new IOException(projectDir.getName().toString() + " is not a directory");
    }

    FileObject noteDir = projectDir.resolveFile(note.id(), 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));
}

From source file:sftpexamples.SftpUtility.java

public static boolean move(String hostName, String username, String password, String remoteSrcFilePath,
        String remoteDestFilePath) {
    StandardFileSystemManager manager = new StandardFileSystemManager();

    try {/*from www.j a  v a2  s.com*/
        manager.init();

        // Create remote object
        FileObject remoteFile = manager.resolveFile(
                createConnectionString(hostName, username, password, remoteSrcFilePath),
                createDefaultOptions());
        FileObject remoteDestFile = manager.resolveFile(
                createConnectionString(hostName, username, password, remoteDestFilePath),
                createDefaultOptions());

        if (remoteFile.exists()) {
            remoteFile.moveTo(remoteDestFile);
            ;
            System.out.println("Move remote file success");
            return true;
        } else {
            System.out.println("Source file doesn't exist");
            return false;
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        manager.close();
    }
}