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

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

Introduction

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

Prototype

void createFolder() throws FileSystemException;

Source Link

Document

Creates this folder, if it does not exist.

Usage

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

/**
 * Move the file for given pattern./* www .ja  v a  2 s  .c om*/
 *
 * @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.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.//ww w.  j a v a  2s .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.util.FileUnzipUtil.java

/**
 * @param source        Location of the zip file
 * @param destDirectory Location of the destination folder
 *///w  w w. ja va  2  s  .  c  o  m
public boolean unzip(String source, String destDirectory, MessageContext messageContext) {
    OMFactory factory = OMAbstractFactory.getOMFactory();
    OMNamespace ns = factory.createOMNamespace(FileConstants.FILECON, FileConstants.NAMESPACE);
    OMElement result = factory.createOMElement(FileConstants.RESULT, ns);
    boolean resultStatus = false;
    FileSystemOptions opts = FileConnectorUtils.init(messageContext);
    try {
        manager = FileConnectorUtils.getManager();
        // Create remote object
        FileObject remoteFile = manager.resolveFile(source, opts);
        FileObject remoteDesFile = manager.resolveFile(destDirectory, opts);
        // File destDir = new File(destDirectory);
        if (remoteFile.exists()) {
            if (!remoteDesFile.exists()) {
                //create a folder
                remoteDesFile.createFolder();
            }
            //open the zip file
            ZipInputStream zipIn = new ZipInputStream(remoteFile.getContent().getInputStream());
            ZipEntry entry = zipIn.getNextEntry();
            try {
                // iterates over entries in the zip file
                while (entry != null) {
                    // boolean testResult;
                    String filePath = destDirectory + 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, filePath, opts);
                            OMElement messageElement = factory.createOMElement(FileConstants.FILE, ns);
                            messageElement.setText(entry.getName() + " | status:" + "true");
                            result.addChild(messageElement);
                        } else {
                            // if the entry is a directory, make the directory
                            remoteFilePath.createFolder();
                        }
                    } catch (IOException e) {
                        log.error("Unable to process the zip file. ", e);
                    } finally {
                        zipIn.closeEntry();
                        entry = zipIn.getNextEntry();
                    }
                }
                messageContext.getEnvelope().getBody().addChild(result);
                resultStatus = true;
            } finally {
                //we must always close the zip file
                zipIn.close();
            }
        } else {
            log.error("File does not exist.");
        }
    } catch (IOException e) {
        log.error("Unable to process the zip file." + e.getMessage(), e);
    } finally {
        manager.close();
    }
    return resultStatus;
}

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

