Java Code Examples for org.apache.commons.vfs2.FileContent

The following examples show how to use org.apache.commons.vfs2.FileContent. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: hop   Source File: TextFileInputTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testClose() throws Exception {

  TextFileInputMeta mockTFIM = createMetaObject( null );
  String virtualFile = createVirtualFile( "pdi-17267.txt", null );
  TextFileInputData mockTFID = createDataObject( virtualFile, ";", null );
  mockTFID.lineBuffer = new ArrayList<>();
  mockTFID.lineBuffer.add( new TextFileLine( null, 0l, null ) );
  mockTFID.lineBuffer.add( new TextFileLine( null, 0l, null ) );
  mockTFID.lineBuffer.add( new TextFileLine( null, 0l, null ) );
  mockTFID.filename = "";

  FileContent mockFileContent = mock( FileContent.class );
  InputStream mockInputStream = mock( InputStream.class );
  when( mockFileContent.getInputStream() ).thenReturn( mockInputStream );
  FileObject mockFO = mock( FileObject.class );
  when( mockFO.getContent() ).thenReturn( mockFileContent );

  TextFileInputReader tFIR = new TextFileInputReader( mock( IBaseFileInputTransformControl.class ),
    mockTFIM, mockTFID, mockFO, mock( LogChannelInterface.class ) );

  assertEquals( 3, mockTFID.lineBuffer.size() );
  tFIR.close();
  // After closing the file, the buffer must be empty!
  assertEquals( 0, mockTFID.lineBuffer.size() );
}
 
Example 2
Source Project: hop   Source File: TextFileInputTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testClose() throws Exception {

  TextFileInputMeta mockTFIM = createMetaObject( null );
  String virtualFile = createVirtualFile( "pdi-17267.txt", null );
  TextFileInputData mockTFID = createDataObject( virtualFile, ";", null );
  mockTFID.lineBuffer = new ArrayList<>();
  mockTFID.lineBuffer.add( new TextFileLine( null, 0l, null ) );
  mockTFID.lineBuffer.add( new TextFileLine( null, 0l, null ) );
  mockTFID.lineBuffer.add( new TextFileLine( null, 0l, null ) );
  mockTFID.filename = "";

  FileContent mockFileContent = mock( FileContent.class );
  InputStream mockInputStream = mock( InputStream.class );
  when( mockFileContent.getInputStream() ).thenReturn( mockInputStream );
  FileObject mockFO = mock( FileObject.class );
  when( mockFO.getContent() ).thenReturn( mockFileContent );

  TextFileInputReader tFIR = new TextFileInputReader( mock( IBaseFileInputTransformControl.class ),
    mockTFIM, mockTFID, mockFO, mock( ILogChannel.class ) );

  assertEquals( 3, mockTFID.lineBuffer.size() );
  tFIR.close();
  // After closing the file, the buffer must be empty!
  assertEquals( 0, mockTFID.lineBuffer.size() );
}
 
Example 3
Source Project: zeppelin   Source File: OldVFSNotebookRepo.java    License: Apache License 2.0 6 votes vote down vote up
private Note getNote(FileObject noteDir) throws IOException {
  if (!isDirectory(noteDir)) {
    throw new IOException(noteDir.getName().toString() + " is not a directory");
  }

  FileObject noteJson = noteDir.resolveFile("note.json", NameScope.CHILD);
  if (!noteJson.exists()) {
    throw new IOException(noteJson.getName().toString() + " not found");
  }
  
  FileContent content = noteJson.getContent();
  InputStream ins = content.getInputStream();
  String json = IOUtils.toString(ins, conf.getString(ConfVars.ZEPPELIN_ENCODING));
  ins.close();

  return Note.fromJson(json);
}
 
