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:com.googlecode.vfsjfilechooser2.plaf.basic.BasicVFSDirectoryModel.java

/**
 * Renames a file in the underlying file system.
 *
 * @param oldFile a <code>File</code> object representing
 *        the existing file//  w  ww .  j a v  a  2  s  . co m
 * @param newFile a <code>File</code> object representing
 *        the desired new file name
 * @return <code>true</code> if rename succeeded,
 *        otherwise <code>false</code>
 * @since 1.4
 */
public boolean renameFile(FileObject oldFile, FileObject newFile) {
    aLock.writeLock().lock();

    try {
        oldFile.moveTo(newFile);
        validateFileCache();

        return true;
    } catch (Exception e) {
        return false;
    } finally {
        aLock.writeLock().unlock();
    }
}

From source file:com.sonicle.webtop.vfs.VfsManager.java

private String doRenameStoreFile(int storeId, String path, String newName)
        throws FileSystemException, SQLException, DAOException, WTException {
    SharingLinkDAO dao = SharingLinkDAO.getInstance();
    FileObject tfo = null, ntfo = null;
    Connection con = null;//from w  w  w.  j av a2s.  c o m

    try {
        tfo = getTargetFileObject(storeId, path);
        String newPath = FilenameUtils
                .separatorsToUnix(FilenameUtils.concat(FilenameUtils.getFullPath(path), newName));
        ntfo = getTargetFileObject(storeId, newPath);

        logger.debug("Renaming store file [{}, {} -> {}]", storeId, path, newPath);
        try {
            con = WT.getConnection(SERVICE_ID, false);

            dao.deleteByStorePath(con, storeId, path);
            tfo.moveTo(ntfo);
            DbUtils.commitQuietly(con);

        } catch (FileSystemException ex1) {
            DbUtils.rollbackQuietly(con);
            throw ex1;
        } finally {
            DbUtils.closeQuietly(con);
        }
        return newPath;

    } finally {
        IOUtils.closeQuietly(tfo);
        IOUtils.closeQuietly(ntfo);
    }
}

From source file:com.yenlo.synapse.transport.vfs.VFSTransportListener.java

/**
 * Take specified action to either move or delete the processed file, depending on the outcome
 * @param entry the PollTableEntry for the file that has been processed
 * @param fileObject the FileObject representing the file to be moved or deleted
 *///  w w  w. j a va  2s . c  o  m
private void moveOrDeleteAfterProcessing(final PollTableEntry entry, FileObject fileObject) throws AxisFault {

    String moveToDirectoryURI = null;
    try {
        switch (entry.getLastPollState()) {
        case PollTableEntry.SUCCSESSFUL:
            if (entry.getActionAfterProcess() == PollTableEntry.MOVE) {
                moveToDirectoryURI = entry.getMoveAfterProcess();
            }
            break;

        case PollTableEntry.FAILED:
            if (entry.getActionAfterFailure() == PollTableEntry.MOVE) {
                moveToDirectoryURI = entry.getMoveAfterFailure();
            }
            break;

        default:
            return;
        }

        if (moveToDirectoryURI != null) {
            FileObject moveToDirectory = fsManager.resolveFile(moveToDirectoryURI);
            String prefix;
            if (entry.getMoveTimestampFormat() != null) {
                prefix = entry.getMoveTimestampFormat().format(new Date());
            } else {
                prefix = "";
            }
            FileObject dest = moveToDirectory.resolveFile(prefix + fileObject.getName().getBaseName());
            if (log.isDebugEnabled()) {
                log.debug("Moving to file :" + dest.getName().getURI());
            }
            try {
                fileObject.moveTo(dest);
            } catch (FileSystemException e) {
                handleException("Error moving file : " + fileObject + " to " + moveToDirectoryURI, e);
            }
        } else {
            try {
                if (log.isDebugEnabled()) {
                    log.debug("Deleting file :" + fileObject);
                }
                fileObject.close();
                if (!fileObject.delete()) {
                    String msg = "Cannot delete file : " + fileObject;
                    log.error(msg);
                    throw new AxisFault(msg);
                }
            } catch (FileSystemException e) {
                log.error("Error deleting file : " + fileObject, e);
            }
        }

    } catch (FileSystemException e) {
        handleException("Error resolving directory to move after processing : " + moveToDirectoryURI, e);
    }
}

From source file:net.sf.jabb.web.action.VfsTreeAction.java