/**
 * Do the post processing actions/*w w w. j a  v  a 2  s . c o 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.sender.VFSClientConnector.java

@Override
public boolean send(CarbonMessage carbonMessage, CarbonCallback carbonCallback, Map<String, String> map)
        throws ClientConnectorException {
    FtpFileSystemConfigBuilder.getInstance().setPassiveMode(opts, true);
    String fileURI = map.get(Constants.FILE_URI);
    String action = map.get(Constants.ACTION);
    FileType fileType;//from  w  ww.j  a  v a2  s. c  o  m
    ByteBuffer byteBuffer;
    InputStream inputStream = null;
    OutputStream outputStream = null;
    try {
        FileSystemManager fsManager = VFS.getManager();
        FileObject path = fsManager.resolveFile(fileURI, opts);
        fileType = path.getType();
        switch (action) {

        case Constants.CREATE:
            boolean isFolder = Boolean.parseBoolean(map.getOrDefault("create-folder", "false"));
            if (path.exists()) {
                throw new ClientConnectorException("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) {
                if (carbonMessage instanceof BinaryCarbonMessage) {
                    BinaryCarbonMessage binaryCarbonMessage = (BinaryCarbonMessage) carbonMessage;
                    byteBuffer = binaryCarbonMessage.readBytes();
                } else {
                    throw new ClientConnectorException("Carbon message received is not a BinaryCarbonMessage");
                }
                byte[] bytes = byteBuffer.array();
                if (map.get(Constants.APPEND) != null) {
                    outputStream = path.getContent()
                            .getOutputStream(Boolean.parseBoolean(map.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 ClientConnectorException(
                        "Failed to delete file: " + path.getName().getURI() + " not found");
            }
            break;
        case Constants.COPY:
            if (path.exists()) {
                String destination = map.get("destination");
                FileObject dest = fsManager.resolveFile(destination, opts);
                dest.copyFrom(path, Selectors.SELECT_ALL);
            } else {
                throw new ClientConnectorException(
                        "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 = map.get("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 ClientConnectorException("The file at " + newPath.getURL().toString()
                            + " already exists or it is a directory");
                }
            } else {
                throw new ClientConnectorException(
                        "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);
                BinaryCarbonMessage message = new BinaryCarbonMessage(ByteBuffer.wrap(bytes), true);
                message.setProperty(org.wso2.carbon.messaging.Constants.DIRECTION,
                        org.wso2.carbon.messaging.Constants.DIRECTION_RESPONSE);
                carbonMessageProcessor.receive(message, carbonCallback);
            } else {
                throw new ClientConnectorException(
                        "Failed to read file: " + path.getName().getURI() + " not found");
            }
            break;
        case Constants.EXISTS:
            TextCarbonMessage message = new TextCarbonMessage(Boolean.toString(path.exists()));
            message.setProperty(org.wso2.carbon.messaging.Constants.DIRECTION,
                    org.wso2.carbon.messaging.Constants.DIRECTION_RESPONSE);
            carbonMessageProcessor.receive(message, carbonCallback);
            break;
        default:
            return false;
        }
    } catch (RuntimeException e) {
        throw new ClientConnectorException("Runtime Exception occurred : " + e.getMessage(), e);
    } catch (Exception e) {
        throw new ClientConnectorException("Exception occurred while processing file: " + e.getMessage(), e);
    } finally {
        closeQuietly(inputStream);
        closeQuietly(outputStream);
    }
    return true;
}

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

/**
 * Do the post processing actions./*from w ww . j a  v  a  2  s.c  o  m*/
 *
 * @param file The file object which needs to be post processed
 * @param processFailed Whether processing of file failed
 */
