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

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

Introduction

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

Prototype

FileContent getContent() throws FileSystemException;

Source Link

Document

Returns this file's content.

Usage

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

/**
 * @param messageContext The message context that is generated for processing the file
 * @param source         Location of the zip file
 *//*from ww w.j  av  a  2s.  co  m*/
private void list(MessageContext messageContext, String source) {
    StandardFileSystemManager manager = null;
    try {
        manager = FileConnectorUtils.getManager();
        ResultPayloadCreate resultPayload = new ResultPayloadCreate();

        // Create remote object
        FileObject remoteFile = manager.resolveFile(source, FileConnectorUtils.init(messageContext));
        if (remoteFile != null && remoteFile.exists()) {
            // open the zip file
            InputStream input = remoteFile.getContent().getInputStream();
            ZipInputStream zip = new ZipInputStream(input);
            OMFactory factory = OMAbstractFactory.getOMFactory();
            String outputResult;
            OMNamespace ns = factory.createOMNamespace(FileConstants.FILECON, FileConstants.NAMESPACE);
            OMElement result = factory.createOMElement(FileConstants.RESULT, ns);
            resultPayload.preparePayload(messageContext, result);
            ZipEntry zipEntry;
            // iterates over entries in the zip file
            while ((zipEntry = zip.getNextEntry()) != null) {
                if (!zipEntry.isDirectory()) {
                    //add the entries
                    outputResult = zipEntry.getName();
                    OMElement messageElement = factory.createOMElement(FileConstants.FILE, ns);
                    messageElement.setText(outputResult);
                    result.addChild(messageElement);
                }
            }
            messageContext.getEnvelope().getBody().addChild(result);
            if (log.isDebugEnabled()) {
                log.debug("The envelop body with the read files path is "
                        + messageContext.getEnvelope().getBody().toString());
            }
            //we must always close the zip file
            zip.close();
            if (log.isDebugEnabled()) {
                log.debug("File listZip completed with. " + source);
            }
        } else {
            log.error("Zip file does not exist.");
        }
    } catch (IOException e) {
        handleException("Error while processing a file.", e, messageContext);
    } finally {
        if (manager != null) {
            manager.close();
        }
    }
}

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

/**
 * List all the files inside zip file./*from  w  ww.  j a v a 2  s. c om*/
 *
 * @param messageContext The message context that is generated for processing the file.
 */
private void listAllFiles(MessageContext messageContext) throws FileSystemException {
    String source = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.FILE_LOCATION);
    StandardFileSystemManager manager = FileConnectorUtils.getManager();
    FileObject remoteFile = manager.resolveFile(source, FileConnectorUtils.init(messageContext));
    if (!remoteFile.exists()) {
        log.error("Zip file location does not exist.");
    }
    // open the zip file
    InputStream input = remoteFile.getContent().getInputStream();
    ZipInputStream zip = new ZipInputStream(input);
    OMFactory factory = OMAbstractFactory.getOMFactory();
    OMNamespace ns = factory.createOMNamespace(FileConstants.FILECON, FileConstants.NAMESPACE);
    OMElement result = factory.createOMElement(FileConstants.RESULT, ns);
    ZipEntry zipEntry;
    try {
        while ((zipEntry = zip.getNextEntry()) != null && !zipEntry.isDirectory()) {
            // add the entries
            String outputResult = zipEntry.getName();
            OMElement messageElement = factory.createOMElement(FileConstants.FILE, ns);
            messageElement.setText(outputResult);
            result.addChild(messageElement);
        }
    } catch (IOException e) {
        throw new SynapseException("Error while reading the next ZIP file entry", e);
    } finally {
        try {
            zip.close();
        } catch (IOException e) {
            log.error("Error while closing ZipInputStream");
        }
        try {
            remoteFile.close();
        } catch (FileSystemException e) {
            log.error("Error while closing the FileObject", e);
        }
        // close the StandardFileSystemManager
        manager.close();
    }
    ResultPayloadCreator.preparePayload(messageContext, result);
    if (log.isDebugEnabled()) {
        log.debug("The envelop body with the read files path is "
                + messageContext.getEnvelope().getBody().toString());
    }
}

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

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

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

/**
 * Send the file to the target directory.
 *
 * @param messageContext The message context that is used in file send mediation flow.
 * @return return true, if file is sent successfully.
 * @throws FileSystemException On error parsing the file name and getting file type.
 *//*from   w  w  w .ja  v  a2  s . c o  m*/

