Example usage for org.apache.commons.vfs2 FileType FOLDER

List of usage examples for org.apache.commons.vfs2 FileType FOLDER

Introduction

In this page you can find the example usage for org.apache.commons.vfs2 FileType FOLDER.

Prototype

FileType FOLDER

To view the source code for org.apache.commons.vfs2 FileType FOLDER.

Click Source Link

Document

A folder.

Usage

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

/**
 * List the all files of given pattern./* w w w.  j  a v a2 s .c  om*/
 *
 * @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./* www  . j ava2s  .c o m*/
 * @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.FileSend.java

/**
 * Send the file to the target directory.
 *
 * @param address Location for send the file.
 * @param append  If the response should be appended to the response file or not.
 * @return return true, if file is sent successfully.
 *///  ww w  .jav a 2  s.co  m
private boolean sendResponseFile(String address, MessageContext messageContext, boolean append) {
    boolean resultStatus = false;
    FileObject fileObj;
    StandardFileSystemManager manager = null;
    CountingOutputStream os = null;
    if (log.isDebugEnabled()) {
        log.debug("File sending started to" + address);
    }
    try {
        manager = FileConnectorUtils.getManager();
        org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext)
                .getAxis2MessageContext();
        fileObj = manager.resolveFile(address, FileConnectorUtils.init(messageContext));
        if (fileObj.getType() == FileType.FOLDER) {
            address = address.concat(FileConstants.DEFAULT_RESPONSE_FILE);
            fileObj = manager.resolveFile(address, FileConnectorUtils.init(messageContext));
        }
        // Get the message formatter.
        MessageFormatter messageFormatter = getMessageFormatter(axis2MessageContext);
        OMOutputFormat format = BaseUtils.getOMOutputFormat(axis2MessageContext);
        // Creating output stream and give the content to that.
        os = new CountingOutputStream(fileObj.getContent().getOutputStream(append));
        if (format != null && os != null && messageContext != null) {
            messageFormatter.writeTo(axis2MessageContext, format, os, true);
            resultStatus = true;
            if (log.isDebugEnabled()) {
                log.debug("File send completed to " + address);
            }
        } else {
            log.error("Can not send the file to specific address");
        }
    } catch (IOException e) {
        handleException("Unable to send a file/folder.", e, messageContext);
    } finally {
        try {
            os.close();
        } catch (IOException e) {
            log.warn("Can not close the output stream");
        }
        if (manager != null) {
            manager.close();
        }
    }
    return resultStatus;
}

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.
 *//*  ww w.j  a va2  s  .c  om*/

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.inbound.endpoint.protocol.file.MockFile.java

protected FileType doGetType() throws Exception {
    if (getName().getPath().endsWith(".fail")) {
        return FileType.IMAGINARY;
    }//from  w ww . jav  a 2s .co m

    if (getName().getPath().endsWith(".lock") && !lockFileCreated) {
        return FileType.IMAGINARY;
    }

    //If file name ends with file separator, it is mocked as folder
    if (getName().getPath().endsWith(File.separator)) {
        return FileType.FOLDER;
    }

    return getName().getType();
}

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

protected String[] doListChildren() throws Exception {
    if (getType() == FileType.FOLDER) {
        String[] children = new String[1];
        for (int i = 0; i < children.length; i++) {
            children[i] = "t-" + i + "-" + System.currentTimeMillis() + ".txt";
        }//w ww.j a v a  2 s. c o m

        return children;
    }
    return new String[0];
}

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

/**
 * Add a mock file//www.  j  a v  a  2  s  .com
 * @param uri file usri
 * @param mockFile mock file object
 */
public void addFile(String uri, MockFile mockFile) {
    if (mockFile.getName().getType() == FileType.FOLDER && !uri.endsWith(File.separator)) {
        uri += File.separator;
    }
    mockFileMap.put(uri, mockFile);
}

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

/**
 * Do the file processing operation for the given set of properties. Do the
 * checks and pass the control to processFile method
 *//* ww  w  .  ja  va2 s. c  om*/