Example 4
Source Project: ant-ivy   Source File: VfsRepository.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Transfer a VFS Resource from the repository to the local file system.
 *
 * @param srcVfsURI
 *            a <code>String</code> identifying the VFS resource to be fetched
 * @param destination
 *            a <code>File</code> identifying the destination file
 * @throws IOException on failure
 * @see "Supported File Systems in the jakarta-commons-vfs documentation"
 */
public void get(String srcVfsURI, File destination) throws IOException {
    VfsResource src = new VfsResource(srcVfsURI, getVFSManager());
    fireTransferInitiated(src, TransferEvent.REQUEST_GET);
    try {
        FileContent content = src.getContent();
        if (content == null) {
            throw new IllegalArgumentException("invalid vfs uri " + srcVfsURI
                    + ": no content found");
        }
        FileUtil.copy(content.getInputStream(), destination, progress);
    } catch (IOException | RuntimeException ex) {
        fireTransferError(ex);
        throw ex;
    }
}
 
Example 5
Source Project: commons-vfs   Source File: WebdavFileContentInfoFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public FileContentInfo create(final FileContent fileContent) throws FileSystemException {
    final WebdavFileObject file = (WebdavFileObject) FileObjectUtils.getAbstractFileObject(fileContent.getFile());

    String contentType = null;
    String contentEncoding = null;

    final DavPropertyNameSet nameSet = new DavPropertyNameSet();
    nameSet.add(DavPropertyName.GETCONTENTTYPE);
    final DavPropertySet propertySet = file.getProperties((URLFileName) file.getName(), nameSet, true);

    DavProperty property = propertySet.get(DavPropertyName.GETCONTENTTYPE);
    if (property != null) {
        contentType = (String) property.getValue();
    }
    property = propertySet.get(WebdavFileObject.RESPONSE_CHARSET);
    if (property != null) {
        contentEncoding = (String) property.getValue();
    }

    return new DefaultFileContentInfo(contentType, contentEncoding);
}
 
Example 6
Source Project: commons-vfs   Source File: Http5FileContentInfoFactory.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public FileContentInfo create(final FileContent fileContent) throws FileSystemException {
    String contentMimeType = null;
    String contentCharset = null;

    try (final Http5FileObject<Http5FileSystem> http4File = (Http5FileObject<Http5FileSystem>) FileObjectUtils
            .getAbstractFileObject(fileContent.getFile())) {
        final HttpResponse lastHeadResponse = http4File.getLastHeadResponse();

        final Header header = lastHeadResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE);

        if (header != null) {
            final ContentType contentType = ContentType.parse(header.getValue());
            contentMimeType = contentType.getMimeType();

            if (contentType.getCharset() != null) {
                contentCharset = contentType.getCharset().name();
            }
        }

        return new DefaultFileContentInfo(contentMimeType, contentCharset);
    } catch (final IOException e) {
        throw new FileSystemException(e);
    }
}
 
Example 7
Source Project: commons-vfs   Source File: HttpFileContentInfoFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public FileContentInfo create(final FileContent fileContent) throws FileSystemException {

    String contentType = null;
    String contentEncoding = null;

    HeadMethod headMethod;
    try (final HttpFileObject<HttpFileSystem> httpFile = (HttpFileObject<HttpFileSystem>) FileObjectUtils
            .getAbstractFileObject(fileContent.getFile())) {
        headMethod = httpFile.getHeadMethod();
    } catch (final IOException e) {
        throw new FileSystemException(e);
    }
    final Header header = headMethod.getResponseHeader("content-type");
    if (header != null) {
        final HeaderElement[] element = header.getElements();
        if (element != null && element.length > 0) {
            contentType = element[0].getName();
        }
    }

    contentEncoding = headMethod.getResponseCharSet();

    return new DefaultFileContentInfo(contentType, contentEncoding);
}
 