private boolean sendResponseFile(MessageContext messageContext) throws FileSystemException {
    boolean append = false;
    String destination = (String) ConnectorUtils.lookupTemplateParamater(messageContext,
            FileConstants.NEW_FILE_LOCATION);
    String strAppend = (String) ConnectorUtils.lookupTemplateParamater(messageContext, FileConstants.APPEND);
    if (StringUtils.isNotEmpty(strAppend)) {
        append = Boolean.parseBoolean(strAppend);
    }
    StandardFileSystemManager manager = FileConnectorUtils.getManager();
    FileObject fileObjectToSend = null;
    FileObject fileObj = manager.resolveFile(destination, FileConnectorUtils.init(messageContext));
    CountingOutputStream outputStream = null;
    if (log.isDebugEnabled()) {
        log.debug("File sending started to " + destination);
    }
    try {
        org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext)
                .getAxis2MessageContext();

        if (FileType.FOLDER.equals(fileObj.getType())) {
            String destDir = destination.concat(FileConstants.DEFAULT_RESPONSE_FILE);
            fileObjectToSend = manager.resolveFile(destDir, FileConnectorUtils.init(messageContext));
        } else if (FileType.FILE.equals(fileObj.getType())) {
            fileObjectToSend = fileObj;
        }
        // Get the message formatter.
        MessageFormatter messageFormatter = getMessageFormatter(axis2MessageContext);
        OMOutputFormat format = BaseUtils.getOMOutputFormat(axis2MessageContext);
        // Creating output stream and give the content to that.
        outputStream = new CountingOutputStream(fileObjectToSend.getContent().getOutputStream(append));
        messageFormatter.writeTo(axis2MessageContext, format, outputStream, true);
        if (log.isDebugEnabled()) {
            log.debug("File send completed to " + destination);
        }
    } catch (AxisFault e) {
        throw new SynapseException("Error while writing the message context", e);
    } finally {
        try {
            fileObjectToSend.close();
        } catch (FileSystemException e) {
            log.error("Error while closing FileObject", e);
        }
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException e) {
            log.warn("Can not close the output stream");
        }
        manager.close();
    }
    return true;
}

From source file:org.wso2.carbon.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.//from ww w  . jav a2s  . c o 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.FileUnzipConnector.java

/**
 * Extract each zip entry and write it into file.
 *
 * @param zipIn          Zip input stream for reading file in the ZIP file format.
 * @param remoteFilePath Location of file where zip entry needs to be extracted.
 *//*from  w w  w  .j  a v  a 2 s.c  om*/
private void extractFile(ZipInputStream zipIn, FileObject remoteFilePath) {
    BufferedOutputStream bos = null;
    try {
        // open the zip file
        OutputStream fOut = remoteFilePath.getContent().getOutputStream();
        bos = new BufferedOutputStream(fOut);
        byte[] bytesIn = new byte[FileConstants.BUFFER_SIZE];
        int read;
        while ((read = zipIn.read(bytesIn)) != -1) {
            bos.write(bytesIn, 0, read);
        }
    } catch (IOException e) {
        throw new SynapseException("Unable to write zip entry", e);
    } finally {
        // close the zip file
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException e) {
                log.error("Error while closing the BufferedOutputStream", e);
            }
        }
        try {
            remoteFilePath.close();
        } catch (FileSystemException e) {
            log.error("Error while closing FileObject", e);
        }
    }
}

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 . j a  v  a 2s  . com*/
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.connector.util.FileUnzipUtil.java

/**
 * @param zipIn    :Input zip stream//w ww .j a va2  s.co  m
 * @param filePath :Location of each entry of the file.
 */
private void extractFile(ZipInputStream zipIn, String filePath, FileSystemOptions opts) {
    BufferedOutputStream bos = null;
    try {
        // Create remote object
        FileObject remoteFilePath = manager.resolveFile(filePath, opts);
        //open the zip file
        OutputStream fOut = remoteFilePath.getContent().getOutputStream();
        bos = new BufferedOutputStream(fOut);
        byte[] bytesIn = new byte[FileConstants.BUFFER_SIZE];
        int read;
        while ((read = zipIn.read(bytesIn)) != -1) {
            bos.write(bytesIn, 0, read);
        }
    } catch (IOException e) {
        log.error("Unable to read an entry: " + e.getMessage(), e);
    } finally {
        //we must always close the zip file
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException e) {
                log.error("Error while closing the BufferedOutputStream: " + e.getMessage(), e);
            }
        }
    }
}

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

