Example usage for org.apache.commons.vfs2 FileContent getInputStream

List of usage examples for org.apache.commons.vfs2 FileContent getInputStream

Introduction

In this page you can find the example usage for org.apache.commons.vfs2 FileContent getInputStream.

Prototype

InputStream getInputStream() throws FileSystemException;

Source Link

Document

Returns an input stream for reading the file's content.

Usage

From source file:org.pentaho.platform.repository.solution.filebased.FileObjectTestHelper.java

public static FileObject mockFile(final String contents, final boolean exists) throws FileSystemException {
    FileObject fileObject = mock(FileObject.class);
    when(fileObject.exists()).thenReturn(exists);
    FileContent fileContent = mock(FileContent.class);
    when(fileObject.getContent()).thenReturn(fileContent);
    when(fileContent.getInputStream()).thenReturn(IOUtils.toInputStream(contents));
    final FileObject parent = mock(FileObject.class);
    when(fileObject.getParent()).thenReturn(parent);
    final FileName fileName = mock(FileName.class);
    when(parent.getName()).thenReturn(fileName);
    when(fileName.getURI()).thenReturn("mondrian:/catalog");
    return fileObject;
}

From source file:org.pentaho.platform.repository.solution.filebased.SolutionRepositoryVfsFileObjectTest.java

@Test
@SuppressWarnings({ "checkstyle:onestatementperline",
        "multiple statements help understand the mock definition" })
public void testContentRelatedMethods(@mockit.Mocked final RepositoryFile mockRepoFile,
        @mockit.Mocked final IAclNodeHelper mockAclHelper,
        @mockit.Mocked final IUnifiedRepository mockUnifiedRepository,
        @mockit.Mocked final SimpleRepositoryFileData mockFileData) throws FileSystemException {
    String fileRef = "/etc/mondrian/SteelWheels/schema.xml";
    new mockit.NonStrictExpectations() {
        //CHECKSTYLE IGNORE check FOR NEXT 6 LINES
        {/* w w  w . j av a 2  s. c  o  m*/
            mockUnifiedRepository.getFile(anyString);
            result = mockRepoFile;
            mockUnifiedRepository.getDataForRead((Serializable) any, (Class) any);
            result = mockFileData;
            mockAclHelper.canAccess(mockRepoFile, EnumSet.of(RepositoryFilePermission.READ));
            result = true;
            mockFileData.getStream();
            result = new ByteArrayInputStream("some string".getBytes());
        }
    };
    Deencapsulation.setField(SolutionRepositoryVfsFileObject.class, "repository", mockUnifiedRepository);
    SolutionRepositoryVfsFileObject solutionRepositoryVfsFileObject = new SolutionRepositoryVfsFileObject(
            fileRef);
    Deencapsulation.setField(solutionRepositoryVfsFileObject, "aclHelper", mockAclHelper);
    FileContent someFileContent = solutionRepositoryVfsFileObject.getContent();
    assertThat(someFileContent, is(notNullValue()));
    assertThat(solutionRepositoryVfsFileObject.isContentOpen(), is(false));
    someFileContent.getInputStream();
    assertThat(solutionRepositoryVfsFileObject.isContentOpen(), is(true));
    someFileContent.close();
    assertThat(solutionRepositoryVfsFileObject.isContentOpen(), is(false));

    someFileContent = solutionRepositoryVfsFileObject.getContent();
    someFileContent.getInputStream();
    assertThat(solutionRepositoryVfsFileObject.isContentOpen(), is(true));
    solutionRepositoryVfsFileObject.close();
    assertThat(solutionRepositoryVfsFileObject.isContentOpen(), is(false));
}

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

/**
 * Actual processing of the file/folder/* w  w w.j a  va  2 s  .  com*/
 *
 * @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:pl.otros.logview.api.io.Utils.java

