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

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

Introduction

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

Prototype

boolean exists() throws FileSystemException;

Source Link

Document

Determines if this file exists.

Usage

From source file:org.wso2.carbon.connector.util.FileUnzipUtil.java

/**
 * @param source        Location of the zip file
 * @param destDirectory Location of the destination folder
 *///  w  w  w . jav a2  s.  co 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

/**
 * //  www .ja  va2  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

/**
 * //from   w  w  w. j  av  a  2s .  c  o  m
 * Acquire distributed lock if required first, then do the file level locking
 * 
 * @param fsManager
 * @param fileObject
 * @return
 */
private boolean acquireLock(FileSystemManager fsManager, FileObject fileObject) {
    String strContext = fileObject.getName().getURI();
    boolean rtnValue = false;
    try {
        if (distributedLock) {
            if (distributedLockTimeout != null) {
                if (!ClusteringServiceUtil.setLock(strContext, distributedLockTimeout)) {
                    return false;
                }
            } else if (!ClusteringServiceUtil.setLock(strContext)) {
                return false;
            }
        }
        // When processing a directory list is fetched initially. Therefore
        // there is still a chance of file processed by another process.
        // Need to check the source file before processing.
        try {
            String parentURI = fileObject.getParent().getName().getURI();
            if (parentURI.contains("?")) {
                String suffix = parentURI.substring(parentURI.indexOf("?"));
                strContext += suffix;
            }
            FileObject sourceFile = fsManager.resolveFile(strContext);
            if (!sourceFile.exists()) {
                return false;
            }
        } catch (FileSystemException e) {
            return false;
        }
        VFSParamDTO vfsParamDTO = new VFSParamDTO();
        vfsParamDTO.setAutoLockRelease(autoLockRelease);
        vfsParamDTO.setAutoLockReleaseSameNode(autoLockReleaseSameNode);
        vfsParamDTO.setAutoLockReleaseInterval(autoLockReleaseInterval);
        rtnValue = VFSUtils.acquireLock(fsManager, fileObject, vfsParamDTO, fso, true);
    } finally {
        if (distributedLock) {
            ClusteringServiceUtil.releaseLock(strContext);
        }
    }
    return rtnValue;
}

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

/**
 * Do the post processing actions//from   w  ww  .j  a  v a 2 s .c om
 * 
 * @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 w  w. j  ava  2  s . c om*/
    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  www .j a  v a  2s .c  om*/
 *
 * @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.filesystem.connector.server.util.FileTransportUtils.java

/**
 * Acquire the file level locking.//from  w w w  . j a  v  a  2s. c  o m
 *
 * @param fsManager     The file system manager instance
 * @param fileObject    The file object to get the lock from
 * @param fsOpts        The file system options to be used with the file system manager
 * @return              Boolean value whether lock was successful
 */