/**
 * AJAX tree functions//from www.  j a v  a 2  s  .co m
 */
public String execute() {
    normalizeTreeRequest();
    JsTreeResult result = new JsTreeResult();

    final AllFileSelector ALL_FILES = new AllFileSelector();
    FileSystemManager fsManager = null;
    FileObject rootFile = null;
    FileObject file = null;
    FileObject referenceFile = null;
    try {
        fsManager = VfsUtility.getManager();
        rootFile = fsManager.resolveFile(rootPath, fsOptions);

        if (JsTreeRequest.OP_GET_CHILDREN.equalsIgnoreCase(requestData.getOperation())) {
            String parentPath = requestData.getId();
            List<JsTreeNodeData> nodes = null;
            try {
                nodes = getChildNodes(rootFile, parentPath);
                if (requestData.isRoot() && rootNodeName != null) { // add root node
                    JsTreeNodeData rootNode = new JsTreeNodeData();
                    rootNode.setData(rootNodeName);
                    Map<String, Object> attr = new HashMap<String, Object>();
                    rootNode.setAttr(attr);
                    attr.put("id", ".");
                    attr.put("rel", "root");
                    attr.put("fileType", FileType.FOLDER.toString());
                    rootNode.setChildren(nodes);
                    rootNode.setState(JsTreeNodeData.STATE_OPEN);
                    nodes = new LinkedList<JsTreeNodeData>();
                    nodes.add(rootNode);
                }
            } catch (Exception e) {
                log.error("Cannot get child nodes for: " + parentPath, e);
                nodes = new LinkedList<JsTreeNodeData>();
            }
            responseData = nodes;
        } else if (JsTreeRequest.OP_REMOVE_NODE.equalsIgnoreCase(requestData.getOperation())) {
            String path = requestData.getId();
            try {
                file = rootFile.resolveFile(path, NameScope.DESCENDENT);
                boolean wasDeleted = false;
                if (file.getType() == FileType.FILE) {
                    wasDeleted = file.delete();
                } else {
                    wasDeleted = file.delete(ALL_FILES) > 0;
                }
                result.setStatus(wasDeleted);
            } catch (Exception e) {
                result.setStatus(false);
                log.error("Cannot delete: " + path, e);
            }
            responseData = result;
        } else if (JsTreeRequest.OP_CREATE_NODE.equalsIgnoreCase(requestData.getOperation())) {
            String parentPath = requestData.getReferenceId();
            String name = requestData.getTitle();
            try {
                referenceFile = rootFile.resolveFile(parentPath, NameScope.DESCENDENT_OR_SELF);
                file = referenceFile.resolveFile(name, NameScope.CHILD);
                file.createFolder();
                result.setStatus(true);
                result.setId(rootFile.getName().getRelativeName(file.getName()));
            } catch (Exception e) {
                result.setStatus(false);
                log.error("Cannot create folder '" + name + "' under '" + parentPath + "'", e);
            }
            responseData = result;
        } else if (JsTreeRequest.OP_RENAME_NODE.equalsIgnoreCase(requestData.getOperation())) {
            String path = requestData.getId();
            String name = requestData.getTitle();
            try {
                referenceFile = rootFile.resolveFile(path, NameScope.DESCENDENT);
                file = referenceFile.getParent().resolveFile(name, NameScope.CHILD);
                referenceFile.moveTo(file);
                result.setStatus(true);
            } catch (Exception e) {
                result.setStatus(false);
                log.error("Cannot rename '" + path + "' to '" + name + "'", e);
            }
            responseData = result;
        } else if (JsTreeRequest.OP_MOVE_NODE.equalsIgnoreCase(requestData.getOperation())) {
            String newParentPath = requestData.getReferenceId();
            String originalPath = requestData.getId();
            try {
                referenceFile = rootFile.resolveFile(originalPath, NameScope.DESCENDENT);
                file = rootFile.resolveFile(newParentPath, NameScope.DESCENDENT_OR_SELF)
                        .resolveFile(referenceFile.getName().getBaseName(), NameScope.CHILD);
                if (requestData.isCopy()) {
                    file.copyFrom(referenceFile, ALL_FILES);
                } else {
                    referenceFile.moveTo(file);
                }
                result.setStatus(true);
            } catch (Exception e) {
                result.setStatus(false);
                log.error("Cannot move '" + originalPath + "' to '" + newParentPath + "'", e);
            }
            responseData = result;
        }
    } catch (FileSystemException e) {
        log.error("Cannot perform file operation.", e);
    } finally {
        VfsUtility.close(fsManager, file, referenceFile, rootFile);
    }
    return SUCCESS;
}

