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

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

Introduction

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

Prototype

boolean delete() throws FileSystemException;

Source Link

Document

Deletes this file.

Usage

From source file:org.pentaho.di.ui.spoon.SharedObjectSyncUtilTest.java

@After
public void tearDown() throws Exception {
    FileObject sharedObjectsFile = KettleVFS.getFileObject(SHARED_OBJECTS_FILE);
    if (sharedObjectsFile.exists()) {
        sharedObjectsFile.delete();
    }//from  w  w  w.  ja  v a 2s.c o m
}

From source file:org.pentaho.googledrive.vfs.test.GoogleDriveFileObjectTest.java

@Test
public void testFileObject() throws Exception {
    FileSystemManager manager = mock(FileSystemManager.class);
    GoogleDriveFileObject fileObjectMock = mock(GoogleDriveFileObject.class);
    when(manager.resolveFile(FOLDER)).thenReturn(fileObjectMock);
    when(fileObjectMock.isFolder()).thenReturn(true);
    when(fileObjectMock.exists()).thenReturn(true);
    when(fileObjectMock.delete()).thenReturn(true);
    FileObject fileObject = manager.resolveFile(FOLDER);
    fileObject.createFolder();//from w  w  w.  j a  v  a2 s  .  c o  m
    assertTrue(fileObject.isFolder());
    assertTrue(fileObject.exists());
    assertTrue(fileObject.delete());
    assertNull(fileObject.getChildren());
}

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

public boolean deleteItem(TreeItem ti) throws FileSystemException {
    FileObject file = (FileObject) ti.getData();
    if (file.getName().getPath().equals("/"))
        return false; // If the root folder is attempted to delete, do nothing.
    if (file.delete()) {
        ti.dispose();/*  w  ww  .  ja  v a2s.  c om*/
        return true;
    }
    // If deleting a file object failed and no exception was kicked in, the selected object is a non-empty folder.
    // Show a second Confirm message, and perform a recursive delete if OK is pressed.
    MessageBox messageDialog = new MessageBox(fileSystemTree.getShell(), SWT.YES | SWT.NO);
    messageDialog.setText(Messages.getString("VfsFileChooserDialog.confirm")); //$NON-NLS-1$
    messageDialog.setMessage(Messages.getString("VfsFileChooserDialog.deleteFolderWithContents")); //$NON-NLS-1$
    int status = messageDialog.open();
    if (status == SWT.YES) {
        if (file.delete(new AllFileSelector()) != 0) {
            ti.dispose();
            return true;
        }
    }
    return false;
}

From source file:org.renjin.primitives.files.Files.java

private static void delete(FileObject file, boolean recursive) throws FileSystemException {
    if (file.exists()) {
        if (file.getType() == FileType.FILE) {
            file.delete();
        } else if (file.getType() == FileType.FOLDER) {
            if (file.getChildren().length == 0) {
                file.delete();/*from  w w  w . ja  v a  2 s. com*/
            } else if (recursive) {
                file.delete();
            }
        }
    }
}

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

/**
 * Delete the file//from  w  w  w .  j a v a 2  s.  com
 *
 * @param source         Location of the file
 * @param messageContext The message context that is generated for processing the file
 * @return Return the status
 */
private boolean deleteFile(String source, 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()) {
            if (remoteFile.getType() == FileType.FILE) {
                //delete a file
                remoteFile.delete();
            } else if (remoteFile.getType() == FileType.FOLDER) {
                //delete folder
                remoteFile.delete(Selectors.SELECT_ALL);
            }
            resultStatus = true;
        } else {
            log.error("The file does not exist.");
            resultStatus = false;
        }
        if (log.isDebugEnabled()) {
            log.debug("File delete completed with. " + source);
        }
    } catch (IOException e) {
        handleException("Error occurs while deleting a file.", e, messageContext);
    } finally {
        if (manager != null) {
            manager.close();
        }
    }
    return resultStatus;
}

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

/**
 * Delete an existing file/folder.//from   w  w w . j  a  v  a 2  s .  co  m
 *
 * @param messageContext The message context that is generated for processing the file.
 * @return true, if the file/folder is successfully deleted.
 */
private boolean deleteFile(MessageContext messageContext) {
    String source = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.FILE_LOCATION);
    StandardFileSystemManager manager = FileConnectorUtils.getManager();
    FileObject remoteFile = null;
    try {
        // create remote fileObject
        remoteFile = manager.resolveFile(source, FileConnectorUtils.init(messageContext));
        if (!remoteFile.exists()) {
            log.error("The file does not exist.");
            return false;
        }
        if (FileType.FILE.equals(remoteFile.getType())) {
            // delete a file
            remoteFile.delete();
        } else if (FileType.FOLDER.equals(remoteFile.getType())) {
            String filePattern = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
                    FileConstants.FILE_PATTERN);

            if (StringUtils.isNotEmpty(filePattern) && !"*".equals(filePattern)) {
                FileObject[] children = remoteFile.getChildren();
                for (FileObject child : children) {
                    if (child.getName().getBaseName().matches(filePattern)) {
                        child.delete();
                    }
                }
            } else {
                // delete folder
                remoteFile.delete(Selectors.SELECT_ALL);
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("File delete completed with " + source);
        }
    } catch (FileSystemException e) {
        throw new SynapseException("Error while deleting file/folder", e);
    } finally {
        // close the StandardFileSystemManager
        manager.close();
        try {
            if (remoteFile != null) {
                // close the file object
                remoteFile.close();
            }
        } catch (FileSystemException e) {
            log.error("Error while closing the FileObject", e);
        }
    }
    return true;
}

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

/**
 * Do the post processing actions/* w  ww. j  a  va  2 s . com*/
 * 
 * @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.server.FileConsumer.java

/**
 * Do the post processing actions//  w w  w  .j  a  va2 s.c o m
 *
 * @param fileObject
 */
private void deleteFile(FileObject fileObject) throws FileServerConnectorException {
    if (log.isDebugEnabled()) {
        log.debug("Deleting file :" + FileTransportUtils.maskURLPassword(fileObject.getName().getBaseName()));
    }
    try {
        if (!fileObject.delete()) {
            throw new FileServerConnectorException("Could not delete file : "
                    + FileTransportUtils.maskURLPassword(fileObject.getName().getBaseName()));
        }
    } catch (FileSystemException e) {
        throw new FileServerConnectorException("Could not delete file : "
                + FileTransportUtils.maskURLPassword(fileObject.getName().getBaseName()), e);
    }
}

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

/**
 * Do the post processing actions.//from  ww w .j av  a2s  . 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);
        }
    }
}

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

/**
 * Do the post processing actions.//from  w  ww .j a v  a 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));
        }
    }
}