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.pentaho.vfs.ui.VfsBrowser.java

public boolean renameItem(TreeItem ti, String newName) throws FileSystemException {
    FileObject file = (FileObject) ti.getData();
    FileObject newFileObject = file.getParent().resolveFile(newName);

    if (file.canRenameTo(newFileObject)) {
        if (!newFileObject.exists()) {
            newFileObject.createFile();/* w  ww .  j  a  va  2s  . c o m*/
        } else {
            return false;
        }
        file.moveTo(newFileObject);
        ti.setText(newName);
        ti.setData(newFileObject);
        return true;
    } else {
        return false;
    }

}

From source file:org.pentaho.vfs.ui.VfsBrowser.java

public boolean moveItem(TreeItem source, TreeItem destination) throws FileSystemException {
    FileObject file = (FileObject) source.getData();
    FileObject destFile = (FileObject) destination.getData();
    if (!file.exists() && !destFile.exists()) {
        return false;
    }/*from   ww  w .  ja v a2s.com*/
    try {
        if (destFile.getChildren() != null) {
            destFile = destFile.resolveFile(source.getText());
        }
    } catch (Exception e) {
        destFile = destFile.getParent().resolveFile(source.getText());
        destination = destination.getParentItem();
    }
    if (!file.getParent().equals(destFile.getParent())) {
        file.moveTo(destFile);
        TreeItem destTreeItem = new TreeItem(destination, SWT.NONE);
        destTreeItem.setImage(getFileImage(source.getDisplay()));
        destTreeItem.setData(destFile);
        destTreeItem.setData("isLoaded", Boolean.FALSE); //$NON-NLS-1$
        populateTreeItemText(destTreeItem, destFile);
        source.dispose();
    }
    return true;
}

From source file:org.wso2.carbon.connector.FileMove.java

/**
 * Move the files//  www  . ja  v a2  s . co  m
 *
 * @param source      Location of the file
 * @param destination Destination of the file
 * @return return a resultStatus
 */
private boolean moveFile(String source, String destination, MessageContext messageContext) {
    boolean resultStatus = false;
    StandardFileSystemManager manager = null;
    try {
        manager = FileConnectorUtils.getManager();
        // Create remote object
        FileObject remoteFile = manager.resolveFile(source, FileConnectorUtils.init(messageContext));
        if (remoteFile.exists()) {
            FileObject file = manager.resolveFile(destination, FileConnectorUtils.init(messageContext));
            if (!file.exists()) {
                file.createFolder();
            }
            if (remoteFile.getType() == FileType.FOLDER) {
                remoteFile.moveTo(file);
            } else if (remoteFile.getType() == FileType.FILE) {
                FileObject newFile = manager.resolveFile(
                        destination + File.separator + remoteFile.getName().getBaseName(),
                        FileConnectorUtils.init(messageContext));
                remoteFile.moveTo(newFile);
            }
            resultStatus = true;
            if (log.isDebugEnabled()) {
                log.debug("File move completed from " + source + " to " + destination);
            }
        } else {
            log.error("The file/folder location does not exist.");
            resultStatus = false;
        }
    } catch (IOException e) {
        handleException("Unable to move a file/folder.", e, messageContext);
    } finally {
        if (manager != null) {
            manager.close();
        }
    }
    return resultStatus;
}

From source file:org.wso2.carbon.connector.FileMoveConnector.java

/**
 * Move the file to the target directory.
 *
 * @param destination The target location of the folder to be moved.
 * @param remoteFile  Location of the remote file.
 * @param manager     Standard file system manager.
 * @param opts        Configured file system options.
 * @throws FileSystemException On error parsing the file name, determining if the file exists and creating the
 *                             file/folder.
 *//*from w  w w . j  av  a  2  s. c  om*/
private void moveFile(String destination, FileObject remoteFile, StandardFileSystemManager manager,
        FileSystemOptions opts) throws FileSystemException {
    FileObject file = manager.resolveFile(destination, opts);
    if (FileConnectorUtils.isFolder(file)) {
        if (!file.exists()) {
            file.createFolder();
        }
        file = manager.resolveFile(destination + File.separator + remoteFile.getName().getBaseName(), opts);
    } else if (!file.exists()) {
        file.createFile();
    }
    remoteFile.moveTo(file);
}

From source file:org.wso2.carbon.connector.FileMoveConnector.java

/**
 * Move the folder to the target directory.
 *
 * @param destination            The target location of the folder to move folder.
 * @param source                 Location of the source folder.
 * @param includeParentDirectory Boolean type to include the parent directory.
 * @param manager                Standard file system manager.
 * @param opts                   Configured file system options.
 *//*from  w  w  w. j a va  2  s  .com*/