From source file:org.apache.synapse.transport.vfs.VFSTransportListener.java

/**
 * Take specified action to either move or delete the processed file, depending on the outcome
 * @param entry the PollTableEntry for the file that has been processed
 * @param fileObject the FileObject representing the file to be moved or deleted
 *//*ww  w . j a  v a  2  s . c  o m*/
private void moveOrDeleteAfterProcessing(final PollTableEntry entry, FileObject fileObject,
        FileSystemOptions fso) throws AxisFault {

    String moveToDirectoryURI = null;
    try {
        switch (entry.getLastPollState()) {
        case PollTableEntry.SUCCSESSFUL:
            if (entry.getActionAfterProcess() == PollTableEntry.MOVE) {
                moveToDirectoryURI = entry.getMoveAfterProcess();
                //Postfix the date given timestamp format
                String strSubfoldertimestamp = entry.getSubfolderTimestamp();
                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 PollTableEntry.FAILED:
            if (entry.getActionAfterFailure() == PollTableEntry.MOVE) {
                moveToDirectoryURI = entry.getMoveAfterFailure();
            }
            break;

        default:
            return;
        }

        if (moveToDirectoryURI != null) {
            FileObject moveToDirectory = fsManager.resolveFile(moveToDirectoryURI, fso);
            String prefix;
            if (entry.getMoveTimestampFormat() != null) {
                prefix = entry.getMoveTimestampFormat().format(new Date());
            } else {
                prefix = "";
            }

            //Forcefully create the folder(s) if does not exists
            if (entry.isForceCreateFolder() && !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);
            } catch (FileSystemException e) {
                handleException("Error moving file : " + VFSUtils.maskURLPassword(fileObject.toString())
                        + " to " + VFSUtils.maskURLPassword(moveToDirectoryURI), e);
            } finally {
                try {
                    fileObject.close();
                } catch (FileSystemException ignore) {
                }
            }
        } 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 AxisFault(msg);
                }
            } catch (FileSystemException e) {
                log.error("Error deleting file : " + VFSUtils.maskURLPassword(fileObject.toString()), e);
            }
        }

    } catch (FileSystemException e) {
        handleException("Error resolving directory to move after processing : "
                + VFSUtils.maskURLPassword(moveToDirectoryURI), e);
    }
}

From source file:org.apache.zeppelin.notebook.repo.OldVFSNotebookRepo.java

@Override
public synchronized void save(Note note, AuthenticationInfo subject) throws IOException {
    LOG.info("Saving note:" + note.getId());
    String json = note.toJson();//from   w  ww  .ja v a2  s.  co  m

    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));
}

From source file:org.efaps.db.store.VFSStoreResource.java

/**
 * Method that deletes the oldest backup and moves the others one up.
 *
 * @param _backup   file to backup/*from  w w  w .  j  a va2s.  c  o  m*/
 * @param _number         number of backup
 * @throws FileSystemException on error
 */
private void backup(final FileObject _backup, final int _number) throws FileSystemException {
    if (_number < this.numberBackup) {
        final FileObject backFile = this.manager.resolveFile(this.manager.getBaseFile(),
                this.storeFileName + VFSStoreResource.EXTENSION_BACKUP + _number);
        if (backFile.exists()) {
            backup(backFile, _number + 1);
        }
        _backup.moveTo(backFile);
    } else {
        _backup.delete();
    }
}

From source file:org.efaps.db.store.VFSStoreResource.java

