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

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

Introduction

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

Prototype

@Override
void close() throws FileSystemException;

Source Link

Document

Closes this file, and its content.

Usage

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 {/*  ww  w  . ja  va2s.  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./*from   w  ww.ja  va  2  s  .  c  om*/
 *
 * @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.FileSearch.java

/**
 * Generate the file search// w w w  . ja v  a 2s . com
 *
 * @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.FileSearch.java

/**
 *
 * @param dir sub directory/*from  ww w .  ja  v  a  2s.c o  m*/
 * @param fileList list of file inside directory
 * @param messageContext the message context that is generated for processing the file
 */
private void getAllFiles(FileObject dir, List<FileObject> fileList, MessageContext messageContext) {
    try {
        FileObject[] children = dir.getChildren();
        for (FileObject child : children) {
            fileList.add(child);
        }
    } catch (IOException e) {
        handleException("Unable to list all folders", e, messageContext);
    } finally {
        try {
            if (dir != null) {
                dir.close();
            }
        } catch (IOException e) {
            log.error("Error while closing Directory: " + e.getMessage(), e);
        }
    }
}

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

/**
 *
 * @param child sub folder/*from   w  w  w.  jav  a  2s.c  o m*/
 * @param filePattern pattern of the file to be searched
 * @param messageContext the message context that is generated for processing the file
 * @param factory OMFactory
 * @param result OMElement
 * @param ns OMNamespace
 * @throws IOException
 */
private void searchSubFolders(FileObject child, String filePattern, MessageContext messageContext,
        OMFactory factory, OMElement result, OMNamespace ns) throws IOException {
    List<FileObject> fileList = new ArrayList<FileObject>();
    getAllFiles(child, fileList, messageContext);
    FilePattenMatcher fpm = new FilePattenMatcher(filePattern);
    String outputResult;
    try {
        for (FileObject file : fileList) {
            if (file.getType() == FileType.FILE) {
                if (fpm.validate(file.getName().getBaseName().toLowerCase())) {
                    outputResult = file.getName().getPath();
                    OMElement messageElement = factory.createOMElement(FileConstants.FILE, ns);
                    messageElement.setText(outputResult);
                    result.addChild(messageElement);
                }
            } else if (file.getType() == FileType.FOLDER) {
                searchSubFolders(file, filePattern, messageContext, factory, result, ns);
            }
        }
    } catch (IOException e) {
        handleException("Unable to search a file in sub folder.", e, messageContext);
    } finally {
        try {
            if (child != null) {
                child.close();
            }
        } catch (IOException e) {
            log.error("Error while closing Directory: " + e.getMessage(), e);
        }
    }
}

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

/**
 * List the all files of given pattern./*  w  ww.j  ava 2  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.FileSearchConnector.java

/**
 * Search the files of given pattern inside the sub directory.
 *
 * @param child          Child folder.//  w w w  .  j a  va2s  . c  om
 * @param filePattern    Pattern of the file to be searched.
 * @param factory        OMFactory.
 * @param result         OMElement.
 * @param ns             OMNamespace.
 * @throws FileSystemException On error getting file type.
 */
private void searchSubFolders(FileObject child, String filePattern, OMFactory factory, OMElement result,
        OMNamespace ns) throws FileSystemException {
    List<FileObject> fileList = new ArrayList<>();
    Collections.addAll(fileList, child.getChildren());
    FilePattenMatcher fpm = new FilePattenMatcher(filePattern);
    String outputResult;
    try {
        for (FileObject file : fileList) {
            if (FileType.FILE.equals(file.getType())) {
                if (fpm.validate(file.getName().getBaseName().toLowerCase())) {
                    outputResult = file.getName().getPath();
                    OMElement messageElement = factory.createOMElement(FileConstants.FILE, ns);
                    messageElement.setText(outputResult);
                    result.addChild(messageElement);
                }
            } else if (FileType.FOLDER.equals(file.getType())) {
                searchSubFolders(file, filePattern, factory, result, ns);
            }
        }
    } catch (FileSystemException e) {
        throw new SynapseException("Unable to search files in sub folder", e);
    } finally {
        try {
            child.close();
        } catch (IOException e) {
            log.error("Error while closing Directory: " + e.getMessage(), e);
        }
    }
}

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

/**
 * Send the file to the target directory.
 *
 * @param messageContext The message context that is used in file send mediation flow.
 * @return return true, if file is sent successfully.
 * @throws FileSystemException On error parsing the file name and getting file type.
 *///from w  w  w .  ja  v  a  2s .c  o  m

private boolean sendResponseFile(MessageContext messageContext) throws FileSystemException {
    boolean append = false;
    String destination = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.NEW_FILE_LOCATION);
    String strAppend = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.APPEND);
    if (StringUtils.isNotEmpty(strAppend)) {
        append = Boolean.parseBoolean(strAppend);
    }
    StandardFileSystemManager manager = FileConnectorUtils.getManager();
    FileObject fileObjectToSend = null;
    FileObject fileObj = manager.resolveFile(destination, FileConnectorUtils.init(messageContext));
    CountingOutputStream outputStream = null;
    if (log.isDebugEnabled()) {
        log.debug("File sending started to " + destination);
    }
    try {
        org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext)
                .getAxis2MessageContext();

        if (FileType.FOLDER.equals(fileObj.getType())) {
            String destDir = destination.concat(FileConstants.DEFAULT_RESPONSE_FILE);
            fileObjectToSend = manager.resolveFile(destDir, FileConnectorUtils.init(messageContext));
        } else if (FileType.FILE.equals(fileObj.getType())) {
            fileObjectToSend = fileObj;
        }
        // Get the message formatter.
        MessageFormatter messageFormatter = getMessageFormatter(axis2MessageContext);
        OMOutputFormat format = BaseUtils.getOMOutputFormat(axis2MessageContext);
        // Creating output stream and give the content to that.
        outputStream = new CountingOutputStream(fileObjectToSend.getContent().getOutputStream(append));
        messageFormatter.writeTo(axis2MessageContext, format, outputStream, true);
        if (log.isDebugEnabled()) {
            log.debug("File send completed to " + destination);
        }
    } catch (AxisFault e) {
        throw new SynapseException("Error while writing the message context", e);
    } finally {
        try {
            fileObjectToSend.close();
        } catch (FileSystemException e) {
            log.error("Error while closing FileObject", e);
        }
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException e) {
            log.warn("Can not close the output stream");
        }
        manager.close();
    }
    return true;
}

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  a  2  s  .co m*/
 */
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;
}

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

/**
 * Extract each zip entry and write it into file.
 *
 * @param zipIn          Zip input stream for reading file in the ZIP file format.
 * @param remoteFilePath Location of file where zip entry needs to be extracted.
 *//*from   w w w . ja  v  a2s  .  c  om*/
private void extractFile(ZipInputStream zipIn, FileObject remoteFilePath) {
    BufferedOutputStream bos = null;
    try {
        // open the zip file
        OutputStream fOut = remoteFilePath.getContent().getOutputStream();
        bos = new BufferedOutputStream(fOut);
        byte[] bytesIn = new byte[FileConstants.BUFFER_SIZE];
        int read;
        while ((read = zipIn.read(bytesIn)) != -1) {
            bos.write(bytesIn, 0, read);
        }
    } catch (IOException e) {
        throw new SynapseException("Unable to write zip entry", e);
    } finally {
        // close the zip file
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException e) {
                log.error("Error while closing the BufferedOutputStream", e);
            }
        }
        try {
            remoteFilePath.close();
        } catch (FileSystemException e) {
            log.error("Error while closing FileObject", e);
        }
    }
}