synchronized void postProcess(FileObject file, boolean processFailed)
        throws FileSystemServerConnectorException {
    String moveToDirectoryURI = null;
    FileType fileType = getFileType(file);
    if (!processFailed) {
        if (postProcessAction.equals(Constants.ACTION_MOVE)) {
            moveToDirectoryURI = fileProperties.get(Constants.MOVE_AFTER_PROCESS);
        }
    } else {
        if (postFailureAction.equals(Constants.ACTION_MOVE)) {
            moveToDirectoryURI = fileProperties.get(Constants.MOVE_AFTER_FAILURE);
        }
    }

    if (moveToDirectoryURI != null) {
        try {
            if (getFileType(fsManager.resolveFile(moveToDirectoryURI, fso)) == FileType.FILE) {
                moveToDirectoryURI = null;
                if (processFailed) {
                    postFailureAction = Constants.ACTION_NONE;
                } else {
                    postProcessAction = Constants.ACTION_NONE;
                }
                if (log.isDebugEnabled()) {
                    log.debug(
                            "Cannot move file because provided location is not a folder. File is kept at source");
                }
            }
        } catch (FileSystemException e) {
            errorHandler
                    .handleError(
                            new FileSystemServerConnectorException(
                                    "Error occurred when resolving move destination file: "
                                            + FileTransportUtils.maskURLPassword(listeningDirURI),
                                    e),
                            null, null);
        }
    }

    try {
        if (!(moveToDirectoryURI == null || fileType == FileType.FOLDER)) {
            FileObject moveToDirectory;
            String relativeName = file.getName().getURI().split(listeningDir.getName().getURI())[1];
            int index = relativeName.lastIndexOf(File.separator);
            moveToDirectoryURI += relativeName.substring(0, index);
            moveToDirectory = fsManager.resolveFile(moveToDirectoryURI, fso);
            String prefix;
            if (fileProperties.get(Constants.MOVE_TIMESTAMP_FORMAT) != null) {
                prefix = new SimpleDateFormat(fileProperties.get(Constants.MOVE_TIMESTAMP_FORMAT))
                        .format(new Date());
            } else {
                prefix = "";
            }

            //Forcefully create the folder(s) if does not exists
            String strForceCreateFolder = fileProperties.get(Constants.FORCE_CREATE_FOLDER);
            if (strForceCreateFolder != null && strForceCreateFolder.equalsIgnoreCase("true")
                    && !moveToDirectory.exists()) {
                moveToDirectory.createFolder();
            }

            FileObject dest = moveToDirectory.resolveFile(prefix + file.getName().getBaseName());
            if (log.isDebugEnabled()) {
                log.debug("Moving to file :" + FileTransportUtils.maskURLPassword(dest.getName().getURI()));
            }
            if (log.isInfoEnabled()) {
                log.info("Moving file :" + FileTransportUtils.maskURLPassword(file.getName().getBaseName()));
            }
            try {
                file.moveTo(dest);
                if (isFailRecord(file)) {
                    releaseFail(file);
                }
            } catch (FileSystemException e) {
                if (!isFailRecord(file)) {
                    markFailRecord(file);
                }
                errorHandler.handleError(
                        new FileSystemServerConnectorException(
                                "Error moving file : " + FileTransportUtils.maskURLPassword(file.toString())
                                        + " to " + FileTransportUtils.maskURLPassword(moveToDirectoryURI),
                                e),
                        null, null);
            }

        } else {
            if (log.isDebugEnabled()) {
                log.debug("Deleting file :" + FileTransportUtils.maskURLPassword(file.getName().getBaseName()));
            }
            if (log.isInfoEnabled()) {
                log.info("Deleting file :" + FileTransportUtils.maskURLPassword(file.getName().getBaseName()));
            }
            try {
                if (!file.delete()) {
                    if (log.isDebugEnabled()) {
                        log.debug("Could not delete file : "
                                + FileTransportUtils.maskURLPassword(file.getName().getBaseName()));
                    }
                } else {
                    if (isFailRecord(file)) {
                        releaseFail(file);
                    }
                }
            } catch (FileSystemException e) {
                errorHandler.handleError(
                        new FileSystemServerConnectorException("Could not delete file : "
                                + FileTransportUtils.maskURLPassword(file.getName().getBaseName()), e),
                        null, null);
            }
        }
    } catch (FileSystemException e) {
        if (!isFailRecord(file)) {
            markFailRecord(file);
            errorHandler.handleError(
                    new FileSystemServerConnectorException("Error resolving directory to move file : "
                            + FileTransportUtils.maskURLPassword(moveToDirectoryURI), e),
                    null, null);
        }
    }
}

From source file:org.wso2.carbon.transport.remotefilesystem.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   ww w  . j  av a2s.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:org.wso2.carbon.transport.remotefilesystem.server.RemoteFileSystemConsumer.java

/**
 * Do the post processing actions./*from ww w . j a  v a2  s.  c o  m*/
 *
 * @param file The file object which needs to be post processed
 * @param processSucceed Whether processing of file passed or not.
 */