Example 8
Source Project: commons-vfs   Source File: Http4FileContentInfoFactory.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public FileContentInfo create(final FileContent fileContent) throws FileSystemException {
    String contentMimeType = null;
    String contentCharset = null;

    try (final Http4FileObject<Http4FileSystem> http4File = (Http4FileObject<Http4FileSystem>) FileObjectUtils
            .getAbstractFileObject(fileContent.getFile())) {
        final HttpResponse lastHeadResponse = http4File.getLastHeadResponse();

        final Header header = lastHeadResponse.getFirstHeader(HTTP.CONTENT_TYPE);

        if (header != null) {
            final ContentType contentType = ContentType.parse(header.getValue());
            contentMimeType = contentType.getMimeType();

            if (contentType.getCharset() != null) {
                contentCharset = contentType.getCharset().name();
            }
        }

        return new DefaultFileContentInfo(contentMimeType, contentCharset);
    } catch (final IOException e) {
        throw new FileSystemException(e);
    }
}
 
Example 9
@Override
public FileContentInfo create(final FileContent fileContent) {
    String contentType = null;

    final String name = fileContent.getFile().getName().getBaseName();
    if (name != null) {
        final FileNameMap fileNameMap = URLConnection.getFileNameMap();
        contentType = fileNameMap.getContentTypeFor(name);
    }

    // optimize object creation for common case
    if (contentType == null) {
        return NULL_INFO;
    } else {
        return new DefaultFileContentInfo(contentType, null);
    }
}
 
Example 10
Source Project: commons-vfs   Source File: FileTypeMap.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Find the scheme for the provider of a layered file system.
 * <p>
 * This will check the FileContentInfo or file extension.
 * </p>
 *
 * @return Scheme supporting the file type or null (if unknonw).
 */
public String getScheme(final FileObject file) throws FileSystemException {
    // Check the file's mime type for a match
    final FileContent content = file.getContent();
    final String mimeType = content.getContentInfo().getContentType();
    if (mimeType != null) {
        return mimeTypeMap.get(mimeType);
    }

    // no specific mime-type - if it is a file also check the extension
    if (!file.isFile()) {
        return null; // VFS-490 folders don't use extensions for mime-type
    }
    final String extension = file.getName().getExtension();
    return extensionMap.get(extension);
}
 
Example 11
Source Project: commons-vfs   Source File: EmptyFileFilter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Checks to see if the file is empty. A non-existing file is also considered empty.
 *
 * @param fileInfo the file or directory to check
 *
 * @return {@code true} if the file or directory is <i>empty</i>, otherwise {@code false}.
 * @throws FileSystemException Thrown for file system errors.
 */
@Override
public boolean accept(final FileSelectInfo fileInfo) throws FileSystemException {
    try (final FileObject file = fileInfo.getFile()) {
        if (!file.exists()) {
            return true;
        }
        if (file.getType() == FileType.FOLDER) {
            final FileObject[] files = file.getChildren();
            return files == null || files.length == 0;
        }
        try (final FileContent content = file.getContent();) {
            return content.isEmpty();
        }
    }
}
 
Example 12
Source Project: commons-vfs   Source File: Bzip2TestCase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBZip2() throws IOException {
    final File testResource = getTestResource("bla.txt.bz2");
    try (final FileObject bz2FileObject = VFS.getManager().resolveFile("bz2://" + testResource)) {
        Assert.assertTrue(bz2FileObject.exists());
        Assert.assertTrue(bz2FileObject.isFolder());
        try (final FileObject fileObjectDir = bz2FileObject.resolveFile("bla.txt")) {
            Assert.assertTrue(fileObjectDir.exists());
            Assert.assertTrue(bz2FileObject.isFolder());
            try (final FileObject fileObject = fileObjectDir.resolveFile("bla.txt")) {
                Assert.assertTrue(fileObject.exists());
                Assert.assertFalse(fileObject.isFolder());
                Assert.assertTrue(fileObject.isFile());
                try (final FileContent content = fileObject.getContent()) {
                    Assert.assertEquals(CompressedFileFileObject.SIZE_UNDEFINED, content.getSize());
                    // blows up, Commons Compress?
                    final String string = content.getString(StandardCharsets.UTF_8);
                    Assert.assertEquals(26, string.length());
                    Assert.assertEquals("Hallo, dies ist ein Test.\n", string);
                }
            }
        }
    }
}
 