public static LoadingInfo openFileObject(FileObject fileObject, boolean tailing) throws Exception {
    LoadingInfo loadingInfo = new LoadingInfo();
    loadingInfo.setFileObject(fileObject);
    loadingInfo.setFriendlyUrl(fileObject.getName().getFriendlyURI());

    final FileContent content = fileObject.getContent();
    InputStream httpInputStream = content.getInputStream();
    byte[] buff = Utils.loadProbe(httpInputStream, 10000);

    loadingInfo.setGziped(checkIfIsGzipped(buff, buff.length));

    ByteArrayInputStream bin = new ByteArrayInputStream(buff);

    SequenceInputStream sequenceInputStream = new SequenceInputStream(bin, httpInputStream);

    ObservableInputStreamImpl observableInputStreamImpl = new ObservableInputStreamImpl(sequenceInputStream);

    if (loadingInfo.isGziped()) {
        loadingInfo.setContentInputStream(new GZIPInputStream(observableInputStreamImpl));
        loadingInfo.setInputStreamBufferedStart(ungzip(buff));
    } else {//from w  ww .ja va 2s  .  c  om
        loadingInfo.setContentInputStream(observableInputStreamImpl);
        loadingInfo.setInputStreamBufferedStart(buff);
    }
    loadingInfo.setObserableInputStreamImpl(observableInputStreamImpl);

    loadingInfo.setTailing(tailing);
    if (fileObject.getType().hasContent()) {
        loadingInfo.setLastFileSize(content.getSize());
    }
    return loadingInfo;

}

From source file:pl.otros.vfs.browser.util.VFSUtils.java

private static FileObject[] extractHttpFileObjectChildren(FileObject fileObject) throws FileSystemException {
    FileObject[] result;// w w  w.  j av a 2  s  .  co m
    HttpFileObject fo = (HttpFileObject) fileObject;
    FileContent content = fo.getContent();
    String contentType = content.getContentInfo().getContentType();
    result = new FileObject[] { fileObject };
    if (contentType.equalsIgnoreCase("text/html")) {
        try {
            String html = IOUtils.toString(content.getInputStream());
            if (html.toLowerCase().contains("index of")) {
                LOGGER.info("Page contains \"index of\", resolving children");
                //a href="DSC_0410.JPG">
                Pattern p = Pattern.compile("<A .*?href=\"(.*?)\"", Pattern.CASE_INSENSITIVE);
                Matcher matcher = p.matcher(html);
                ArrayList<FileObject> list = new ArrayList<FileObject>();
                while (matcher.find()) {
                    String link = matcher.group(1);
                    LOGGER.info("Getting children from link {}", link);
                    if (StringUtils.isBlank(link)) {
                        LOGGER.debug("URL link is blank");
                        continue;
                    }
                    FileObject child;
                    URL url = fileObject.getURL();
                    child = extractHttpFileObject(link, url);
                    list.add(child);
                }
                result = list.toArray(result);
            }
            //TODO extract links
        } catch (Exception e) {
            throw new FileSystemException(e);
        }
    }
    return result;
}

From source file:tain.kr.test.vfs.v01.TestVfs2FilehandleService.java

@Test
public void testAccessFile() throws Exception {

    FileSystemManager manager = VFS.getManager();

    FileObject baseDir = manager.resolveFile(this.absoluteFilePath);
    FileObject file = manager.resolveFile(baseDir, "testfolder/file1.txt");

    //   //from  w  ww  . j ava 2  s  .  c  o m
    file.delete(Selectors.SELECT_FILES);
    assertFalse(file.exists());

    //  
    file.createFile();
    assertTrue(file.exists());

    FileContent fileContent = file.getContent();
    assertEquals(0, fileContent.getSize());

    //  
    String string = "test.";
    OutputStream os = fileContent.getOutputStream();

    try {
        os.write(string.getBytes());
        os.flush();
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (Exception ignore) {
                // no-op
            }
        }
    }
    assertNotSame(0, fileContent.getSize());

    //  
    StringBuffer sb = new StringBuffer();
    FileObject writtenFile = manager.resolveFile(baseDir, "testfolder/file1.txt");
    FileContent writtenContents = writtenFile.getContent();
    InputStream is = writtenContents.getInputStream();

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));

        String line = "";
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (Exception ignore) {
                // no-op
            }
        }
    }

    //  
    assertEquals(sb.toString(), string);
}