synchronized void postProcess(FileObject file, boolean processSucceed)
        throws RemoteFileSystemConnectorException {
    String moveToDirectoryURI = null;
    FileType fileType = getFileType(file);
    if (processSucceed) {
        if (postProcessAction.equals(Constants.ACTION_MOVE)) {
            moveToDirectoryURI = fileProperties.get(Constants.MOVE_AFTER_PROCESS);
        }
    } else {
        if (postFailureAction.equals(Constants.ACTION_MOVE)) {
            moveToDirectoryURI = fileProperties.get(Constants.MOVE_AFTER_FAILURE);
        }
    }
    if (moveToDirectoryURI != null) {
        try {
            if (getFileType(fsManager.resolveFile(moveToDirectoryURI, fso)) == FileType.FILE) {
                moveToDirectoryURI = null;
                if (processSucceed) {
                    postProcessAction = Constants.ACTION_NONE;
                } else {
                    postFailureAction = Constants.ACTION_NONE;
                }
                log.warn("[" + serviceName + "] Cannot move file because provided location is not a folder."
                        + " File is kept at source.");
            }
        } catch (FileSystemException e) {
            remoteFileSystemListener.onError(new RemoteFileSystemConnectorException(
                    "Error occurred when resolving move destination file: "
                            + FileTransportUtils.maskURLPassword(listeningDirURI),
                    e));
        }
    }
    if (postProcessAction.equals(Constants.ACTION_NONE) && fileType == FileType.FOLDER) {
        return;
    }
    try {
        if (!(moveToDirectoryURI == null || fileType == FileType.FOLDER)) {
            FileObject moveToDirectory;
            String relativeName = file.getName().getURI().split(listeningDir.getName().getURI())[1];
            int index = relativeName.lastIndexOf(File.separator);
            moveToDirectoryURI += relativeName.substring(0, index);
            moveToDirectory = fsManager.resolveFile(moveToDirectoryURI, fso);
            String prefix;
            if (fileProperties.get(Constants.MOVE_TIMESTAMP_FORMAT) != null) {
                prefix = new SimpleDateFormat(fileProperties.get(Constants.MOVE_TIMESTAMP_FORMAT))
                        .format(new Date());
            } else {
                prefix = "";
            }
            //Forcefully create the folder(s) if does not exists
            String strForceCreateFolder = fileProperties.get(Constants.FORCE_CREATE_FOLDER);
            if (strForceCreateFolder != null && strForceCreateFolder.equalsIgnoreCase("true")
                    && !moveToDirectory.exists()) {
                moveToDirectory.createFolder();
            }
            FileObject destination = moveToDirectory.resolveFile(prefix + file.getName().getBaseName());
            if (log.isDebugEnabled()) {
                log.debug("Moving file: " + FileTransportUtils.maskURLPassword(file.getName().getBaseName()));
            }
            try {
                file.moveTo(destination);
                if (isFailRecord(file)) {
                    releaseFail(file);
                }
            } catch (FileSystemException e) {
                if (!isFailRecord(file)) {
                    markFailRecord(file);
                }
                remoteFileSystemListener.onError(new RemoteFileSystemConnectorException("[" + serviceName
                        + "] Error moving file: " + FileTransportUtils.maskURLPassword(file.toString()) + " to "
                        + FileTransportUtils.maskURLPassword(moveToDirectoryURI), e));
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Deleting file: " + FileTransportUtils.maskURLPassword(file.getName().getBaseName()));
            }
            try {
                if (!file.delete()) {
                    if (log.isDebugEnabled()) {
                        log.debug("Could not delete file: "
                                + FileTransportUtils.maskURLPassword(file.getName().getBaseName()));
                    }
                } else {
                    if (isFailRecord(file)) {
                        releaseFail(file);
                    }
                }
            } catch (FileSystemException e) {
                remoteFileSystemListener.onError(
                        new RemoteFileSystemConnectorException("[" + serviceName + "] Could not delete file: "
                                + FileTransportUtils.maskURLPassword(file.getName().getBaseName()), e));
            }
        }
    } catch (FileSystemException e) {
        if (!isFailRecord(file)) {
            markFailRecord(file);
            remoteFileSystemListener.onError(new RemoteFileSystemConnectorException(
                    "[" + serviceName + "] Error resolving directory to move file : "
                            + FileTransportUtils.maskURLPassword(moveToDirectoryURI),
                    e));
        }
    }
}

From source file:se.kth.hopsworks.zeppelin.notebook.repo.FSNotebookRepo.java

@Override
public void save(Note note) throws IOException {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setPrettyPrinting();//from  ww w . j a  va  2  s.  co  m
    Gson gson = gsonBuilder.create();
    String json = gson.toJson(note);

    FileObject rootDir = getRootDir();

    FileObject projectDir = rootDir.resolveFile(this.project.getName(), NameScope.CHILD);
    if (!projectDir.exists()) {
        projectDir.createFolder();
    }
    if (!isDirectory(projectDir)) {
        throw new IOException(projectDir.getName().toString() + " is not a directory");
    }

    FileObject noteDir = projectDir.resolveFile(note.id(), NameScope.CHILD);

    if (!noteDir.exists()) {
        noteDir.createFolder();
    }
    if (!isDirectory(noteDir)) {
        throw new IOException(noteDir.getName().toString() + " is not a directory");
    }

    FileObject noteJson = noteDir.resolveFile("note.json", NameScope.CHILD);
    // false means not appending. creates file if not exists
    OutputStream out = noteJson.getContent().getOutputStream(false);
    out.write(json.getBytes(conf.getString(ConfVars.ZEPPELIN_ENCODING)));
    out.close();
    noteJson.moveTo(noteDir.resolveFile("note.json", NameScope.CHILD));
}