Example 13
Source Project: commons-vfs   Source File: Webdav4FileContentInfoFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public FileContentInfo create(final FileContent fileContent) throws FileSystemException {
    final Webdav4FileObject file = (Webdav4FileObject) FileObjectUtils.getAbstractFileObject(fileContent.getFile());

    String contentType = null;
    String contentEncoding = null;

    final DavPropertyNameSet nameSet = new DavPropertyNameSet();
    nameSet.add(DavPropertyName.GETCONTENTTYPE);
    final DavPropertySet propertySet = file.getProperties((GenericURLFileName) file.getName(), nameSet, true);

    DavProperty property = propertySet.get(DavPropertyName.GETCONTENTTYPE);
    if (property != null) {
        contentType = (String) property.getValue();
    }
    property = propertySet.get(Webdav4FileObject.RESPONSE_CHARSET);
    if (property != null) {
        contentEncoding = (String) property.getValue();
    }

    return new DefaultFileContentInfo(contentType, contentEncoding);
}
 
Example 14
Source Project: pentaho-kettle   Source File: TextFileInputTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testClose() throws Exception {

  TextFileInputMeta mockTFIM = createMetaObject( null );
  String virtualFile = createVirtualFile( "pdi-17267.txt", null );
  TextFileInputData mockTFID = createDataObject( virtualFile, ";", null );
  mockTFID.lineBuffer = new ArrayList<>();
  mockTFID.lineBuffer.add( new TextFileLine( null, 0l, null ) );
  mockTFID.lineBuffer.add( new TextFileLine( null, 0l, null ) );
  mockTFID.lineBuffer.add( new TextFileLine( null, 0l, null ) );
  mockTFID.filename = "";

  FileContent mockFileContent = mock( FileContent.class );
  InputStream mockInputStream = mock( InputStream.class );
  when( mockFileContent.getInputStream() ).thenReturn( mockInputStream );
  FileObject mockFO = mock( FileObject.class );
  when( mockFO.getContent() ).thenReturn( mockFileContent );

  TextFileInputReader tFIR = new TextFileInputReader( mock( IBaseFileInputStepControl.class ),
    mockTFIM, mockTFID, mockFO, mock( LogChannelInterface.class ) );

  assertEquals( 3, mockTFID.lineBuffer.size() );
  tFIR.close();
  // After closing the file, the buffer must be empty!
  assertEquals( 0, mockTFID.lineBuffer.size() );
}
 
Example 15
Source Project: hop   Source File: HopVfsFileDialog.java    License: Apache License 2.0 5 votes vote down vote up
private void showFilename( FileObject fileObject ) {
  try {
    wFilename.setText( HopVfs.getFilename( fileObject ) );

    FileContent content = fileObject.getContent();

    String details = "";

    if ( fileObject.isFolder() ) {
      details += "Folder: " + HopVfs.getFilename( fileObject ) + Const.CR;
    } else {
      details += "Name: " + fileObject.getName().getBaseName() + "   ";
      details += "Folder: " + HopVfs.getFilename( fileObject.getParent() ) + "   ";
      details += "Size: " + content.getSize();
      if ( content.getSize() >= 1024 ) {
        details += " (" + getFileSize( fileObject ) + ")";
      }
      details += Const.CR;
    }
    details += "Last modified: " + getFileDate( fileObject ) + Const.CR;
    details += "Readable: " + (fileObject.isReadable()?"Yes":"No") + "  ";
    details += "Writable: " + (fileObject.isWriteable()?"Yes":"No") + "  ";
    details += "Executable: " + (fileObject.isExecutable()?"Yes":"No") + Const.CR;
    if ( fileObject.isSymbolicLink() ) {
      details += "This is a symbolic link" + Const.CR;
    }
    Map<String, Object> attributes = content.getAttributes();
    if ( attributes != null && !attributes.isEmpty() ) {
      details += "Attributes: " + Const.CR;
      for ( String key : attributes.keySet() ) {
        Object value = attributes.get( key );
        details += "   " + key + " : " + ( value == null ? "" : value.toString() ) + Const.CR;
      }
    }
    showDetails( details );
  } catch ( Throwable e ) {
    showError( "Error getting information on file " + fileObject.toString(), e );
  }
}
 
