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:com.google.code.docbook4j.XslURIResolver.java

public Source resolve(String href, String base) throws TransformerException {

    log.debug("Resolving href={} for base={}", href, base);

    if (href == null || href.trim().length() == 0)
        return null;

    if (docbookXslBase == null && href.startsWith("res:") && href.endsWith("docbook.xsl")) {
        try {/*from   www  .j a  v a  2  s.co m*/
            docbookXslBase = FileObjectUtils.resolveFile(href).getParent().getURL().toExternalForm();
        } catch (FileSystemException e) {
            docbookXslBase = null;
        }
    }

    String normalizedBase = null;
    if (base != null) {
        try {
            normalizedBase = FileObjectUtils.resolveFile(base).getParent().getURL().toExternalForm();
        } catch (FileSystemException e) {
            normalizedBase = null;
        }
    }

    try {

        FileObject urlFileObject = FileObjectUtils.resolveFile(href, normalizedBase);

        if (!urlFileObject.exists())
            throw new FileSystemException("File object not found: " + urlFileObject);

        return new StreamSource(urlFileObject.getContent().getInputStream(),
                urlFileObject.getURL().toExternalForm());

    } catch (FileSystemException e) {

        // not exists for given base? try with docbook base...
        try {
            if (docbookXslBase != null) {
                FileObject urlFileObject = FileObjectUtils.resolveFile(href, docbookXslBase);
                return new StreamSource(urlFileObject.getContent().getInputStream(),
                        urlFileObject.getURL().toExternalForm());
            }

        } catch (FileSystemException e1) {
            // do nothing.
        }

        log.error("Error resolving href=" + href + " for base=" + base, e);
    }

    return null;

}

From source file:com.streamsets.pipeline.stage.origin.remote.FTPRemoteDownloadSourceDelegate.java

private long getModTime(FileObject fileObject) throws FileSystemException {
    long modTime = fileObject.getContent().getLastModifiedTime();
    if (supportsMDTM) {
        FtpClient ftpClient = null;/*ww  w  .j  a  va  2s . c o m*/
        FtpFileSystem ftpFileSystem = (FtpFileSystem) remoteDir.getFileSystem();
        try {
            ftpClient = ftpFileSystem.getClient();
            FTPClient rawFtpClient = (FTPClient) getFtpClient.invoke(ftpClient);
            String path = fileObject.getName().getPath();
            if (conf.userDirIsRoot && path.startsWith("/")) {
                // Remove the leading slash to turn it into a proper relative path
                path = path.substring(1);
            }
            FTPFile ftpFile = rawFtpClient.mdtmFile(path);
            if (ftpFile != null) {
                modTime = ftpFile.getTimestamp().getTimeInMillis();
            }
        } catch (Exception e) {
            LOG.trace("Ignoring Exception from MDTM command and falling back to basic timestamp", e);
        } finally {
            if (ftpClient != null) {
                ftpFileSystem.putClient(ftpClient);
            }
        }
    }
    return modTime;
}

From source file:com.google.code.docbook4j.renderer.BaseRenderer.java

protected Transformer createTransformer(FileObject xmlSource, FileObject xslStylesheet)
        throws TransformerConfigurationException, IOException {

    TransformerFactory transformerFactory = createTransformerFactory();
    if (xslStylesheet != null) {
        transformerFactory.setURIResolver(new XslURIResolver());
    }/*from  w w  w .j  a va2s  .c o  m*/
    FileObject xsl = xslStylesheet != null ? xslStylesheet : getDefaultXslStylesheet();

    Source source = new StreamSource(xsl.getContent().getInputStream(), xsl.getURL().toExternalForm());
    Transformer transformer = transformerFactory.newTransformer(source);

    transformer.setParameter("use.extensions", "1");
    transformer.setParameter("callout.graphics", "0");
    transformer.setParameter("callout.unicode", "1");
    transformer.setParameter("callouts.extension", "1");
    transformer.setParameter("base.dir", xmlSource.getParent().getURL().toExternalForm());

    for (Map.Entry<String, String> entry : this.params.entrySet()) {
        transformer.setParameter(entry.getKey(), entry.getValue());
    }

    return transformer;
}

