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.util.ResultPayloadCreator.java

/**
 * Read the file content and set those content as the current SOAPEnvelope.
 *
 * @param file        File which needs to be read.
 * @param msgCtx      Message Context that is used in the file read mediation flow.
 * @param contentType content type.//w w w .ja v  a 2 s  .c om
 * @param streaming   streaming mode (true/false).
 * @return true, if file content is read successfully.
 */

public static boolean buildFile(FileObject file, MessageContext msgCtx, String contentType, boolean streaming) {
    ManagedDataSource dataSource = null;
    InputStream in = null;
    try {
        if (StringUtils.isEmpty(contentType)) {
            if (file.getName().getExtension().toLowerCase().endsWith("xml")) {
                contentType = "application/xml";
            } else if (file.getName().getExtension().toLowerCase().endsWith("txt")) {
                contentType = "text/plain";
            }
        } else {
            // Extract the charset encoding from the configured content type and
            // set the CHARACTER_SET_ENCODING property as e.g. SOAPBuilder relies on this.
            try {
                String charSetEnc = new ContentType(contentType).getParameter("charset");
                msgCtx.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc);
            } catch (ParseException ex) {
                throw new SynapseException("Invalid encoding type.", ex);
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Processed file : " + file + " of Content-type : " + contentType);
        }
        org.apache.axis2.context.MessageContext axis2MsgCtx = ((org.apache.synapse.core.axis2.Axis2MessageContext) msgCtx)
                .getAxis2MessageContext();
        // Determine the message builder to use
        Builder builder;
        if (StringUtils.isEmpty(contentType)) {
            log.debug("No content type specified. Using RELAY builder.");
            builder = new BinaryRelayBuilder();
        } else {
            int index = contentType.indexOf(';');
            String type = index > 0 ? contentType.substring(0, index) : contentType;
            builder = BuilderUtil.getBuilderFromSelector(type, axis2MsgCtx);
            if (builder == null) {
                if (log.isDebugEnabled()) {
                    log.debug(
                            "No message builder found for type '" + type + "'. Falling back to RELAY builder.");
                }
                builder = new BinaryRelayBuilder();
            }
        }
        // set the message payload to the message context
        OMElement documentElement;
        if (builder instanceof DataSourceMessageBuilder && streaming) {
            dataSource = ManagedDataSourceFactory.create(new FileObjectDataSource(file, contentType));
            documentElement = ((DataSourceMessageBuilder) builder).processDocument(dataSource, contentType,
                    axis2MsgCtx);
        } else {
            in = new AutoCloseInputStream(file.getContent().getInputStream());
            documentElement = builder.processDocument(in, contentType, axis2MsgCtx);
        }
        // We need this to build the complete message before closing the stream
        if (!streaming && documentElement != null) {
            //msgCtx.getEnvelope().build();
            documentElement.toString();
        }
        msgCtx.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement));
    } catch (Exception e) {
        throw new SynapseException("Error while processing the file/folder", e);
    } finally {
        if (dataSource != null) {
            dataSource.destroy();
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                log.error("Error while closing the InputStream");
            }
        }
        try {
            file.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

/**
 * //from w  w  w.  j  a v a 2 s.  co m
 * Do the file processing operation for the given set of properties. Do the
 * checks and pass the control to processFile method
 * 
 * */
public FileObject poll() {
    if (fileURI == null || fileURI.trim().equals("")) {
        log.error("Invalid file url. Check the inbound endpoint configuration. Endpoint Name : " + name
                + ", File URL : " + VFSUtils.maskURLPassword(fileURI));
        return null;
    }

    if (log.isDebugEnabled()) {
        log.debug("Start : Scanning directory or file : " + VFSUtils.maskURLPassword(fileURI));
    }

    if (!initFileCheck()) {
        // Unable to read from the source location provided.
        return null;
    }

    // If file/folder found proceed to the processing stage
    try {
        lastCycle = 0;
        if (fileObject.exists() && fileObject.isReadable()) {
            FileObject[] children = null;
            try {
                children = fileObject.getChildren();
            } catch (FileNotFolderException ignored) {
                if (log.isDebugEnabled()) {
                    log.debug("No Folder found. Only file found on : " + VFSUtils.maskURLPassword(fileURI));
                }
            } catch (FileSystemException ex) {
                log.error(ex.getMessage(), ex);
            }

            // if this is a file that would translate to a single message
            if (children == null || children.length == 0) {
                // Fail record is a one that is processed but was not moved
                // or deleted due to an error.
                boolean isFailedRecord = VFSUtils.isFailRecord(fsManager, fileObject);
                if (!isFailedRecord) {
                    fileHandler();
                    if (injectHandler == null) {
                        return fileObject;
                    }
                } else {
                    try {
                        lastCycle = 2;
                        moveOrDeleteAfterProcessing(fileObject);
                    } catch (SynapseException synapseException) {
                        log.error("File object '" + VFSUtils.maskURLPassword(fileObject.getURL().toString())
                                + "' " + "cloud not be moved after first attempt", synapseException);
                    }
                    if (fileLock) {
                        // TODO: passing null to avoid build break. Fix properly
                        VFSUtils.releaseLock(fsManager, fileObject, fso);
                    }
                    if (log.isDebugEnabled()) {
                        log.debug("File '" + VFSUtils.maskURLPassword(fileObject.getURL().toString())
                                + "' has been marked as a failed" + " record, it will not process");
                    }
                }
            } else {
                FileObject fileObject = directoryHandler(children);
                if (fileObject != null) {
                    return fileObject;
                }
            }
        } else {
            log.warn("Unable to access or read file or directory : " + VFSUtils.maskURLPassword(fileURI) + "."
                    + " Reason: "
                    + (fileObject.exists()
                            ? (fileObject.isReadable() ? "Unknown reason" : "The file can not be read!")
                            : "The file does not exists!"));
            return null;
        }
    } catch (FileSystemException e) {
        log.error("Error checking for existence and readability : " + VFSUtils.maskURLPassword(fileURI), e);
        return null;
    } catch (Exception e) {
        log.error("Error while processing the file/folder in URL : " + VFSUtils.maskURLPassword(fileURI), e);
        return null;
    } finally {
        try {
            if (fsManager != null) {
                fsManager.closeFileSystem(fileObject.getParent().getFileSystem());
            }
            fileObject.close();
        } catch (Exception e) {
            log.error("Unable to close the file system. " + e.getMessage());
            log.error(e);
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("End : Scanning directory or file : " + VFSUtils.maskURLPassword(fileURI));
    }
    return null;
}

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

/**
 * /*  w ww  .ja  v  a  2s  .com*/
 * Handle directory with chile elements
 * 
 * @param children
 * @return
 * @throws FileSystemException
 */
private FileObject directoryHandler(FileObject[] children) throws FileSystemException {
    // Process Directory
    lastCycle = 0;
    int failCount = 0;
    int successCount = 0;
    int processCount = 0;

    if (log.isDebugEnabled()) {
        log.debug("File name pattern : "
                + vfsProperties.getProperty(VFSConstants.TRANSPORT_FILE_FILE_NAME_PATTERN));
    }

    // Sort the files
    String strSortParam = vfsProperties.getProperty(VFSConstants.FILE_SORT_PARAM);
    if (strSortParam != null && !"NONE".equals(strSortParam)) {
        log.debug("Start Sorting the files.");
        String strSortOrder = vfsProperties.getProperty(VFSConstants.FILE_SORT_ORDER);
        boolean bSortOrderAsscending = true;
        if (strSortOrder != null && strSortOrder.toLowerCase().equals("false")) {
            bSortOrderAsscending = false;
        }
        if (log.isDebugEnabled()) {
            log.debug("Sorting the files by : " + strSortOrder + ". (" + bSortOrderAsscending + ")");
        }
        if (strSortParam.equals(VFSConstants.FILE_SORT_VALUE_NAME) && bSortOrderAsscending) {
            Arrays.sort(children, new FileNameAscComparator());
        } else if (strSortParam.equals(VFSConstants.FILE_SORT_VALUE_NAME) && !bSortOrderAsscending) {
            Arrays.sort(children, new FileNameDesComparator());
        } else if (strSortParam.equals(VFSConstants.FILE_SORT_VALUE_SIZE) && bSortOrderAsscending) {
            Arrays.sort(children, new FileSizeAscComparator());
        } else if (strSortParam.equals(VFSConstants.FILE_SORT_VALUE_SIZE) && !bSortOrderAsscending) {
            Arrays.sort(children, new FileSizeDesComparator());
        } else if (strSortParam.equals(VFSConstants.FILE_SORT_VALUE_LASTMODIFIEDTIMESTAMP)
                && bSortOrderAsscending) {
            Arrays.sort(children, new FileLastmodifiedtimestampAscComparator());
        } else if (strSortParam.equals(VFSConstants.FILE_SORT_VALUE_LASTMODIFIEDTIMESTAMP)
                && !bSortOrderAsscending) {
            Arrays.sort(children, new FileLastmodifiedtimestampDesComparator());
        }
        log.debug("End Sorting the files.");
    }

    for (FileObject child : children) {
        // skipping *.lock / *.fail file
        if (child.getName().getBaseName().endsWith(".lock")
                || child.getName().getBaseName().endsWith(".fail")) {
            continue;
        }
        boolean isFailedRecord = VFSUtils.isFailRecord(fsManager, child);

        // child's file name matches the file name pattern or process all
        // files now we try to get the lock and process
        if ((strFilePattern == null || child.getName().getBaseName().matches(strFilePattern))
                && !isFailedRecord) {

            if (log.isDebugEnabled()) {
                log.debug("Matching file : " + child.getName().getBaseName());
            }

            if ((!fileLock || (fileLock && acquireLock(fsManager, child)))) {
                // process the file
                boolean runPostProcess = true;
                try {
                    if (log.isDebugEnabled()) {
                        log.debug("Processing file :" + VFSUtils.maskURLPassword(child.toString()));
                    }
                    processCount++;
                    if (processFile(child) == null) {
                        runPostProcess = false;
                    } else {
                        successCount++;
                    }
                    // tell moveOrDeleteAfterProcessing() file was success
                    lastCycle = 1;
                } catch (Exception e) {
                    if (e.getCause() instanceof FileNotFoundException) {
                        log.warn("Error processing File URI : "
                                + VFSUtils.maskURLPassword(child.getName().toString())
                                + ". This can be due to file moved from another process.");
                        runPostProcess = false;
                    } else {
                        log.error("Error processing File URI : "
                                + VFSUtils.maskURLPassword(child.getName().toString()), e);
                        failCount++;
                        // tell moveOrDeleteAfterProcessing() file failed
                        lastCycle = 2;
                    }

                }
                // skipping un-locking file if failed to do delete/move
                // after process
                boolean skipUnlock = false;
                if (runPostProcess) {
                    try {
                        moveOrDeleteAfterProcessing(child);
                    } catch (SynapseException synapseException) {
                        log.error(
                                "File object '" + VFSUtils.maskURLPassword(child.getURL().toString())
                                        + "'cloud not be moved, will remain in \"locked\" state",
                                synapseException);
                        skipUnlock = true;
                        failCount++;
                        lastCycle = 3;
                        VFSUtils.markFailRecord(fsManager, child);
                    }
                }
                // if there is a failure or not we'll try to release the
                // lock
                if (fileLock && !skipUnlock) {
                    // TODO: passing null to avoid build break. Fix properly
                    VFSUtils.releaseLock(fsManager, child, fso);
                }
                if (injectHandler == null) {
                    return child;
                }
            }
        } else if (log.isDebugEnabled() && strFilePattern != null
                && !child.getName().getBaseName().matches(strFilePattern) && !isFailedRecord) {
            // child's file name does not match the file name pattern
            log.debug("Non-Matching file : " + child.getName().getBaseName());
        } else if (isFailedRecord) {
            // it is a failed record
            try {
                lastCycle = 1;
                moveOrDeleteAfterProcessing(child);
            } catch (SynapseException synapseException) {
                log.error("File object '" + VFSUtils.maskURLPassword(child.getURL().toString())
                        + "'cloud not be moved, will remain in \"fail\" state", synapseException);
            }
            if (fileLock) {
                // TODO: passing null to avoid build break. Fix properly
                VFSUtils.releaseLock(fsManager, child, fso);
                VFSUtils.releaseLock(fsManager, fileObject, fso);
            }
            if (log.isDebugEnabled()) {
                log.debug("File '" + VFSUtils.maskURLPassword(fileObject.getURL().toString())
                        + "' has been marked as a failed record, it will not " + "process");
            }
        }

        //close the file system after processing
        try {
            child.close();
        } catch (Exception e) {
        }

        // Manage throttling of file processing
        if (iFileProcessingInterval != null && iFileProcessingInterval > 0) {
            try {
                if (log.isDebugEnabled()) {
                    log.debug("Put the VFS processor to sleep for : " + iFileProcessingInterval);
                }
                Thread.sleep(iFileProcessingInterval);
            } catch (InterruptedException ie) {
                log.error("Unable to set the interval between file processors." + ie);
            }
        } else if (iFileProcessingCount != null && iFileProcessingCount <= processCount) {
            break;
        }
    }
    if (failCount == 0 && successCount > 0) {
        lastCycle = 1;
    } else if (successCount == 0 && failCount > 0) {
        lastCycle = 4;
    } else {
        lastCycle = 5;
    }
    return null;
}

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

/**
 * Do the post processing actions// www . java2  s  .co  m
 * 
 * @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

/**
 * Handle directory with chile elements/* ww  w  .j  a  va 2s .  c o m*/
 *
 * @param children
 * @return
 * @throws FileSystemException
 */
private void directoryHandler(FileObject[] children) throws FileServerConnectorException {
    // Sort the files
    String strSortParam = fileProperties.get(Constants.FILE_SORT_PARAM);

    if (strSortParam != null && !"NONE".equals(strSortParam)) {
        log.debug("Starting to sort the files in folder: " + FileTransportUtils.maskURLPassword(fileURI));

        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) {
        processFile(child);
        deleteFile(child);
        //close the file system after processing
        try {
            child.close();
        } catch (FileSystemException e) {
            log.warn("Could not close the file: " + child.getName().getPath(), e);
        }
    }
}

From source file:org.wso2.carbon.transport.remotefilesystem.client.connector.contractimpl.VFSClientConnectorImpl.java

@Override
public void send(RemoteFileSystemMessage message) {
    FtpFileSystemConfigBuilder.getInstance().setPassiveMode(opts, true);
    String fileURI = connectorConfig.get(Constants.URI);
    String action = connectorConfig.get(Constants.ACTION);
    FileType fileType;//from   www .  ja  va 2 s.  c  o  m
    ByteBuffer byteBuffer;
    InputStream inputStream = null;
    OutputStream outputStream = null;
    FileObject path = null;
    try {
        FileSystemManager fsManager = VFS.getManager();
        path = fsManager.resolveFile(fileURI, opts);
        fileType = path.getType();
        switch (action) {
        case Constants.CREATE:
            boolean isFolder = Boolean
                    .parseBoolean(connectorConfig.getOrDefault(Constants.CREATE_FOLDER, "false"));
            if (path.exists()) {
                throw new RemoteFileSystemConnectorException("File already exists: " + path.getName().getURI());
            }
            if (isFolder) {
                path.createFolder();
            } else {
                path.createFile();
            }
            break;
        case Constants.WRITE:
            if (!path.exists()) {
                path.createFile();
                path.refresh();
                fileType = path.getType();
            }
            if (fileType == FileType.FILE) {
                byteBuffer = message.getBytes();
                byte[] bytes = byteBuffer.array();
                if (connectorConfig.get(Constants.APPEND) != null) {
                    outputStream = path.getContent()
                            .getOutputStream(Boolean.parseBoolean(connectorConfig.get(Constants.APPEND)));
                } else {
                    outputStream = path.getContent().getOutputStream();
                }
                outputStream.write(bytes);
                outputStream.flush();
            }
            break;
        case Constants.DELETE:
            if (path.exists()) {
                int filesDeleted = path.delete(Selectors.SELECT_ALL);
                if (logger.isDebugEnabled()) {
                    logger.debug(filesDeleted + " files successfully deleted");
                }
            } else {
                throw new RemoteFileSystemConnectorException(
                        "Failed to delete file: " + path.getName().getURI() + " not found");
            }
            break;
        case Constants.COPY:
            if (path.exists()) {
                String destination = connectorConfig.get(Constants.DESTINATION);
                FileObject dest = fsManager.resolveFile(destination, opts);
                dest.copyFrom(path, Selectors.SELECT_ALL);
            } else {
                throw new RemoteFileSystemConnectorException(
                        "Failed to copy file: " + path.getName().getURI() + " not found");
            }
            break;
        case Constants.MOVE:
            if (path.exists()) {
                //TODO: Improve this to fix issue #331
                String destination = connectorConfig.get(Constants.DESTINATION);
                FileObject newPath = fsManager.resolveFile(destination, opts);
                FileObject parent = newPath.getParent();
                if (parent != null && !parent.exists()) {
                    parent.createFolder();
                }
                if (!newPath.exists()) {
                    path.moveTo(newPath);
                } else {
                    throw new RemoteFileSystemConnectorException("The file at " + newPath.getURL().toString()
                            + " already exists or it is a directory");
                }
            } else {
                throw new RemoteFileSystemConnectorException(
                        "Failed to move file: " + path.getName().getURI() + " not found");
            }
            break;
        case Constants.READ:
            if (path.exists()) {
                //TODO: Do not assume 'path' always refers to a file
                inputStream = path.getContent().getInputStream();
                byte[] bytes = toByteArray(inputStream);
                RemoteFileSystemMessage fileContent = new RemoteFileSystemMessage(ByteBuffer.wrap(bytes));
                remoteFileSystemListener.onMessage(fileContent);
            } else {
                throw new RemoteFileSystemConnectorException(
                        "Failed to read file: " + path.getName().getURI() + " not found");
            }
            break;
        case Constants.EXISTS:
            RemoteFileSystemMessage fileContent = new RemoteFileSystemMessage(Boolean.toString(path.exists()));
            remoteFileSystemListener.onMessage(fileContent);
            break;
        default:
            break;
        }
        remoteFileSystemListener.done();
    } catch (RemoteFileSystemConnectorException | IOException e) {
        remoteFileSystemListener.onError(e);
    } finally {
        if (path != null) {
            try {
                path.close();
            } catch (FileSystemException e) {
                //Do nothing.
            }
        }
        closeQuietly(inputStream);
        closeQuietly(outputStream);
    }
}

From source file:pl.otros.logview.api.io.Utils.java

public static void closeQuietly(FileObject fileObject) {

    if (fileObject != null) {
        String friendlyURI = fileObject.getName().getFriendlyURI();
        try {//from  ww w  .j av  a 2s  .com
            LOGGER.info(String.format("Closing file %s", friendlyURI));
            fileObject.close();
            LOGGER.info(String.format("File %s closed", friendlyURI));
        } catch (FileSystemException ignore) {
            LOGGER.error(String.format("File %s is not closed: %s", friendlyURI, ignore.getMessage()));
        }
    }
}

From source file:pl.otros.logview.io.Utils.java

public static void closeQuietly(FileObject fileObject) {

    if (fileObject != null) {
        String friendlyURI = fileObject.getName().getFriendlyURI();
        try {// www  .  ja va 2s  .  co  m
            LOGGER.info(String.format("Closing file %s", friendlyURI));
            fileObject.close();
            LOGGER.info(String.format("File %s closed", friendlyURI));
        } catch (FileSystemException ignore) {
            LOGGER.info(String.format("File %s is not closed: %s", friendlyURI, ignore.getMessage()));
        }
    }
}

From source file:tain.kr.test.vfs.v01.ShowProperties.java

private static void test01(String[] args) throws Exception {

    if (flag)/*from w  ww . j av a 2 s  .  com*/
        new ShowProperties();

    if (flag) {

        if (args.length == 0) {
            System.err.println("Please pass the name of a file as parameter.");
            System.err.println("e.g. java org.apache.commons.vfs2.example.ShowProperties LICENSE.txt");
            return;
        }

        for (final String arg : args) {
            try {
                final FileSystemManager mgr = VFS.getManager();
                System.out.println();
                System.out.println("Parsing   : " + arg);
                final FileObject file = mgr.resolveFile(arg);
                System.out.println("URL       : " + file.getURL());
                System.out.println("getName() : " + file.getName());
                System.out.println("BaseName  : " + file.getName().getBaseName());
                System.out.println("Extension : " + file.getName().getExtension());
                System.out.println("Path      : " + file.getName().getPath());
                System.out.println("Scheme    : " + file.getName().getScheme());
                System.out.println("URI       : " + file.getName().getURI());
                System.out.println("Root URI  : " + file.getName().getRootURI());
                System.out.println("Parent    : " + file.getName().getParent());
                System.out.println("Type      : " + file.getType());
                System.out.println("Exists    : " + file.exists());
                System.out.println("Readable  : " + file.isReadable());
                System.out.println("Writeable : " + file.isWriteable());
                System.out.println("Root path : " + file.getFileSystem().getRoot().getName().getPath());

                if (file.exists()) {
                    if (file.getType().equals(FileType.FILE)) {
                        System.out.println("Size: " + file.getContent().getSize() + " bytes");

                    } else if (file.getType().equals(FileType.FOLDER) && file.isReadable()) {

                        final FileObject[] children = file.getChildren();
                        System.out.println("Directory with " + children.length + " files");

                        for (int iterChildren = 0; iterChildren < children.length; iterChildren++) {
                            System.out.println("#" + iterChildren + ": " + children[iterChildren].getName());
                            if (iterChildren > SHOW_MAX) {
                                break;
                            }
                        }
                    }

                    System.out.println("Last modified: " + DateFormat.getInstance()
                            .format(new Date(file.getContent().getLastModifiedTime())));
                } else {
                    System.out.println("The file does not exist");
                }

                file.close();
            } catch (final FileSystemException ex) {
                ex.printStackTrace();
            }
        }
    }
}