public static synchronized boolean acquireLock(FileSystemManager fsManager, FileObject fileObject,
        FileSystemOptions fsOpts) {
    String strContext = fileObject.getName().getURI();

    // When processing a directory list is fetched initially. Therefore
    // there is still a chance of file processed by another process.
    // Need to check the source file before processing.
    try {
        String parentURI = fileObject.getParent().getName().getURI();
        if (parentURI.contains("?")) {
            String suffix = parentURI.substring(parentURI.indexOf("?"));
            strContext += suffix;
        }
        FileObject sourceFile = fsManager.resolveFile(strContext, fsOpts);
        if (!sourceFile.exists()) {
            return false;
        }
    } catch (FileSystemException e) {
        return false;
    }

    FileObject lockObject = null;

    try {
        // check whether there is an existing lock for this item, if so it is assumed
        // to be processed by an another listener (downloading) or a sender (uploading)
        // lock file is derived by attaching the ".lock" second extension to the file name
        String fullPath = fileObject.getName().getURI();
        int pos = fullPath.indexOf("?");
        if (pos != -1) {
            fullPath = fullPath.substring(0, pos);
        }
        lockObject = fsManager.resolveFile(fullPath + ".lock", fsOpts);
        if (lockObject.exists()) {
            log.debug("There seems to be an external lock, aborting the processing of the file "
                    + maskURLPassword(fileObject.getName().getURI())
                    + ". This could possibly be due to some other party already "
                    + "processing this file or the file is still being uploaded");
        } else if (processing.contains(fullPath)) {
            log.debug(maskURLPassword(fileObject.getName().getURI()) + "is already being processed.");
        } else {
            //Check the original file existence before the lock file to handle concurrent access scenario
            FileObject originalFileObject = fsManager.resolveFile(fullPath, fsOpts);
            if (!originalFileObject.exists()) {
                return false;
            }
            processing.add(fullPath);
            return true;
        }
    } catch (FileSystemException fse) {
        log.error("Cannot get the lock for the file : " + maskURLPassword(fileObject.getName().getURI())
                + " before processing", fse);
        if (lockObject != null) {
            try {
                fsManager.closeFileSystem(lockObject.getParent().getFileSystem());
            } catch (FileSystemException e) {
                log.warn("Unable to close the lockObject parent file system");
            }
        }
    }
    return false;
}

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   w ww.ja  v a2 s.  c  om
    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 w  w  w.  j  a  va 2s . com
 *
 * @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:org.wso2.carbon.transport.remotefilesystem.server.util.FileTransportUtils.java

/**
 * Acquire the file level locking.// w  w  w  . j  ava2  s. c o m
 *
 * @param fsManager     The file system manager instance
 * @param fileObject    The file object to get the lock from
 * @param fsOpts        The file system options to be used with the file system manager
 * @return              Boolean value whether lock was successful
 */
public static synchronized boolean acquireLock(FileSystemManager fsManager, FileObject fileObject,
        FileSystemOptions fsOpts) {
    String strContext = fileObject.getName().getURI();

    // When processing a directory list is fetched initially. Therefore
    // there is still a chance of file processed by another process.
    // Need to check the source file before processing.
    try {
        String parentURI = fileObject.getParent().getName().getURI();
        if (parentURI.contains("?")) {
            String suffix = parentURI.substring(parentURI.indexOf("?"));
            strContext += suffix;
        }
        FileObject sourceFile = fsManager.resolveFile(strContext, fsOpts);
        if (!sourceFile.exists()) {
            return false;
        }
    } catch (FileSystemException e) {
        return false;
    }
    FileObject lockObject = null;
    try {
        // check whether there is an existing lock for this item, if so it is assumed
        // to be processed by an another listener (downloading) or a sender (uploading)
        // lock file is derived by attaching the ".lock" second extension to the file name
        String fullPath = fileObject.getName().getURI();
        int pos = fullPath.indexOf("?");
        if (pos != -1) {
            fullPath = fullPath.substring(0, pos);
        }
        lockObject = fsManager.resolveFile(fullPath + ".lock", fsOpts);
        if (lockObject.exists()) {
            if (log.isDebugEnabled()) {
                log.debug("There seems to be an external lock, aborting the processing of the file "
                        + maskURLPassword(fileObject.getName().getURI())
                        + ". This could possibly be due to some other party already "
                        + "processing this file or the file is still being uploaded");
            }
        } else if (processing.contains(fullPath)) {
            if (log.isDebugEnabled()) {
                log.debug(maskURLPassword(fileObject.getName().getURI()) + "is already being processed.");
            }
        } else {
            //Check the original file existence before the lock file to handle concurrent access scenario
            FileObject originalFileObject = fsManager.resolveFile(fullPath, fsOpts);
            if (!originalFileObject.exists()) {
                return false;
            }
            processing.add(fullPath);
            return true;
        }
    } catch (FileSystemException fse) {
        log.error("Cannot get the lock for the file : " + maskURLPassword(fileObject.getName().getURI())
                + " before processing", fse);
        if (lockObject != null) {
            try {
                fsManager.closeFileSystem(lockObject.getParent().getFileSystem());
            } catch (FileSystemException e) {
                log.warn("Unable to close the lockObject parent file system");
            }
        }
    }
    return false;
}