private void moveFolder(String source, String destination, String filePattern, boolean includeParentDirectory,
        StandardFileSystemManager manager, FileSystemOptions opts) throws FileSystemException {
    FileObject remoteFile = manager.resolveFile(source, opts);
    FileObject file = manager.resolveFile(destination, opts);
    if (StringUtils.isNotEmpty(filePattern)) {
        FileObject[] children = remoteFile.getChildren();
        for (FileObject child : children) {
            if (FileType.FILE.equals(child.getType())) {
                moveFileWithPattern(child, destination, filePattern, manager, opts);
            } else if (FileType.FOLDER.equals(child.getType())) {
                String newSource = source + File.separator + child.getName().getBaseName();
                moveFolder(newSource, destination, filePattern, includeParentDirectory, manager, opts);
            }
        }
    } else if (includeParentDirectory) {
        FileObject destFile = manager
                .resolveFile(destination + File.separator + remoteFile.getName().getBaseName(), opts);
        destFile.createFolder();
        remoteFile.moveTo(destFile);
    } else {
        if (!file.exists()) {
            file.createFolder();
        }
        remoteFile.moveTo(file);
        remoteFile.createFolder();
    }
}

From source file:org.wso2.carbon.connector.FileMoveConnector.java

/**
 * Move the file for given pattern.//w  w w.ja  v  a 2  s.c o m
 *
 * @param remoteFile  Location of the remote file.
 * @param destination Location of the target folder.
 * @param filePattern Pattern of the file.
 * @param manager     Standard file system manager.
 * @param opts        Configured file system options.
 */
private void moveFileWithPattern(FileObject remoteFile, String destination, String filePattern,
        StandardFileSystemManager manager, FileSystemOptions opts) {
    FilePattenMatcher patternMatcher = new FilePattenMatcher(filePattern);
    try {
        if (patternMatcher.validate(remoteFile.getName().getBaseName())) {
            FileObject destFile = manager.resolveFile(destination, opts);
            if (!destFile.exists()) {
                destFile.createFolder();
            }
            FileObject newDestFile = manager
                    .resolveFile(destination + File.separator + remoteFile.getName().getBaseName(), opts);
            remoteFile.moveTo(newDestFile);
        }
    } catch (FileSystemException e) {
        throw new SynapseException("Error occurred while moving a file for a given pattern", e);
    }
}

From source file:org.wso2.carbon.connector.FileRename.java

/**
 * Rename the files//  ww w  . j a v a 2  s .  c o m
 * 
 * @param fileLocation
 * @param filename
 * @param newFileName
 * @param filebeforepprocess
 * @return
 */
private boolean renameFile(String fileLocation, String filename, String newFileName, String filebeforepprocess)
        throws FileSystemException {
    boolean resultStatus = false;
    FileSystemManager manager = VFS.getManager();
    if (manager != null) {
        // Create remote object
        FileObject remoteFile = manager.resolveFile(fileLocation.toString() + filename.toString(),
                FTPSiteUtils.createDefaultOptions());

        FileObject reNameFile = manager.resolveFile(fileLocation.toString() + newFileName.toString(),
                FTPSiteUtils.createDefaultOptions());
        if (remoteFile.exists()) {
            if (!filebeforepprocess.equals("")) {
                FileObject fBeforeProcess = manager.resolveFile(filebeforepprocess + filename);
                fBeforeProcess.copyFrom(remoteFile, Selectors.SELECT_SELF_AND_CHILDREN);
            }

            remoteFile.moveTo(reNameFile);
            resultStatus = true;
            if (log.isDebugEnabled()) {
                log.info("Rename remote file success");
            }
        }
    }

    return resultStatus;
}

From source file:org.wso2.carbon.inbound.endpoint.protocol.file.FilePollingConsumer.java

/**
 * Do the post processing actions// w w  w . j a  v a2s .  c om
 * 
 * @param fileObject
 * @throws synapseException
 */
