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

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

Introduction

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

Prototype

FileName getName();

Source Link

Document

Returns the name of this file.

Usage

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

/**
 * Inject the message to the sequence/*from  w  w  w .ja v  a2  s .c  om*/
 * */
public boolean invoke(Object object, String name) throws SynapseException {

    ManagedDataSource dataSource = null;
    ;
    FileObject file = (FileObject) object;
    try {
        org.apache.synapse.MessageContext msgCtx = createMessageContext();
        msgCtx.setProperty("inbound.endpoint.name", name);
        InboundEndpoint inboundEndpoint = msgCtx.getConfiguration().getInboundEndpoint(name);
        CustomLogSetter.getInstance().setLogAppender(inboundEndpoint.getArtifactContainerName());
        String contentType = vfsProperties.getProperty(VFSConstants.TRANSPORT_FILE_CONTENT_TYPE);
        if (contentType == null || contentType.trim().equals("")) {
            if (file.getName().getExtension().toLowerCase().endsWith("xml")) {
                contentType = "text/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.
            String charSetEnc = null;
            try {
                if (contentType != null) {
                    charSetEnc = new ContentType(contentType).getParameter("charset");
                }
            } catch (ParseException ex) {
                // ignore
            }
            msgCtx.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc);
        }
        if (log.isDebugEnabled()) {
            log.debug("Processed file : " + file + " of Content-type : " + contentType);
        }
        MessageContext axis2MsgCtx = ((org.apache.synapse.core.axis2.Axis2MessageContext) msgCtx)
                .getAxis2MessageContext();
        // Determine the message builder to use
        Builder builder;
        if (contentType == null) {
            log.debug("No content type specified. Using SOAP builder.");
            builder = new SOAPBuilder();
        } 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 SOAP.");
                }
                builder = new SOAPBuilder();
            }
        }

        // set the message payload to the message context
        InputStream in;
        String streaming = vfsProperties.getProperty(VFSConstants.STREAMING);

        if (builder instanceof DataSourceMessageBuilder && "true".equals(streaming)) {
            dataSource = ManagedDataSourceFactory.create(new FileObjectDataSource(file, contentType));
            in = null;
        } else {
            in = new AutoCloseInputStream(file.getContent().getInputStream());
            dataSource = null;
        }

        //Inject the message to the sequence.

        OMElement documentElement;
        if (in != null) {
            documentElement = builder.processDocument(in, contentType, axis2MsgCtx);
        } else {
            documentElement = ((DataSourceMessageBuilder) builder).processDocument(dataSource, contentType,
                    axis2MsgCtx);
        }

        if ("true".equals(vfsProperties.getProperty(VFSConstants.TRANSPORT_BUILD))) {
            documentElement.build();
        }
        msgCtx.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement));

        if (injectingSeq == null || injectingSeq.equals("")) {
            log.error("Sequence name not specified. Sequence : " + injectingSeq);
        }
        SequenceMediator seq = (SequenceMediator) synapseEnvironment.getSynapseConfiguration()
                .getSequence(injectingSeq);
        if (seq != null) {
            if (log.isDebugEnabled()) {
                log.debug("injecting message to sequence : " + injectingSeq);
            }
            if (!seq.isInitialized()) {
                seq.init(synapseEnvironment);
            }
            seq.setErrorHandler(onErrorSeq);
            if (!synapseEnvironment.injectInbound(msgCtx, seq, sequential)) {
                return false;
            }
        } else {
            log.error("Sequence: " + injectingSeq + " not found");
        }
    } catch (SynapseException se) {
        throw se;
    } catch (Exception e) {
        log.error("Error while processing the file/folder", e);
        throw new SynapseException("Error while processing the file/folder", e);
    } finally {
        if (dataSource != null) {
            dataSource.destroy();
        }
    }
    return true;
}

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

/**
 * //from   w  w  w. j av  a  2  s  . co m
 * 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

/**
 * //w w  w  .  jav  a2  s.  co  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

/**
 * Actual processing of the file/folder/*from  ww  w .  ja  v a  2 s .  co m*/
 * 
 * @param file
 * @return
 * @throws synapseException
 */
private FileObject processFile(FileObject file) throws SynapseException {
    try {
        FileContent content = file.getContent();
        String fileName = file.getName().getBaseName();
        String filePath = file.getName().getPath();
        String fileURI = file.getName().getURI();

        if (injectHandler != null) {
            Map<String, Object> transportHeaders = new HashMap<String, Object>();
            transportHeaders.put(VFSConstants.FILE_PATH, filePath);
            transportHeaders.put(VFSConstants.FILE_NAME, fileName);
            transportHeaders.put(VFSConstants.FILE_URI, fileURI);

            try {
                transportHeaders.put(VFSConstants.FILE_LENGTH, content.getSize());
                transportHeaders.put(VFSConstants.LAST_MODIFIED, content.getLastModifiedTime());
            } catch (FileSystemException e) {
                log.warn("Unable to set file length or last modified date header.", e);
            }

            injectHandler.setTransportHeaders(transportHeaders);
            // injectHandler
            if (!injectHandler.invoke(file, name)) {
                return null;
            }
        }

    } catch (FileSystemException e) {
        log.error("Error reading file content or attributes : " + VFSUtils.maskURLPassword(file.toString()), e);
    }
    return file;
}

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

/**
 * Do the post processing actions/*from   w ww  .j  a  v a  2s  . 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.mediation.connector.pmode.PModeRepository.java

/**
 * Constructor for PMode repository implementation.
 *
 * @param pmodeRepositoryPath Path to the directory containing PMode files
 *///w  ww  . j a v a 2 s  .c  o m