From source file:hadoopInstaller.installation.UploadConfiguration.java

private String getLocalFileContents(String fileName) throws InstallationError {
    log.debug("HostInstallation.LoadingLocal", //$NON-NLS-1$
            fileName);/*from ww  w  .  j a  v  a2 s .c  om*/
    FileObject localFile;
    String localFileContents = new String();
    try {
        localFile = filesToUpload.resolveFile(fileName);
        if (localFile.exists()) {
            localFileContents = IOUtils.toString(localFile.getContent().getInputStream());
        }
    } catch (IOException e) {
        throw new InstallationError(e, "HostInstallation.CouldNotOpen", //$NON-NLS-1$
                fileName);
    }
    try {
        localFile.close();
    } catch (FileSystemException e) {
        log.warn("HostInstallation.CouldNotClose", //$NON-NLS-1$
                localFile.getName().getURI());
    }
    log.debug("HostInstallation.LoadedLocal", //$NON-NLS-1$
            fileName);
    return localFileContents;
}

From source file:com.streamsets.pipeline.lib.remote.TestFTPRemoteFile.java

@Test
public void testCreateAndCommitOutputStream() throws Exception {
    String name = "file.txt";
    String filePath = "/some/path/";
    FileObject fileObject = Mockito.mock(FileObject.class);
    FileName fileName = Mockito.mock(FileName.class);
    Mockito.when(fileObject.getName()).thenReturn(fileName);
    Mockito.when(fileName.getBaseName()).thenReturn(name);
    FileObject parentFileObject = Mockito.mock(FileObject.class);
    FileObject tempFileObject = Mockito.mock(FileObject.class);
    Mockito.when(fileObject.getParent()).thenReturn(parentFileObject);
    Mockito.when(parentFileObject.resolveFile(Mockito.any())).thenReturn(tempFileObject);
    FileContent tempFileContent = Mockito.mock(FileContent.class);
    Mockito.when(tempFileObject.getContent()).thenReturn(tempFileContent);

    FTPRemoteFile file = new FTPRemoteFile(filePath + name, 0L, fileObject);

    try {/*  ww  w  . ja v a 2  s  .c  o m*/
        file.commitOutputStream();
        Assert.fail("Expected IOException because called commitOutputStream before createOutputStream");
    } catch (IOException ioe) {
        Assert.assertEquals("Cannot commit " + filePath + name + " - it must be written first",
                ioe.getMessage());
    }

    file.createOutputStream();
    Mockito.verify(parentFileObject).resolveFile("_tmp_" + name);
    Mockito.verify(tempFileContent).getOutputStream();

    file.commitOutputStream();
    Mockito.verify(tempFileObject).moveTo(fileObject);
}

From source file:com.google.code.docbook4j.renderer.BaseRenderer.java