Example 16
Source Project: hop   Source File: HopVfs.java    License: Apache License 2.0 5 votes vote down vote up
public static OutputStream getOutputStream( FileObject fileObject, boolean append ) throws IOException {
  FileObject parent = fileObject.getParent();
  if ( parent != null ) {
    if ( !parent.exists() ) {
      throw new IOException( BaseMessages.getString(
        PKG, "HopVFS.Exception.ParentDirectoryDoesNotExist", getFriendlyURI( parent ) ) );
    }
  }
  try {
    fileObject.createFile();
    FileContent content = fileObject.getContent();
    return content.getOutputStream( append );
  } catch ( FileSystemException e ) {
    // Perhaps if it's a local file, we can retry using the standard
    // File object. This is because on Windows there is a bug in VFS.
    //
    if ( fileObject instanceof LocalFile ) {
      try {
        String filename = getFilename( fileObject );
        return new FileOutputStream( new File( filename ), append );
      } catch ( Exception e2 ) {
        throw e; // throw the original exception: hide the retry.
      }
    } else {
      throw e;
    }
  }
}
 
Example 17
Source Project: obevo   Source File: FileObject.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public FileContent getContent() {
    try {
        return this.fileObject.getContent();
    } catch (FileSystemException e) {
        throw new VFSFileSystemException(e);
    }
}
 
Example 18
Source Project: datacollector   Source File: TestFTPRemoteFile.java    License: Apache License 2.0 5 votes vote down vote up
@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 {
    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);
}
 
Example 19
Source Project: bluima   Source File: PubmedArchiveCollectionReader.java    License: Apache License 2.0 5 votes vote down vote up
private NextArticle getNextArticle() throws IOException {

		while (directoryIterator.hasNext()) {
			File f = directoryIterator.next();
			LOG.debug("extracting " + f.getAbsolutePath());

			try {
				FileObject archive = fsManager.resolveFile("tgz:file://"
						+ f.getAbsolutePath());

				// List the children of the archive file
				FileObject[] children = archive.getChildren()[0].getChildren();
				for (int i = 0; i < children.length; i++) {
					FileObject fo = children[i];
					if (fo.isReadable() && fo.getType() == FileType.FILE
							&& fo.getName().getExtension().equals("nxml")) {
						FileContent fc = fo.getContent();
						Article article = archiveArticleParser.parse(fc
								.getInputStream());

						NextArticle nextArticle = new NextArticle();
						nextArticle.article = article;
						nextArticle.file = f.getAbsolutePath();

						return nextArticle;
					}
				}
			} catch (Exception e) {
				LOG.error("Error extracting " + f.getAbsolutePath() + ", " + e);
			}
		}
		return null;
	}
 