private void moveOrDeleteAfterProcessing(FileObject fileObject) throws SynapseException {

    String moveToDirectoryURI = null;
    try {
        switch (lastCycle) {
        case 1:
            if ("MOVE".equals(vfsProperties.getProperty(VFSConstants.TRANSPORT_FILE_ACTION_AFTER_PROCESS))) {
                moveToDirectoryURI = vfsProperties.getProperty(VFSConstants.TRANSPORT_FILE_MOVE_AFTER_PROCESS);
                //Postfix the date given timestamp format
                String strSubfoldertimestamp = vfsProperties.getProperty(VFSConstants.SUBFOLDER_TIMESTAMP);
                if (strSubfoldertimestamp != null) {
                    try {
                        SimpleDateFormat sdf = new SimpleDateFormat(strSubfoldertimestamp);
                        String strDateformat = sdf.format(new Date());
                        int iIndex = moveToDirectoryURI.indexOf("?");
                        if (iIndex > -1) {
                            moveToDirectoryURI = moveToDirectoryURI.substring(0, iIndex) + strDateformat
                                    + moveToDirectoryURI.substring(iIndex, moveToDirectoryURI.length());
                        } else {
                            moveToDirectoryURI += strDateformat;
                        }
                    } catch (Exception e) {
                        log.warn("Error generating subfolder name with date", e);
                    }
                }
            }
            break;

        case 2:
            if ("MOVE".equals(vfsProperties.getProperty(VFSConstants.TRANSPORT_FILE_ACTION_AFTER_FAILURE))) {
                moveToDirectoryURI = vfsProperties.getProperty(VFSConstants.TRANSPORT_FILE_MOVE_AFTER_FAILURE);
            }
            break;

        default:
            return;
        }

        if (moveToDirectoryURI != null) {
            FileObject moveToDirectory = fsManager.resolveFile(moveToDirectoryURI, fso);
            String prefix;
            if (vfsProperties.getProperty(VFSConstants.TRANSPORT_FILE_MOVE_TIMESTAMP_FORMAT) != null) {
                prefix = new SimpleDateFormat(
                        vfsProperties.getProperty(VFSConstants.TRANSPORT_FILE_MOVE_TIMESTAMP_FORMAT))
                                .format(new Date());
            } else {
                prefix = "";
            }

            //Forcefully create the folder(s) if does not exists
            String strForceCreateFolder = vfsProperties.getProperty(VFSConstants.FORCE_CREATE_FOLDER);
            if (strForceCreateFolder != null && strForceCreateFolder.toLowerCase().equals("true")
                    && !moveToDirectory.exists()) {
                moveToDirectory.createFolder();
            }

            FileObject dest = moveToDirectory.resolveFile(prefix + fileObject.getName().getBaseName());
            if (log.isDebugEnabled()) {
                log.debug("Moving to file :" + VFSUtils.maskURLPassword(dest.getName().getURI()));
            }
            try {
                fileObject.moveTo(dest);
                if (VFSUtils.isFailRecord(fsManager, fileObject)) {
                    VFSUtils.releaseFail(fsManager, fileObject);
                }
            } catch (FileSystemException e) {
                if (!VFSUtils.isFailRecord(fsManager, fileObject)) {
                    VFSUtils.markFailRecord(fsManager, fileObject);
                }
                log.error("Error moving file : " + VFSUtils.maskURLPassword(fileObject.toString()) + " to "
                        + VFSUtils.maskURLPassword(moveToDirectoryURI), e);
            }
        } else {
            try {
                if (log.isDebugEnabled()) {
                    log.debug("Deleting file :" + VFSUtils.maskURLPassword(fileObject.toString()));
                }
                fileObject.close();
                if (!fileObject.delete()) {
                    String msg = "Cannot delete file : " + VFSUtils.maskURLPassword(fileObject.toString());
                    log.error(msg);
                    throw new SynapseException(msg);
                }
            } catch (FileSystemException e) {
                log.error("Error deleting file : " + VFSUtils.maskURLPassword(fileObject.toString()), e);
            }
        }
    } catch (FileSystemException e) {
        if (!VFSUtils.isFailRecord(fsManager, fileObject)) {
            VFSUtils.markFailRecord(fsManager, fileObject);
            log.error("Error resolving directory to move after processing : "
                    + VFSUtils.maskURLPassword(moveToDirectoryURI), e);
        }
    }
}

From source file:org.wso2.carbon.transport.file.connector.sender.VFSClientConnector.java