private PModeRepository(String pmodeRepositoryPath) throws AxisFault {

    if (log.isDebugEnabled()) {
        log.debug("Initializing PMode repository for the location : " + pmodeRepositoryPath);
    }

    this.pModeMap = new HashMap<String, PMode>();
    this.fileNameRefMap = new HashMap<String, String>();
    this.possibleNameChangeMap = new HashMap<String, String>();
    File pmodeFolder;

    try {
        this.pModeUnmarshaller = JAXBContext.newInstance(PMode.class).createUnmarshaller();
    } catch (JAXBException e) {
        log.error("Unable to create JAXB unmarshaller for : " + PMode.class, e);
        throw new AxisFault("Unable to create JAXB unmarshaller for : " + PMode.class, e);
    }

    if (pmodeRepositoryPath != null) {
        pmodeFolder = new File(pmodeRepositoryPath);
        if (!pmodeFolder.exists() || !pmodeFolder.isDirectory()) {
            log.warn("Provided PMode directory is invalid, falling back to default PMode Directory : "
                    + AS4Constants.AS4_PMODE_LOCATION);
            pmodeFolder = new File(AS4Constants.AS4_PMODE_LOCATION);
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("PMode directory not provided, falling back to default PMode Directory : "
                    + AS4Constants.AS4_PMODE_LOCATION);
        }
        pmodeFolder = new File(AS4Constants.AS4_PMODE_LOCATION);
    }

    traversePmodeDirectory(pmodeFolder);
    try {
        FileSystemManager fileSystemManager = VFS.getManager();
        FileObject listenDirectory = fileSystemManager.resolveFile(pmodeFolder.getAbsolutePath());
        this.basePathLength = listenDirectory.getName().getPathDecoded().length() + 1;
        DefaultFileMonitor fileMonitor = new DefaultFileMonitor(this);
        fileMonitor.addFile(listenDirectory);
        fileMonitor.start();
    } catch (FileSystemException e) {
        log.warn("Error registering PMode watcher, hence needs to restart the server when PModes "
                + "change or added, " + e.getMessage(), 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  av  a 2 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.file.connector.server.FileConsumer.java

/**
 * Handle directory with chile elements//from  w ww. j  a v a 2 s .  co  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.file.connector.server.FileConsumer.java

/**
 * Actual processing of the file/folder/*  w  ww.j a v  a 2  s . co m*/
 *
 * @param file
 * @return
 */
private FileObject processFile(FileObject file) throws FileServerConnectorException {
    FileContent content;
    String fileURI;

    String fileName = file.getName().getBaseName();
    String filePath = file.getName().getPath();
    fileURI = file.getName().getURI();

    try {
        content = file.getContent();
    } catch (FileSystemException e) {
        throw new FileServerConnectorException(
                "Could not read content of file at URI: " + FileTransportUtils.maskURLPassword(fileURI) + ". ",
                e);
    }

    InputStream inputStream;
    try {
        inputStream = content.getInputStream();
    } catch (FileSystemException e) {
        throw new FileServerConnectorException("Error occurred when trying to get "
                + "input stream from file at URI :" + FileTransportUtils.maskURLPassword(fileURI), e);
    }
    CarbonMessage cMessage = new StreamingCarbonMessage(inputStream);
    cMessage.setProperty(org.wso2.carbon.messaging.Constants.PROTOCOL, Constants.PROTOCOL_NAME);
    cMessage.setProperty(Constants.FILE_TRANSPORT_PROPERTY_SERVICE_NAME, serviceName);
    cMessage.setHeader(Constants.FILE_PATH, filePath);
    cMessage.setHeader(Constants.FILE_NAME, fileName);
    cMessage.setHeader(Constants.FILE_URI, fileURI);
    try {
        cMessage.setHeader(Constants.FILE_LENGTH, Long.toString(content.getSize()));
        cMessage.setHeader(Constants.LAST_MODIFIED, Long.toString(content.getLastModifiedTime()));
    } catch (FileSystemException e) {
        log.warn("Unable to set file length or last modified date header.", e);
    }

    FileServerConnectorCallback callback = new FileServerConnectorCallback();
    try {
        messageProcessor.receive(cMessage, callback);
    } catch (Exception e) {
        throw new FileServerConnectorException("Failed to send stream from file: "
                + FileTransportUtils.maskURLPassword(fileURI) + " to message processor. ", e);
    }
    try {
        callback.waitTillDone(timeOutInterval, deleteIfNotAck, fileURI);
    } catch (InterruptedException e) {
        throw new FileServerConnectorException("Interrupted while waiting for message "
                + "processor to consume the file input stream. Aborting processing of file: "
                + FileTransportUtils.maskURLPassword(fileURI), e);
    }
    return file;
}

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

/**
 * Do the post processing actions//  w  w  w  .  j  a va2 s  .c om
 *
 * @param fileObject
 */
private void deleteFile(FileObject fileObject) throws FileServerConnectorException {
    if (log.isDebugEnabled()) {
        log.debug("Deleting file :" + FileTransportUtils.maskURLPassword(fileObject.getName().getBaseName()));
    }
    try {
        if (!fileObject.delete()) {
            throw new FileServerConnectorException("Could not delete file : "
                    + FileTransportUtils.maskURLPassword(fileObject.getName().getBaseName()));
        }
    } catch (FileSystemException e) {
        throw new FileServerConnectorException("Could not delete file : "
                + FileTransportUtils.maskURLPassword(fileObject.getName().getBaseName()), e);
    }
}