Example 20
Source Project: bluima   Source File: PubmedCentralCollectionReader.java    License: Apache License 2.0 5 votes vote down vote up
private NextArticle getNextArticle() throws IOException {

        while (directoryIterator.hasNext()) {
            File f = directoryIterator.next();
            // LOG.debug("extracting " + f.getAbsolutePath());

            try {
                FileObject archive = fsManager.resolveFile("tgz:file://"
                        + f.getAbsolutePath());

                // List the children of the archive file
                FileObject[] children = archive.getChildren()[0].getChildren();
                for (int i = 0; i < children.length; i++) {
                    FileObject fo = children[i];
                    if (fo.isReadable() && fo.getType() == FileType.FILE
                            && fo.getName().getExtension().equals("nxml")) {
                        FileContent fc = fo.getContent();
                        Article article = archiveArticleParser.parse(fc
                                .getInputStream());

                        NextArticle nextArticle = new NextArticle();
                        nextArticle.article = article;
                        nextArticle.file = f.getAbsolutePath();

                        return nextArticle;
                    }
                }
            } catch (Exception e) {
                LOG.error("Error extracting " + f.getAbsolutePath() + ", " + e);
            }
        }
        return null;
    }
 
Example 21
Source Project: bluima   Source File: PubmedArchiveCollectionReader2.java    License: Apache License 2.0 5 votes vote down vote up
public boolean hasNext() throws IOException, CollectionException {
    if (articlesIt != null && articlesIt.hasNext()) {
        return true;
    } else {
        if (super.hasNext()) {
            // try to fetch
            File f = fileIterator.next();
            FileObject archive = fsManager.resolveFile("gz:file://"
                    + f.getAbsolutePath());
            FileObject fo = archive.getChildren()[0];
            LOG.debug("extracted file {} from archive {}", fo.getName(),
                    f.getName());
            if (fo.isReadable() && fo.getType() == FileType.FILE) {
                FileContent fc = fo.getContent();
                List<MedlineCitation> articles = xmlArticleParser
                        .parseAsArticles(fc.getInputStream());
                articlesIt = articles.iterator();
                if (articlesIt.hasNext()) {
                    return true;
                } else { // empty, try next file
                    return hasNext();
                }
            }
        }
    }
    return false;
}
 
Example 22
@Before
public void setUp() throws Exception {
  fileObject = mock( FileObject.class );
  childFile1 = mock( FileObject.class );
  childFile2 = mock( FileObject.class );
  childFile3 = mock( FileObject.class );
  childFileName1 = mock( FileName.class );
  childFileName2 = mock( FileName.class );
  childFileName3 = mock( FileName.class );
  childFileContent1 = mock( FileContent.class );
  childFileContent2 = mock( FileContent.class );
  childFileContent3 = mock( FileContent.class );
}
 
Example 23
Source Project: commons-vfs   Source File: ShowFileTask.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Logs the details of a file.
 */
private void showFile(final FileObject file, final String prefix) throws Exception {
    // Write details
    final StringBuilder msg = new StringBuilder(prefix);
    msg.append(file.getName().getBaseName());
    if (file.exists()) {
        msg.append(" (");
        msg.append(file.getType().getName());
        msg.append(")");
    } else {
        msg.append(" (unknown)");
    }
    log(msg.toString());

    if (file.exists()) {
        final String newPrefix = prefix + INDENT;
        if (file.getType().hasContent()) {
            try (final FileContent content = file.getContent()) {
                log(newPrefix + "Content-Length: " + content.getSize());
                log(newPrefix + "Last-Modified" + new Date(content.getLastModifiedTime()));
            }
            if (showContent) {
                log(newPrefix + "Content:");
                logContent(file, newPrefix);
            }
        }
        if (file.getType().hasChildren()) {
            final FileObject[] children = file.getChildren();
            for (final FileObject child : children) {
                if (recursive) {
                    showFile(child, newPrefix);
                } else {
                    log(newPrefix + child.getName().getBaseName());
                }
            }
        }
    }
}
 
Example 24
Source Project: commons-vfs   Source File: JarURLConnectionImpl.java    License: Apache License 2.0 5 votes vote down vote up
public JarURLConnectionImpl(final JarFileObject file, final FileContent content)
        throws MalformedURLException, FileSystemException {
    // This is because JarURLConnection SUCKS!!
    super(new URL(HACK_URL));

    this.url = file.getURL();
    this.content = content;
    this.parentURL = file.getURL();
    this.entryName = file.getName().getPath();
    this.file = file;
}
 