@Override
public boolean send(CarbonMessage carbonMessage, CarbonCallback carbonCallback, Map<String, String> map)
        throws ClientConnectorException {
    FtpFileSystemConfigBuilder.getInstance().setPassiveMode(opts, true);
    String fileURI = map.get(Constants.FILE_URI);
    String action = map.get(Constants.ACTION);
    FileType fileType;// ww w. ja  v a2  s.  com
    ByteBuffer byteBuffer;
    InputStream inputStream = null;
    OutputStream outputStream = null;
    try {
        FileSystemManager fsManager = VFS.getManager();
        FileObject path = fsManager.resolveFile(fileURI, opts);
        fileType = path.getType();
        switch (action) {

        case Constants.CREATE:
            boolean isFolder = Boolean.parseBoolean(map.getOrDefault("create-folder", "false"));
            if (path.exists()) {
                throw new ClientConnectorException("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) {
                if (carbonMessage instanceof BinaryCarbonMessage) {
                    BinaryCarbonMessage binaryCarbonMessage = (BinaryCarbonMessage) carbonMessage;
                    byteBuffer = binaryCarbonMessage.readBytes();
                } else {
                    throw new ClientConnectorException("Carbon message received is not a BinaryCarbonMessage");
                }
                byte[] bytes = byteBuffer.array();
                if (map.get(Constants.APPEND) != null) {
                    outputStream = path.getContent()
                            .getOutputStream(Boolean.parseBoolean(map.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 ClientConnectorException(
                        "Failed to delete file: " + path.getName().getURI() + " not found");
            }
            break;
        case Constants.COPY:
            if (path.exists()) {
                String destination = map.get("destination");
                FileObject dest = fsManager.resolveFile(destination, opts);
                dest.copyFrom(path, Selectors.SELECT_ALL);
            } else {
                throw new ClientConnectorException(
                        "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 = map.get("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 ClientConnectorException("The file at " + newPath.getURL().toString()
                            + " already exists or it is a directory");
                }
            } else {
                throw new ClientConnectorException(
                        "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);
                BinaryCarbonMessage message = new BinaryCarbonMessage(ByteBuffer.wrap(bytes), true);
                message.setProperty(org.wso2.carbon.messaging.Constants.DIRECTION,
                        org.wso2.carbon.messaging.Constants.DIRECTION_RESPONSE);
                carbonMessageProcessor.receive(message, carbonCallback);
            } else {
                throw new ClientConnectorException(
                        "Failed to read file: " + path.getName().getURI() + " not found");
            }
            break;
        case Constants.EXISTS:
            TextCarbonMessage message = new TextCarbonMessage(Boolean.toString(path.exists()));
            message.setProperty(org.wso2.carbon.messaging.Constants.DIRECTION,
                    org.wso2.carbon.messaging.Constants.DIRECTION_RESPONSE);
            carbonMessageProcessor.receive(message, carbonCallback);
            break;
        default:
            return false;
        }
    } catch (RuntimeException e) {
        throw new ClientConnectorException("Runtime Exception occurred : " + e.getMessage(), e);
    } catch (Exception e) {
        throw new ClientConnectorException("Exception occurred while processing file: " + e.getMessage(), e);
    } finally {
        closeQuietly(inputStream);
        closeQuietly(outputStream);
    }
    return true;
}

From source file:org.wso2.carbon.transport.filesystem.connector.server.FileSystemConsumer.java

/**
 * Do the post processing actions./*from w w  w  . j a  va2 s  .  c  o  m*/
 *
 * @param file The file object which needs to be post processed
 * @param processFailed Whether processing of file failed
 */
synchronized void postProcess(FileObject file, boolean processFailed)
        throws FileSystemServerConnectorException {
    String moveToDirectoryURI = null;
    FileType fileType = getFileType(file);
    if (!processFailed) {
        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 (processFailed) {
                    postFailureAction = Constants.ACTION_NONE;
                } else {
                    postProcessAction = Constants.ACTION_NONE;
                }
                if (log.isDebugEnabled()) {
                    log.debug(
                            "Cannot move file because provided location is not a folder. File is kept at source");
                }
            }
        } catch (FileSystemException e) {
            errorHandler
                    .handleError(
                            new FileSystemServerConnectorException(
                                    "Error occurred when resolving move destination file: "
                                            + FileTransportUtils.maskURLPassword(listeningDirURI),
                                    e),
                            null, null);
        }
    }

    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 dest = moveToDirectory.resolveFile(prefix + file.getName().getBaseName());
            if (log.isDebugEnabled()) {
                log.debug("Moving to file :" + FileTransportUtils.maskURLPassword(dest.getName().getURI()));
            }
            if (log.isInfoEnabled()) {
                log.info("Moving file :" + FileTransportUtils.maskURLPassword(file.getName().getBaseName()));
            }
            try {
                file.moveTo(dest);
                if (isFailRecord(file)) {
                    releaseFail(file);
                }
            } catch (FileSystemException e) {
                if (!isFailRecord(file)) {
                    markFailRecord(file);
                }
                errorHandler.handleError(
                        new FileSystemServerConnectorException(
                                "Error moving file : " + FileTransportUtils.maskURLPassword(file.toString())
                                        + " to " + FileTransportUtils.maskURLPassword(moveToDirectoryURI),
                                e),
                        null, null);
            }

        } else {
            if (log.isDebugEnabled()) {
                log.debug("Deleting file :" + FileTransportUtils.maskURLPassword(file.getName().getBaseName()));
            }
            if (log.isInfoEnabled()) {
                log.info("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) {
                errorHandler.handleError(
                        new FileSystemServerConnectorException("Could not delete file : "
                                + FileTransportUtils.maskURLPassword(file.getName().getBaseName()), e),
                        null, null);
            }
        }
    } catch (FileSystemException e) {
        if (!isFailRecord(file)) {
            markFailRecord(file);
            errorHandler.handleError(
                    new FileSystemServerConnectorException("Error resolving directory to move file : "
                            + FileTransportUtils.maskURLPassword(moveToDirectoryURI), e),
                    null, null);
        }
    }
}