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

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

Introduction

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

Prototype

boolean exists() throws FileSystemException;

Source Link

Document

Determines if this file exists.

Usage

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

/**
 * Move the file/folder from source to destination directory.
 *
 * @param messageContext The message context that is generated for processing the move operation.
 * @return true, if the file/folder is successfully moved.
 *//* www .j a va2s .  c  om*/
private boolean move(MessageContext messageContext) throws FileSystemException {
    String source = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.FILE_LOCATION);
    String destination = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.NEW_FILE_LOCATION);
    String filePattern = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.FILE_PATTERN);
    String includeParentDirectory = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.INCLUDE_PARENT_DIRECTORY);
    boolean includeParentDirectoryParameter = FileConstants.DEFAULT_INCLUDE_PARENT_DIRECTORY;

    if (StringUtils.isNotEmpty(includeParentDirectory)) {
        includeParentDirectoryParameter = Boolean.parseBoolean(includeParentDirectory);
    }

    StandardFileSystemManager manager = FileConnectorUtils.getManager();
    FileSystemOptions opts = FileConnectorUtils.init(messageContext);
    // Create remote object
    FileObject remoteFile = manager.resolveFile(source, opts);
    try {
        if (!remoteFile.exists()) {
            log.error("The file/folder location does not exist.");
            return false;
        }
        if (FileType.FILE.equals(remoteFile.getType())) {
            moveFile(destination, remoteFile, manager, opts);
        } else {
            moveFolder(source, destination, filePattern, includeParentDirectoryParameter, manager, opts);
        }
        if (log.isDebugEnabled()) {
            log.debug("File move completed from " + source + " to " + destination);
        }
    } catch (FileSystemException e) {
        throw new SynapseException("Unable to move a file/folder.", e);
    } finally {
        // close the StandardFileSystemManager
        manager.close();
        try {
            remoteFile.close();
        } catch (FileSystemException e) {
            log.error("Error while closing the FileObject", e);
        }
    }
    return true;
}

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   ww w  .j a va  2s  .c o  m
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 va2  s  .co m*/
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./*from w  w  w. j  a v a 2s.  co  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.FileRead.java

public void connect(MessageContext messageContext) {
    String fileLocation = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.FILE_LOCATION);
    String contentType = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.CONTENT_TYPE);
    String filePattern = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.FILE_PATTERN);
    FileObject fileObj = null;
    StandardFileSystemManager manager = null;
    try {/*from  w  w w  .  ja v  a 2  s .  c  o  m*/
        manager = FileConnectorUtils.getManager();
        fileObj = manager.resolveFile(fileLocation, FileConnectorUtils.init(messageContext));
        if (fileObj.exists()) {
            if (fileObj.getType() == FileType.FOLDER) {
                FileObject[] children = fileObj.getChildren();
                if (children == null || children.length == 0) {
                    log.warn("Empty folder.");
                    handleException("Empty folder.", messageContext);
                } else if (filePattern != null && !filePattern.trim().equals("")) {
                    boolean bFound = false;
                    for (FileObject child : children) {
                        if (child.getName().getBaseName().matches(filePattern)) {
                            fileObj = child;
                            bFound = true;
                            break;
                        }
                    }
                    if (!bFound) {
                        log.warn("File does not exists for the mentioned pattern.");
                        handleException("File does not exists for the mentioned pattern.", messageContext);
                    }
                } else {
                    fileObj = children[0];
                }
            } else if (fileObj.getType() != FileType.FILE) {
                log.warn("File does not exists, or an empty folder.");
                handleException("File does not exists, or an empty folder.", messageContext);
            }
        } else {
            log.warn("File/Folder does not exists");
            handleException("File/Folder does not exists", messageContext);
        }
        ResultPayloadCreate.buildFile(fileObj, messageContext, contentType);
        if (log.isDebugEnabled()) {
            log.debug("File read completed." + fileLocation);
        }
    } catch (Exception e) {
        handleException(e.getMessage(), messageContext);
    } finally {
        try {
            // Close the File system if it is not already closed by the finally block of
            // processFile method
            if (fileObj != null && fileObj.getParent() != null && fileObj.getParent().getFileSystem() != null) {
                manager.closeFileSystem(fileObj.getParent().getFileSystem());
            }
        } catch (FileSystemException warn) {
            // ignore the warning, since we handed over the stream close job to
            // AutoCloseInputStream..
        }
        try {
            if (fileObj != null) {
                fileObj.close();
            }
        } catch (Exception e) {
            // ignore the warning, since we handed over the stream close job to
            // AutoCloseInputStream..
        }
    }
}

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

/**
 * Read the file content./*  www.j  a v  a  2s .c  o  m*/
 *
 * @param messageContext The message context that is generated for processing the read operation.
 */