Example 25
Source Project: commons-vfs   Source File: DefaultFileContent.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Writes this content to another FileContent.
 *
 * @param fileContent The target FileContent.
 * @return the total number of bytes written
 * @throws IOException if an error occurs writing the content.
 * @since 2.1
 */
@Override
public long write(final FileContent fileContent) throws IOException {
    final OutputStream output = fileContent.getOutputStream();
    try {
        return this.write(output);
    } finally {
        output.close();
    }
}
 
Example 26
Source Project: commons-vfs   Source File: AbstractFileObject.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the file's content.
 *
 * @return the FileContent for this FileObject.
 * @throws FileSystemException if an error occurs.
 */
@Override
public FileContent getContent() throws FileSystemException {
    synchronized (fileSystem) {
        attach();
        if (content == null) {
            content = doCreateFileContent();
        }
        return content;
    }
}
 
Example 27
Source Project: commons-vfs   Source File: CustomRamProviderTest.java    License: Apache License 2.0 5 votes vote down vote up
private InputStream createNonEmptyFile() throws FileSystemException, IOException {
    final FileObject root = manager.resolveFile("ram://file");
    root.createFile();

    final FileContent content = root.getContent();
    final OutputStream output = this.closeOnTearDown(content.getOutputStream());
    output.write(1);
    output.write(2);
    output.write(3);
    output.flush();
    output.close();

    return this.closeOnTearDown(content.getInputStream());
}
 
Example 28
Source Project: commons-vfs   Source File: Http5GetContentInfoTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests VFS-427 NPE on Http5FileObject.getContent().getContentInfo().
 *
 * @throws FileSystemException thrown when the getContentInfo API fails.
 */
@Test
public void testGetContentInfo() throws FileSystemException {
    final FileSystemManager fsManager = VFS.getManager();
    final FileObject fo = fsManager.resolveFile("http5://www.apache.org/licenses/LICENSE-2.0.txt");
    final FileContent content = fo.getContent();
    Assert.assertNotNull(content);
    // Used to NPE before fix:
    content.getContentInfo();
}
 
Example 29
Source Project: commons-vfs   Source File: GetContentInfoFunctionalTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests VFS-427 NPE on HttpFileObject.getContent().getContentInfo().
 *
 * @throws FileSystemException thrown when the getContentInfo API fails.
 */
@Test
public void testGetContentInfo() throws FileSystemException {
    final FileSystemManager fsManager = VFS.getManager();
    try (final FileObject fo = fsManager.resolveFile("http://www.apache.org/licenses/LICENSE-2.0.txt");
            final FileContent content = fo.getContent();) {
        Assert.assertNotNull(content);
        // Used to NPE before fix:
        content.getContentInfo();
    }
}
 
Example 30
Source Project: commons-vfs   Source File: DefaultFileContentTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test VFS-724 should be done on a website which render a page with no content size. Note the getSize() is
 * currently the value sent back by the server then zero usually means no content length attached.
 */
@Test
public void testGetZeroContents() throws IOException {
    final FileSystemManager fsManager = VFS.getManager();
    try (final FileObject fo = fsManager.resolveFile(new File("."), "src/test/resources/test-data/size-0-file.bin");
            final FileContent content = fo.getContent()) {
        Assert.assertEquals(0, content.getSize());
        Assert.assertTrue(content.isEmpty());
        Assert.assertEquals(StringUtils.EMPTY, content.getString(StandardCharsets.UTF_8));
        Assert.assertEquals(StringUtils.EMPTY, content.getString(StandardCharsets.UTF_8.name()));
        Assert.assertArrayEquals(ArrayUtils.EMPTY_BYTE_ARRAY, content.getByteArray());
    }
}