/**
 * @param file        Read file//from w ww  .  j  a  va 2 s . c om
 * @param msgCtx      Message Context
 * @param contentType content type
 * @param streaming   streaming mode (true/false)
 * @return return the status
 * @throws SynapseException
 */
@SuppressWarnings("ResultOfMethodCallIgnored")
public static boolean buildFile(FileObject file, MessageContext msgCtx, String contentType)
        throws SynapseException {
    ManagedDataSource dataSource = null;
    try {
        if (StringUtils.isEmpty(contentType) || StringUtils.isEmpty(contentType.trim())) {
            if (file.getName().getExtension().toLowerCase().endsWith("xml")) {
                contentType = "application/xml";
            } else if (file.getName().getExtension().toLowerCase().endsWith("txt")) {
                contentType = "text/plain";
            }
        } else {
            // Extract the charset encoding from the configured content type and
            // set the CHARACTER_SET_ENCODING property as e.g. SOAPBuilder relies on this.
            String charSetEnc = null;
            try {
                charSetEnc = new ContentType(contentType).getParameter("charset");
            } catch (ParseException ex) {
                log.warn("Invalid encoding type.", ex);
            }
            msgCtx.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc);
        }
        if (log.isDebugEnabled()) {
            log.debug("Processed file : " + file + " of Content-type : " + contentType);
        }
        org.apache.axis2.context.MessageContext axis2MsgCtx = ((org.apache.synapse.core.axis2.Axis2MessageContext) msgCtx)
                .getAxis2MessageContext();
        // Determine the message builder to use
        Builder builder;
        if (StringUtils.isEmpty(contentType)) {
            log.debug("No content type specified. Using RELAY builder.");
            builder = new BinaryRelayBuilder();
        } else {
            int index = contentType.indexOf(';');
            String type = index > 0 ? contentType.substring(0, index) : contentType;
            builder = BuilderUtil.getBuilderFromSelector(type, axis2MsgCtx);
            if (builder == null) {
                if (log.isDebugEnabled()) {
                    log.debug("No message builder found for type '" + type + "'. Falling back " + "to"
                            + " RELAY builder.");
                }
                builder = new BinaryRelayBuilder();
            }
        }

        // set the message payload to the message context
        InputStream in = null;
        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);
        }
        //We need this to build the complete message before closing the stream
        //noinspection ResultOfMethodCallIgnored
        documentElement.toString();
        msgCtx.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement));
    } 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.connector.util.ResultPayloadCreater.java

public static boolean buildFile(FileObject file, MessageContext msgCtx, String contentType, String streaming)
        throws SynapseException {
    ManagedDataSource dataSource = null;
    try {/*from   w  w w.j  a  v a2s . co m*/
        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) {
                log.warn("Invalid encoding type.", ex);
            }
            msgCtx.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc);
        }
        if (log.isDebugEnabled()) {
            log.debug("Processed file : " + file + " of Content-type : " + contentType);
        }
        org.apache.axis2.context.MessageContext axis2MsgCtx = ((org.apache.synapse.core.axis2.Axis2MessageContext) msgCtx)
                .getAxis2MessageContext();
        // Determine the message builder to use
        Builder builder;
        if (contentType == null) {
            log.debug("No content type specified. Using RELAY builder.");
            builder = new BinaryRelayBuilder();
        } else {
            int index = contentType.indexOf(';');
            String type = index > 0 ? contentType.substring(0, index) : contentType;
            builder = BuilderUtil.getBuilderFromSelector(type, axis2MsgCtx);
            if (builder == null) {
                if (log.isDebugEnabled()) {
                    log.debug(
                            "No message builder found for type '" + type + "'. Falling back to RELAY builder.");
                }
                builder = new BinaryRelayBuilder();
            }
        }

        // set the message payload to the message context
        InputStream in;
        if (builder instanceof DataSourceMessageBuilder && "true".equals(streaming)) {
            in = null;
            dataSource = ManagedDataSourceFactory.create(new FileObjectDataSource(file, contentType));
        } 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);
        }

        //We need this to build the complete message before closing the stream
        documentElement.toString();

        msgCtx.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement));

    } 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;
}