private void readFile(MessageContext messageContext) {
    String source = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.FILE_LOCATION);
    String contentType = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.CONTENT_TYPE);
    String filePattern = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.FILE_PATTERN);
    boolean streaming = false;
    String enableStreamingParameter = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.ENABLE_STREAMING);
    if (StringUtils.isNotEmpty(enableStreamingParameter)) {
        streaming = Boolean.parseBoolean(enableStreamingParameter);
    }

    FileObject fileObjectToRead = null;
    StandardFileSystemManager manager = FileConnectorUtils.getManager();
    try {
        FileObject rootFileObject = manager.resolveFile(source, FileConnectorUtils.init(messageContext));
        if (!rootFileObject.exists()) {
            log.error("File/Folder does not exists.");
        }
        if (FileType.FOLDER.equals(rootFileObject.getType())) {
            FileObject[] children = rootFileObject.getChildren();
            if (children == null || children.length == 0) {
                log.error("Empty folder.");
            } else if (StringUtils.isNotEmpty(filePattern)) {
                for (FileObject child : children) {
                    if (child.getName().getBaseName().matches(filePattern)) {
                        fileObjectToRead = child;
                        break;
                    }
                }
                if (fileObjectToRead == null) {
                    log.error("File does not exists for the mentioned pattern.");
                }
            } else {
                fileObjectToRead = children[0];
            }
        } else if (FileType.FILE.equals(rootFileObject.getType())) {
            fileObjectToRead = rootFileObject;
        } else {
            log.error("File does not exists, or an empty folder");
        }
        ResultPayloadCreator.buildFile(fileObjectToRead, messageContext, contentType, streaming);
        if (log.isDebugEnabled()) {
            log.debug("File read completed." + source);
        }
    } catch (FileSystemException e) {
        throw new SynapseException("Error while reading a file", e);
    } finally {
        try {
            // Close the File system if it is not already closed by the finally block of processFile method
            if (fileObjectToRead != null && fileObjectToRead.getParent() != null
                    && fileObjectToRead.getParent().getFileSystem() != null) {
                manager.closeFileSystem(fileObjectToRead.getParent().getFileSystem());
            }
            if (fileObjectToRead != null) {
                fileObjectToRead.close();
            }
        } catch (FileSystemException e) {
            log.error("Error while closing the FileObject", e);
        }
    }
}

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

/**
 * Rename the files//from   w w  w . j ava  2  s .  c om
 * 
 * @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.connector.FileSearch.java

/**
 * Generate the file search/*from w  w  w .  j av  a 2s.c om*/
 *
 * @param source         Location fo the file
 * @param filePattern    Pattern of the file
 * @param recursiveSearch check whether recursively search or not
 * @param messageContext The message context that is processed by a handler in the handle method
 */
private void search(String source, String filePattern, String recursiveSearch, MessageContext messageContext) {
    ResultPayloadCreate resultPayload = new ResultPayloadCreate();
    StandardFileSystemManager manager = null;
    if (StringUtils.isEmpty(filePattern)) {
        log.error("FilePattern should not be null");
    } else {
        try {
            manager = FileConnectorUtils.getManager();
            FileSystemOptions opt = FileConnectorUtils.init(messageContext);
            FileObject remoteFile = manager.resolveFile(source, opt);
            if (remoteFile.exists()) {
                FileObject[] children = remoteFile.getChildren();
                OMFactory factory = OMAbstractFactory.getOMFactory();
                String outputResult;
                OMNamespace ns = factory.createOMNamespace(FileConstants.FILECON, FileConstants.NAMESPACE);
                OMElement result = factory.createOMElement(FileConstants.RESULT, ns);
                resultPayload.preparePayload(messageContext, result);
                FilePattenMatcher fpm = new FilePattenMatcher(filePattern);
                recursiveSearch = recursiveSearch.trim();

                for (FileObject child : children) {
                    try {
                        if (child.getType() == FileType.FILE
                                && fpm.validate(child.getName().getBaseName().toLowerCase())) {
                            outputResult = child.getName().getPath();
                            OMElement messageElement = factory.createOMElement(FileConstants.FILE, ns);
                            messageElement.setText(outputResult);
                            result.addChild(messageElement);
                        } else if (child.getType() == FileType.FOLDER && "true".equals(recursiveSearch)) {
                            searchSubFolders(child, filePattern, messageContext, factory, result, ns);
                        }
                    } catch (IOException e) {
                        handleException("Unable to search a file.", e, messageContext);
                    } finally {
                        try {
                            if (child != null) {
                                child.close();
                            }
                        } catch (IOException e) {
                            log.error("Error while closing Directory: " + e.getMessage(), e);
                        }
                    }
                }
                messageContext.getEnvelope().getBody().addChild(result);
            } else {
                log.error("File location does not exist.");
            }
        } catch (IOException e) {
            handleException("Unable to search a file.", e, messageContext);
        } finally {
            if (manager != null) {
                manager.close();
            }
        }
    }
}

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

/**
 * List the all files of given pattern.//w ww. jav  a2  s.c o m
 *
 * @param messageContext The message context that is generated for processing the file.
 */