public InputStream render() throws Docbook4JException {

    assertNotNull(xmlResource, "Value of the xml source should be not null!");

    FileObject xsltResult = null;
    FileObject xmlSourceFileObject = null;
    FileObject xslSourceFileObject = null;
    FileObject userConfigXmlSourceFileObject = null;

    try {/* w ww  . j a  v  a2 s .com*/

        xmlSourceFileObject = FileObjectUtils.resolveFile(xmlResource);
        if (xslResource != null) {
            xslSourceFileObject = FileObjectUtils.resolveFile(xslResource);
        } else {
            xslSourceFileObject = getDefaultXslStylesheet();
        }

        if (userConfigXmlResource != null) {
            userConfigXmlSourceFileObject = FileObjectUtils.resolveFile(userConfigXmlResource);
        }

        SAXParserFactory factory = createParserFactory();
        final XMLReader reader = factory.newSAXParser().getXMLReader();

        EntityResolver resolver = new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {

                log.debug("Resolving file {}", systemId);

                FileObject inc = FileObjectUtils.resolveFile(systemId);
                return new InputSource(inc.getContent().getInputStream());
            }
        };

        // prepare xml sax source
        ExpressionEvaluatingXMLReader piReader = new ExpressionEvaluatingXMLReader(reader, vars);
        piReader.setEntityResolver(resolver);

        SAXSource source = new SAXSource(piReader,
                new InputSource(xmlSourceFileObject.getContent().getInputStream()));
        source.setSystemId(xmlSourceFileObject.getURL().toExternalForm());

        // prepare xslt result
        xsltResult = FileObjectUtils.resolveFile("tmp://" + UUID.randomUUID().toString());
        xsltResult.createFile();

        // create transofrmer and do transformation
        final Transformer transformer = createTransformer(xmlSourceFileObject, xslSourceFileObject);
        transformer.transform(source, new StreamResult(xsltResult.getContent().getOutputStream()));

        // do post processing
        FileObject target = postProcess(xmlSourceFileObject, xslSourceFileObject, xsltResult,
                userConfigXmlSourceFileObject);

        FileObjectUtils.closeFileObjectQuietly(xsltResult);
        FileObjectUtils.closeFileObjectQuietly(target);
        return target.getContent().getInputStream();

    } catch (FileSystemException e) {
        throw new Docbook4JException("Error transofrming xml!", e);
    } catch (SAXException e) {
        throw new Docbook4JException("Error transofrming xml!", e);
    } catch (ParserConfigurationException e) {
        throw new Docbook4JException("Error transofrming xml!", e);
    } catch (TransformerException e) {
        throw new Docbook4JException("Error transofrming xml!", e);
    } catch (IOException e) {
        throw new Docbook4JException("Error transofrming xml !", e);
    } finally {
        FileObjectUtils.closeFileObjectQuietly(xmlSourceFileObject);
        FileObjectUtils.closeFileObjectQuietly(xslSourceFileObject);
    }

}

From source file:com.mirth.connect.util.MessageImporter.java

private void importVfsFile(FileObject file, MessageWriter messageWriter, int[] result)
        throws InterruptedException, MessageImportException {
    InputStream inputStream = null;

    try {/*from  www  .j ava2  s .  c o  m*/
        inputStream = file.getContent().getInputStream();

        // scan the first XML_SCAN_BUFFER_SIZE bytes in the file to see if it contains message xml
        char[] cbuf = new char[XML_SCAN_BUFFER_SIZE];
        new InputStreamReader(inputStream, CHARSET).read(cbuf);

        if (StringUtils.contains(new String(cbuf), OPEN_ELEMENT)) {
            logger.debug("Importing file: " + file.getName().getURI());

            // re-open the input stream to reposition it at the beginning of the stream
            inputStream.close();
            inputStream = file.getContent().getInputStream();
            importMessagesFromInputStream(inputStream, messageWriter, result);
        }
    } catch (IOException e) {
        throw new MessageImportException(e);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:maspack.fileutil.MultiFileTransferMonitor.java

private long getFileSize(FileObject file) {
    long size = -1;
    try {/*from www.  j av  a2  s  . c  om*/
        size = file.getContent().getSize();
    } catch (FileSystemException e) {
        size = -1;
    }
    return size;
}

From source file:com.google.code.docbook4j.renderer.FORenderer.java

protected Configuration createFOPConfig(final FileObject userConfigXml)
        throws IOException, SAXException, ConfigurationException {
    if (userConfigXml == null) {
        return null;
    }// w ww.j  a v a2 s  .  co m
    DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder();
    Configuration cfg = cfgBuilder.build(userConfigXml.getContent().getInputStream());
    return cfg;
}

From source file:maspack.fileutil.FileTransferMonitorAgent.java

/**
 * @param fm FileTransferMonitor associated with this agent
 * @param dest Transfer destination/*from   ww  w .  jav a 2  s . co  m*/
 * @param source Transfer source
 * @param displayName Name associated with file transfer
 */
public FileTransferMonitorAgent(FileTransferMonitor fm, FileObject dest, FileObject source,
        String displayName) {
    this(fm, dest, source, -1, displayName);
    try {
        sourceSize = source.getContent().getSize();
    } catch (FileSystemException e) {
        sourceSize = -1;
    }
}