/**
 * The method is called from the transaction manager if the complete
 * transaction is completed.<br/>/*w ww  .  j a va2 s . c om*/
 * A file in the virtual file system is committed with the algorithms:
 * <ol>
 * <li>any existing backup fill will be moved to an older backup file. The
 *     maximum number of backups can be defined by setting the property
 *     {@link #PROPERTY_NUMBER_BACKUP}. Default is one. To disable the
 *     property must be set to 0.</li>
 * <li>the current file is moved to the backup file (or deleted if property
 *     {@link #PROPERTY_NUMBER_BACKUP} is 0)</li>
 * <li>the new file is moved to the original name</li>
 * </ol>
 *
 * @param _xid      global transaction identifier (not used, because each
 *                  file with the file id gets a new VFS store resource
 *                  instance)
 * @param _onePhase <i>true</i> if it is a one phase commitment transaction
 *                  (not used)
 * @throws XAException if any exception occurs (catch on
 *         {@link java.lang.Throwable})
 */
@Override
public void commit(final Xid _xid, final boolean _onePhase) throws XAException {
    if (VFSStoreResource.LOG.isDebugEnabled()) {
        VFSStoreResource.LOG.debug("transaction commit");
    }
    if (getStoreEvent() == VFSStoreResource.StoreEvent.WRITE) {
        try {
            final FileObject tmpFile = this.manager.resolveFile(this.manager.getBaseFile(),
                    this.storeFileName + VFSStoreResource.EXTENSION_TEMP);
            final FileObject currentFile = this.manager.resolveFile(this.manager.getBaseFile(),
                    this.storeFileName + VFSStoreResource.EXTENSION_NORMAL);
            final FileObject bakFile = this.manager.resolveFile(this.manager.getBaseFile(),
                    this.storeFileName + VFSStoreResource.EXTENSION_BACKUP);
            if (bakFile.exists() && (this.numberBackup > 0)) {
                backup(bakFile, 0);
            }
            if (currentFile.exists()) {
                if (this.numberBackup > 0) {
                    currentFile.moveTo(bakFile);
                } else {
                    currentFile.delete();
                }
            }
            tmpFile.moveTo(currentFile);
            tmpFile.close();
            currentFile.close();
            bakFile.close();
        } catch (final FileSystemException e) {
            VFSStoreResource.LOG
                    .error("transaction commit fails for " + _xid + " (one phase = " + _onePhase + ")", e);
            final XAException xa = new XAException(XAException.XA_RBCOMMFAIL);
            xa.initCause(e);
            throw xa;
        }
    } else if (getStoreEvent() == VFSStoreResource.StoreEvent.DELETE) {
        try {
            final FileObject curFile = this.manager.resolveFile(this.manager.getBaseFile(),
                    this.storeFileName + VFSStoreResource.EXTENSION_NORMAL);
            final FileObject bakFile = this.manager.resolveFile(this.manager.getBaseFile(),
                    this.storeFileName + VFSStoreResource.EXTENSION_BACKUP);
            if (bakFile.exists()) {
                bakFile.delete();
            }
            if (curFile.exists()) {
                curFile.moveTo(bakFile);
            }
            bakFile.close();
            curFile.close();
        } catch (final FileSystemException e) {
            VFSStoreResource.LOG
                    .error("transaction commit fails for " + _xid + " (one phase = " + _onePhase + ")", e);
            final XAException xa = new XAException(XAException.XA_RBCOMMFAIL);
            xa.initCause(e);
            throw xa;
        }
    }
}

From source file:org.esupportail.portlet.filemanager.services.vfs.VfsAccessImpl.java

@Override
public boolean renameFile(String path, String title, SharedUserPortletParameters userParameters) {
    try {//from  w w  w  . j a v a  2 s. c  om
        FileObject file = cd(path, userParameters);
        FileObject newFile = file.getParent().resolveFile(title);
        if (!newFile.exists()) {
            file.moveTo(newFile);
            return true;
        } else {
            log.info("file " + title + " already exists !");
        }
    } catch (FileSystemException e) {
        log.info("can't rename file because of FileSystemException : " + e.getMessage(), e);
    }
    return false;
}

From source file:org.esupportail.portlet.filemanager.services.vfs.VfsAccessImpl.java

@Override
public boolean moveCopyFilesIntoDirectory(String dir, List<String> filesToCopy, boolean copy,
        SharedUserPortletParameters userParameters) {
    try {//from  ww  w .j  ava  2s .  co m
        FileObject folder = cd(dir, userParameters);
        for (String fileToCopyPath : filesToCopy) {
            FileObject fileToCopy = cd(fileToCopyPath, userParameters);
            FileObject newFile = folder.resolveFile(fileToCopy.getName().getBaseName());
            if (copy) {
                newFile.copyFrom(fileToCopy, Selectors.SELECT_ALL);
            } else {
                fileToCopy.moveTo(newFile);
            }

        }
        return true;
    } catch (FileSystemException e) {
        log.warn("can't move/copy file because of FileSystemException : " + e.getMessage(), e);
    }
    return false;
}