private void searchFile(MessageContext messageContext) {
    String source = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.FILE_LOCATION);
    String filePattern = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.FILE_PATTERN);
    boolean enableRecursiveSearch = false;

    String recursiveSearchParameter = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.RECURSIVE_SEARCH);

    if (StringUtils.isNotEmpty(recursiveSearchParameter)) {
        enableRecursiveSearch = Boolean.parseBoolean(recursiveSearchParameter);
    }
    StandardFileSystemManager manager = FileConnectorUtils.getManager();
    if (StringUtils.isEmpty(filePattern)) {
        throw new SynapseException("FilePattern should not be null");
    }
    try {
        FileSystemOptions opt = FileConnectorUtils.init(messageContext);
        FileObject remoteFile = manager.resolveFile(source, opt);
        if (!remoteFile.exists()) {
            throw new SynapseException("File location does not exist");
        }
        FileObject[] children = remoteFile.getChildren();
        OMFactory factory = OMAbstractFactory.getOMFactory();
        OMNamespace ns = factory.createOMNamespace(FileConstants.FILECON, FileConstants.NAMESPACE);
        OMElement result = factory.createOMElement(FileConstants.RESULT, ns);
        ResultPayloadCreator.preparePayload(messageContext, result);
        FilePattenMatcher fpm = new FilePattenMatcher(filePattern);

        for (FileObject child : children) {
            try {
                if (FileType.FILE.equals(child.getType()) && fpm.validate(child.getName().getBaseName())) {
                    String outputResult = child.getName().getPath();
                    OMElement messageElement = factory.createOMElement(FileConstants.FILE, ns);
                    messageElement.setText(outputResult);
                    result.addChild(messageElement);
                } else if (FileType.FOLDER.equals(child.getType()) && enableRecursiveSearch) {
                    searchSubFolders(child, filePattern, factory, result, ns);
                }
            } catch (FileSystemException e) {
                throw new SynapseException("Unable to search a file.", e);
            } finally {
                try {
                    if (child != null) {
                        child.close();
                    }
                } catch (IOException e) {
                    log.error("Error while closing Directory: " + e.getMessage(), e);
                }
            }
        }
        messageContext.getEnvelope().getBody().addChild(result);
    } catch (FileSystemException e) {
        throw new SynapseException("Unable to search a file for a given pattern.", e);
    } finally {
        manager.close();
    }
}

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

/**
 * Decompress the compressed file into the given directory.
 *
 * @param messageContext The message context that is generated for processing unzip operation.
 * @return true, if zip file successfully extracts and false, if not.
 * @throws FileSystemException On error parsing the file name, determining if the file exists and creating the
 * folder./*  w  w  w  . ja  v  a2 s  . c om*/
 */
private boolean unzip(MessageContext messageContext) throws FileSystemException {
    String source = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.FILE_LOCATION);
    String destination = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.NEW_FILE_LOCATION);
    StandardFileSystemManager manager = FileConnectorUtils.getManager();
    FileSystemOptions opts = FileConnectorUtils.init(messageContext);
    FileObject remoteFile = manager.resolveFile(source, opts);
    FileObject remoteDesFile = manager.resolveFile(destination, opts);

    if (!remoteFile.exists()) {
        log.error("File does not exist.");
        return false;
    }
    if (!remoteDesFile.exists()) {
        //create a folder
        remoteDesFile.createFolder();
    }
    //open the zip file
    ZipInputStream zipIn = new ZipInputStream(remoteFile.getContent().getInputStream());
    try {
        ZipEntry entry = zipIn.getNextEntry();

        // iterates over entries in the zip file
        while (entry != null) {
            String filePath = destination + File.separator + entry.getName();
            // create remote object
            FileObject remoteFilePath = manager.resolveFile(filePath, opts);
            if (log.isDebugEnabled()) {
                log.debug("The created path is " + remoteFilePath.toString());
            }
            try {
                if (!entry.isDirectory()) {
                    // if the entry is a file, extracts it
                    extractFile(zipIn, remoteFilePath);
                } else {
                    // if the entry is a directory, make the directory
                    remoteFilePath.createFolder();
                }
            } finally {
                try {
                    zipIn.closeEntry();
                    entry = zipIn.getNextEntry();
                } catch (IOException e) {
                    log.error("Error while closing the ZipInputStream", e);
                }
            }
        }
    } catch (IOException e) {
        throw new SynapseException("Error while reading the next ZIP file entry", e);
    } finally {
        // close the zip file
        try {
            zipIn.close();
        } catch (IOException e) {
            log.error("Error while closing the ZipInputStream", e);
        }
        // close the StandardFileSystemManager
        manager.close();
        try {
            remoteFile.close();
            remoteDesFile.close();
        } catch (FileSystemException e) {
            log.error("Error while closing the FileObject", e);
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("File extracted to" + destination);
    }
    return true;
}