public void consume() throws FileServerConnectorException {
    if (log.isDebugEnabled()) {
        log.debug("Polling for directory or file : " + FileTransportUtils.maskURLPassword(fileURI));
    }

    // If file/folder found proceed to the processing stage
    try {
        boolean isFileExists;
        try {
            isFileExists = fileObject.exists();
        } catch (FileSystemException e) {
            throw new FileServerConnectorException("Error occurred when determining whether the file at URI : "
                    + FileTransportUtils.maskURLPassword(fileURI) + " exists. " + e);
        }

        boolean isFileReadable;
        try {
            isFileReadable = fileObject.isReadable();
        } catch (FileSystemException e) {
            throw new FileServerConnectorException("Error occurred when determining whether the file at URI : "
                    + FileTransportUtils.maskURLPassword(fileURI) + " is readable. " + e);
        }

        if (isFileExists && isFileReadable) {
            FileType fileType;
            try {
                fileType = fileObject.getType();
            } catch (FileSystemException e) {
                throw new FileServerConnectorException("Error occurred when determining whether file: "
                        + FileTransportUtils.maskURLPassword(fileURI) + " is a file or a folder", e);
            }

            if (fileType == FileType.FILE) {
                processFile(fileObject);
                deleteFile(fileObject);
            } else if (fileType == FileType.FOLDER) {
                FileObject[] children = null;
                try {
                    children = fileObject.getChildren();
                } catch (FileSystemException ignored) {
                    if (log.isDebugEnabled()) {
                        log.debug("The file does not exist, or is not a folder, or an error "
                                + "has occurred when trying to list the children. File URI : "
                                + FileTransportUtils.maskURLPassword(fileURI), ignored);
                    }
                }

                // if this is a file that would translate to a single message
                if (children == null || children.length == 0) {
                    if (log.isDebugEnabled()) {
                        log.debug("Folder at " + FileTransportUtils.maskURLPassword(fileURI) + " is empty.");
                    }
                } else {
                    directoryHandler(children);
                }
            } else {
                throw new FileServerConnectorException("File: " + FileTransportUtils.maskURLPassword(fileURI)
                        + " is neither a file or " + "a folder"
                        + (fileType == null ? "" : ". Found file type: " + fileType.toString()));
            }
        } else {
            throw new FileServerConnectorException("Unable to access or read file or directory : "
                    + FileTransportUtils.maskURLPassword(fileURI) + ". Reason: "
                    + (isFileExists ? (isFileReadable ? "Unknown reason" : "The file can not be read!")
                            : "The file does not exist!"));
        }
    } finally {
        try {
            fileObject.close();
        } catch (FileSystemException e) {
            log.warn("Could not close file at URI: " + FileTransportUtils.maskURLPassword(fileURI), e);
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("End : Scanning directory or file : " + FileTransportUtils.maskURLPassword(fileURI));
    }
}

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

/**
 * Constructor for the FileSystemConsumer.
 *
 * @param id                Name of the service that creates the consumer
 * @param fileProperties    Map of property values
 * @param messageProcessor  Message processor instance
 *///w w w.  j  a v a  2 s .c o m
FileSystemConsumer(String id, Map<String, String> fileProperties, CarbonMessageProcessor messageProcessor,
        ServerConnectorErrorHandler errorHandler) throws ServerConnectorException {
    this.serviceName = id;
    this.fileProperties = fileProperties;
    this.messageProcessor = messageProcessor;
    this.errorHandler = errorHandler;

    setupParams();
    try {
        fsManager = VFS.getManager();

        Map<String, String> options = parseSchemeFileOptions(listeningDirURI);
        fso = FileTransportUtils.attachFileSystemOptions(options, fsManager);

        // TODO: Make this and other file related configurations configurable
        if (options != null && Constants.SCHEME_FTP.equals(options.get(Constants.SCHEME))) {
            FtpFileSystemConfigBuilder.getInstance().setPassiveMode(fso, true);
        }

        try {
            listeningDir = fsManager.resolveFile(listeningDirURI, fso);
        } catch (FileSystemException e) {
            this.errorHandler.handleError(new FileSystemServerConnectorException(
                    "Failed to resolve listeningDirURI: " + FileTransportUtils.maskURLPassword(listeningDirURI),
                    e), null, null);
        }
    } catch (FileSystemException e) {
        this.errorHandler.handleError(new ServerConnectorException(
                "Could not initialize File System Manager from " + "the configuration: providers.xml", e), null,
                null);
    }

    try {
        if (!listeningDir.isWriteable()) {
            postProcessAction = Constants.ACTION_NONE;
        }
    } catch (FileSystemException e) {
        this.errorHandler
                .handleError(new FileSystemServerConnectorException("Exception while determining file: "
                        + FileTransportUtils.maskURLPassword(listeningDirURI) + " is writable", e), null, null);
    }

    FileType fileType = getFileType(listeningDir);
    if (fileType != FileType.FOLDER) {
        this.errorHandler
                .handleError(
                        new FileSystemServerConnectorException("File system server connector is used to "
                                + "listen to a folder. But the given path does not refer to a folder."),
                        null, null);
    }
    //Initialize the thread executor based on properties
    ThreadPoolFactory.createInstance(threadPoolSize, parallelProcess);
}

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

/**
 * Handle directory with child elements.
 *
 * @param children The array containing child elements of a folder
 *///from  w w w .jav  a 2 s. c o m
private void directoryHandler(FileObject[] children) throws FileSystemServerConnectorException {
    // Sort the files according to given properties
    String strSortParam = fileProperties.get(Constants.FILE_SORT_PARAM);

    // TODO: rethink the way the string constants are handled
    if (strSortParam != null && !"NONE".equals(strSortParam)) {
        if (log.isDebugEnabled()) {
            log.debug("Starting to sort the files in folder: "
                    + FileTransportUtils.maskURLPassword(listeningDirURI));
        }

        String strSortOrder = fileProperties.get(Constants.FILE_SORT_ORDER);
        boolean bSortOrderAscending = true;

        if (strSortOrder != null) {
            bSortOrderAscending = Boolean.parseBoolean(strSortOrder);
        }
        if (log.isDebugEnabled()) {
            log.debug("Sorting the files by : " + strSortOrder + ". (" + bSortOrderAscending + ")");
        }
        switch (strSortParam) {
        case Constants.FILE_SORT_VALUE_NAME:
            if (bSortOrderAscending) {
                Arrays.sort(children, new FileNameAscComparator());
            } else {
                Arrays.sort(children, new FileNameDesComparator());
            }
            break;
        case Constants.FILE_SORT_VALUE_SIZE:
            if (bSortOrderAscending) {
                Arrays.sort(children, new FileSizeAscComparator());
            } else {
                Arrays.sort(children, new FileSizeDesComparator());
            }
            break;
        case Constants.FILE_SORT_VALUE_LASTMODIFIEDTIMESTAMP:
            if (bSortOrderAscending) {
                Arrays.sort(children, new FileLastmodifiedtimestampAscComparator());
            } else {
                Arrays.sort(children, new FileLastmodifiedtimestampDesComparator());
            }
            break;
        default:
            log.warn("Invalid value given for " + Constants.FILE_SORT_PARAM + " parameter. "
                    + " Expected one of the values: " + Constants.FILE_SORT_VALUE_NAME + ", "
                    + Constants.FILE_SORT_VALUE_SIZE + " or " + Constants.FILE_SORT_VALUE_LASTMODIFIEDTIMESTAMP
                    + ". Found: " + strSortParam);
            break;
        }
        if (log.isDebugEnabled()) {
            log.debug("End sorting the files.");
        }
    }
    for (FileObject child : children) {
        if (fileProcessCount != 0 && processCount > fileProcessCount) {
            return;
        }
        if (child.getName().getBaseName().endsWith(".lock")
                || child.getName().getBaseName().endsWith(".fail")) {
            continue;
        }
        if (!(fileNamePattern == null || child.getName().getBaseName().matches(fileNamePattern))) {
            if (log.isDebugEnabled()) {
                log.debug("File " + FileTransportUtils.maskURLPassword(listeningDir.getName().getBaseName())
                        + " is not processed because it did not match the specified pattern.");
            }
        } else {
            FileType childType = getFileType(child);
            if (childType == FileType.FOLDER) {
                FileObject[] c = null;
                try {
                    c = child.getChildren();
                } catch (FileSystemException ignored) {
                    if (log.isDebugEnabled()) {
                        log.debug("The file does not exist, or is not a folder, or an error "
                                + "has occurred when trying to list the children. File URI : "
                                + FileTransportUtils.maskURLPassword(listeningDirURI), ignored);
                    }
                }

                // if this is a file that would translate to a single message
                if (c == null || c.length == 0) {
                    if (log.isDebugEnabled()) {
                        log.debug("Folder at " + FileTransportUtils.maskURLPassword(child.getName().getURI())
                                + " is empty.");
                    }
                } else {
                    directoryHandler(c);
                }
                postProcess(child, false);
            } else {
                fileHandler(child);
            }
        }
    }
}