Java Code Examples for org.apache.commons.vfs2.FileObject#getFileSystem()

The following examples show how to use org.apache.commons.vfs2.FileObject#getFileSystem() . 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 File: ProviderCacheStrategyTests.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * Test the on_call strategy
 */
public void testOnCallCache() throws Exception {
    final FileObject scratchFolder = getWriteFolder();
    if (FileObjectUtils.isInstanceOf(getBaseFolder(), RamFileObject.class)
            || scratchFolder.getFileSystem() instanceof VirtualFileSystem) {
        // cant check ram filesystem as every manager holds its own ram filesystem data
        return;
    }

    scratchFolder.delete(Selectors.EXCLUDE_SELF);

    final DefaultFileSystemManager fs = createManager();
    fs.setCacheStrategy(CacheStrategy.ON_CALL);
    fs.init();
    final FileObject foBase2 = getBaseTestFolder(fs);

    final FileObject cachedFolder = foBase2.resolveFile(scratchFolder.getName().getPath());

    FileObject[] fos = cachedFolder.getChildren();
    assertContainsNot(fos, "file1.txt");

    scratchFolder.resolveFile("file1.txt").createFile();

    fos = cachedFolder.getChildren();
    assertContains(fos, "file1.txt");
}
 
Example 2
Source File: SoftRefFilesCache.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
@Override
public void putFile(final FileObject fileObject) {
    if (log.isDebugEnabled()) {
        log.debug("putFile: " + this.getSafeName(fileObject));
    }

    final Map<FileName, Reference<FileObject>> files = getOrCreateFilesystemCache(fileObject.getFileSystem());

    final Reference<FileObject> ref = createReference(fileObject, refQueue);
    final FileSystemAndNameKey key = new FileSystemAndNameKey(fileObject.getFileSystem(), fileObject.getName());

    lock.lock();
    try {
        final Reference<FileObject> old = files.put(fileObject.getName(), ref);
        if (old != null) {
            refReverseMap.remove(old);
        }
        refReverseMap.put(ref, key);
    } finally {
        lock.unlock();
    }
}
 
Example 3
Source File: SoftRefFilesCache.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
@Override
public boolean putFileIfAbsent(final FileObject fileObject) {
    if (log.isDebugEnabled()) {
        log.debug("putFile: " + this.getSafeName(fileObject));
    }

    final Map<FileName, Reference<FileObject>> files = getOrCreateFilesystemCache(fileObject.getFileSystem());

    final Reference<FileObject> ref = createReference(fileObject, refQueue);
    final FileSystemAndNameKey key = new FileSystemAndNameKey(fileObject.getFileSystem(), fileObject.getName());

    lock.lock();
    try {
        if (files.containsKey(fileObject.getName()) && files.get(fileObject.getName()).get() != null) {
            return false;
        }
        final Reference<FileObject> old = files.put(fileObject.getName(), ref);
        if (old != null) {
            refReverseMap.remove(old);
        }
        refReverseMap.put(ref, key);
        return true;
    } finally {
        lock.unlock();
    }
}
 
Example 4
Source File: AbstractFilesCacheTestsBase.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * Basic Cache operations, work for all caches (besides {@link NullFilesCache#testBasicCacheOps() NullFilesCache}).
 */
public void testBasicCacheOps() throws Exception {
    final FilesCache cache = getManager().getFilesCache();
    final FileObject fo = getWriteFolder().resolveFile("dir1");
    final FileName fn = fo.getName();
    final FileSystem fs = fo.getFileSystem();

    cache.clear(fs);
    assertNull(cache.getFile(fs, fn));

    cache.putFile(fo);
    assertSame(fo, cache.getFile(fs, fn));

    assertFalse(cache.putFileIfAbsent(fo));
    cache.clear(fs);
    assertNull(cache.getFile(fs, fn));
    assertTrue(cache.putFileIfAbsent(fo));

    cache.removeFile(fs, fn);
    assertNull(cache.getFile(fs, fn));
    assertTrue(cache.putFileIfAbsent(fo));
}
 
Example 5
Source File: NullFilesCacheTests.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
@Override
public void testBasicCacheOps() throws Exception {
    final DefaultFileSystemManager manager = getManager();
    Assert.assertNotNull("This test should not have a null DefaultFileSystemManager", manager);
    // the basic test looks different for a null cache:
    final FilesCache cache = manager.getFilesCache();
    final FileObject fo = getWriteFolder().resolveFile("dir1");
    final FileName fn = fo.getName();
    final FileSystem fs = fo.getFileSystem();

    cache.clear(fs);
    assertNull(cache.getFile(fs, fn));

    cache.putFile(fo);
    assertNull(null, cache.getFile(fs, fn));

    assertFalse(cache.putFileIfAbsent(fo)); // hmmm?
    assertNull(null, cache.getFile(fs, fn));

    cache.removeFile(fs, fn);
    assertNull(cache.getFile(fs, fn));
}
 
Example 6
Source File: ZipProviderWithCharsetTestCase.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the base folder for read tests.
 */
@Override
public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception {
    final FileSystemOptions opts = new FileSystemOptions();
    final ZipFileSystemConfigBuilder builder = ZipFileSystemConfigBuilder.getInstance();
    // Tests the same charset as the default but we exercise having a Charset set.
    builder.setCharset(opts, StandardCharsets.UTF_8);

    final File zipFile = AbstractVfsTestCase.getTestResource("test.zip");
    final String uri = "zip:file:" + zipFile.getAbsolutePath() + "!/";
    final FileObject resolvedFile = manager.resolveFile(uri, opts);
    final FileSystem fileSystem = resolvedFile.getFileSystem();
    Assert.assertTrue(fileSystem instanceof ZipFileSystem);
    final ZipFileSystem zipFileSystem = (ZipFileSystem) fileSystem;
    Assert.assertEquals(StandardCharsets.UTF_8, zipFileSystem.getCharset());
    return resolvedFile;
}
 
Example 7
Source File: ZipProviderWithCharsetNullTestCase.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the base folder for read tests.
 */
@Override
public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception {
    final FileSystemOptions opts = new FileSystemOptions();
    final ZipFileSystemConfigBuilder builder = ZipFileSystemConfigBuilder.getInstance();
    // Tests null as the default.
    builder.setCharset(opts, null);

    final File zipFile = AbstractVfsTestCase.getTestResource("test.zip");
    final String uri = "zip:file:" + zipFile.getAbsolutePath() + "!/";
    final FileObject resolvedFile = manager.resolveFile(uri, opts);
    final FileSystem fileSystem = resolvedFile.getFileSystem();
    Assert.assertTrue(fileSystem instanceof ZipFileSystem);
    final ZipFileSystem zipFileSystem = (ZipFileSystem) fileSystem;
    Assert.assertNull(zipFileSystem.getCharset());
    return resolvedFile;
}
 
Example 8
Source File: RamProviderTestCase.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the base folder for tests.
 */
@Override
public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception {
    if (!inited) {
        // Import the test tree
        final FileObject fo = manager.resolveFile("ram:/");
        final RamFileSystem fs = (RamFileSystem) fo.getFileSystem();
        fs.importTree(getTestDirectoryFile());
        fo.close();

        inited = true;
    }

    final String uri = "ram:/";
    return manager.resolveFile(uri);
}
 
Example 9
Source File: AbstractSftpProviderTestCase.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the base folder for tests.
 */
@Override
public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception {
    String uri = getSystemTestUriOverride();
    if (uri == null) {
        uri = ConnectionUri;
    }

    final FileSystemOptions fileSystemOptions = new FileSystemOptions();
    final SftpFileSystemConfigBuilder builder = SftpFileSystemConfigBuilder.getInstance();
    builder.setStrictHostKeyChecking(fileSystemOptions, "no");
    builder.setUserInfo(fileSystemOptions, new TrustEveryoneUserInfo());
    builder.setIdentityRepositoryFactory(fileSystemOptions, new TestIdentityRepositoryFactory());
    final FileObject fileObject = manager.resolveFile(uri, fileSystemOptions);
    this.fileSystem = (SftpFileSystem) fileObject.getFileSystem();
    return fileObject;
}
 
Example 10
Source File: ValidateLoginTask.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public boolean validateLoginData() throws FileSystemException {
  if ( loginData == null ) {
    return true;
  }
  final FileObject vfsConnection = PublishUtil.createVFSConnection( VFS.getManager(), loginData );
  try {
    final FileSystem fileSystem = vfsConnection.getFileSystem();
    if ( fileSystem instanceof WebSolutionFileSystem ) {
      final WebSolutionFileSystem webSolutionFileSystem = (WebSolutionFileSystem) fileSystem;
      final Long l = (Long) webSolutionFileSystem.getAttribute( WebSolutionFileSystem.LAST_REFRESH_TIME_ATTRIBUTE );
      if ( l != null ) {
        if ( ( System.currentTimeMillis() - l ) > 500 ) {
          webSolutionFileSystem.getLocalFileModel().refresh();
        }
      }
      return true;
    }
  } catch ( FileSystemException fse ) {
    // not all file systems support attributes ..
  } catch ( IOException e ) {
    return false;
  }
  final FileType type = vfsConnection.getType();
  if ( type != FileType.FOLDER ) {
    return false;
  }
  return true;
}
 
Example 11
Source File: ProviderCacheStrategyTests.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Test the on_resolve strategy
 */
public void testOnResolveCache() throws Exception {
    final FileObject scratchFolder = getWriteFolder();
    if (FileObjectUtils.isInstanceOf(getBaseFolder(), RamFileObject.class)
            || scratchFolder.getFileSystem() instanceof VirtualFileSystem) {
        // cant check ram filesystem as every manager holds its own ram filesystem data
        return;
    }

    scratchFolder.delete(Selectors.EXCLUDE_SELF);

    final DefaultFileSystemManager fs = createManager();
    fs.setCacheStrategy(CacheStrategy.ON_RESOLVE);
    fs.init();
    final FileObject foBase2 = getBaseTestFolder(fs);

    FileObject cachedFolder = foBase2.resolveFile(scratchFolder.getName().getPath());

    FileObject[] fos = cachedFolder.getChildren();
    assertContainsNot(fos, "file1.txt");

    scratchFolder.resolveFile("file1.txt").createFile();

    fos = cachedFolder.getChildren();
    assertContainsNot(fos, "file1.txt");

    cachedFolder = foBase2.resolveFile(scratchFolder.getName().getPath());
    fos = cachedFolder.getChildren();
    assertContains(fos, "file1.txt");
}
 
Example 12
Source File: ProviderCacheStrategyTests.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Test the manual cache strategy
 */
public void testManualCache() throws Exception {
    final FileObject scratchFolder = getWriteFolder();
    if (FileObjectUtils.isInstanceOf(getBaseFolder(), RamFileObject.class)
            || scratchFolder.getFileSystem() instanceof VirtualFileSystem) {
        // cant check ram filesystem as every manager holds its own ram filesystem data
        return;
    }

    scratchFolder.delete(Selectors.EXCLUDE_SELF);

    final DefaultFileSystemManager fs = createManager();
    fs.setCacheStrategy(CacheStrategy.MANUAL);
    fs.init();
    final FileObject foBase2 = getBaseTestFolder(fs);

    final FileObject cachedFolder = foBase2.resolveFile(scratchFolder.getName().getPath());

    FileObject[] fos = cachedFolder.getChildren();
    assertContainsNot(fos, "file1.txt");

    scratchFolder.resolveFile("file1.txt").createFile();

    fos = cachedFolder.getChildren();
    assertContainsNot(fos, "file1.txt");

    cachedFolder.refresh();
    fos = cachedFolder.getChildren();
    assertContains(fos, "file1.txt");
}
 
Example 13
Source File: SftpProviderStreamProxyModeTestCase.java    From commons-vfs with Apache License 2.0 4 votes vote down vote up
@Override
public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception {
    String uri = getSystemTestUriOverride();
    if (uri == null) {
        uri = ConnectionUri;
    }

    final FileSystemOptions fileSystemOptions = new FileSystemOptions();
    final SftpFileSystemConfigBuilder builder = SftpFileSystemConfigBuilder.getInstance();
    builder.setStrictHostKeyChecking(fileSystemOptions, "no");
    builder.setUserInfo(fileSystemOptions, new TrustEveryoneUserInfo());
    builder.setIdentityRepositoryFactory(fileSystemOptions, new TestIdentityRepositoryFactory());

    final FileSystemOptions proxyOptions = (FileSystemOptions) fileSystemOptions.clone();

    final URI parsedURI = new URI(uri);
    final String userInfo = parsedURI.getUserInfo();
    final String[] userFields = userInfo == null ? null : userInfo.split(":", 2);

    builder.setProxyType(fileSystemOptions, SftpFileSystemConfigBuilder.PROXY_STREAM);
    if (userFields != null) {
        if (userFields.length > 0) {
            builder.setProxyUser(fileSystemOptions, userFields[0]);
        }
        if (userFields.length > 1) {
            builder.setProxyPassword(fileSystemOptions, userFields[1]);
        }
    }
    builder.setProxyHost(fileSystemOptions, parsedURI.getHost());
    builder.setProxyPort(fileSystemOptions, parsedURI.getPort());
    builder.setProxyCommand(fileSystemOptions, SftpStreamProxy.NETCAT_COMMAND);
    builder.setProxyOptions(fileSystemOptions, proxyOptions);
    builder.setProxyPassword(fileSystemOptions, parsedURI.getAuthority());

    // Set up the new URI
    if (userInfo == null) {
        uri = String.format("sftp://localhost:%d", parsedURI.getPort());
    } else {
        uri = String.format("sftp://%s@localhost:%d", userInfo, parsedURI.getPort());
    }


    final FileObject fileObject = manager.resolveFile(uri, fileSystemOptions);
    this.fileSystem = (SftpFileSystem) fileObject.getFileSystem();
    return fileObject;
}
 
Example 14
Source File: WeakRefFileListener.java    From commons-vfs with Apache License 2.0 4 votes vote down vote up
protected WeakRefFileListener(final FileObject file, final FileListener listener) {
    this.fs = file.getFileSystem();
    this.name = file.getName();
    this.listener = new WeakReference<>(listener);
}
 
Example 15
Source File: PublishToServerTask.java    From pentaho-reporting with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void run() {
  final MasterReport report = reportDesignerContext.getActiveContext().getContextRoot();
  final DocumentMetaData metaData = report.getBundle().getMetaData();

  try {
    final String oldName = extractLastFileName( report );

    SelectFileForPublishTask selectFileForPublishTask = new SelectFileForPublishTask( uiContext );
    readBundleMetaData( report, metaData, selectFileForPublishTask );

    final String selectedReport = selectFileForPublishTask.selectFile( loginData, oldName );
    if ( selectedReport == null ) {
      return;
    }

    loginData.setOption( "lastFilename", selectedReport );
    storeBundleMetaData( report, selectedReport, selectFileForPublishTask );

    reportDesignerContext.getActiveContext().getAuthenticationStore().add( loginData, storeUpdates );

    //populate all properties from file which loaded in report designer before publish it to server
    Properties fileProperties = new Properties();
    String reportTitle = selectFileForPublishTask.getReportTitle();
    if ( reportTitle != null ) {
      fileProperties.setProperty( PublishRestUtil.REPORT_TITLE_KEY, reportTitle );
    }

    final byte[] data = PublishUtil.createBundleData( report );
    int responseCode = PublishUtil.publish( data, selectedReport, loginData, fileProperties );

    if ( responseCode == 200 ) {
      final Component glassPane = SwingUtilities.getRootPane( uiContext ).getGlassPane();
      try {
        glassPane.setVisible( true );
        glassPane.setCursor( new Cursor( Cursor.WAIT_CURSOR ) );

        FileObject fileSystemRoot = PublishUtil.createVFSConnection( loginData );
        final JCRSolutionFileSystem fileSystem = (JCRSolutionFileSystem) fileSystemRoot.getFileSystem();
        fileSystem.getLocalFileModel().refresh();
      } catch ( Exception e1 ) {
        UncaughtExceptionsModel.getInstance().addException( e1 );
      } finally {
        glassPane.setVisible( false );
        glassPane.setCursor( new Cursor( Cursor.DEFAULT_CURSOR ) );
      }
      if ( JOptionPane.showConfirmDialog( uiContext, Messages.getInstance().getString(
          "PublishToServerAction.Successful.LaunchNow" ), Messages.getInstance().getString(
          "PublishToServerAction.Successful.LaunchTitle" ), JOptionPane.YES_NO_OPTION ) == JOptionPane.YES_OPTION ) {
        PublishUtil.launchReportOnServer( loginData.getUrl(), selectedReport );
      }
    } else if ( responseCode == 403 ) {
      logger.error( "Publish failed. Server responded with status-code " + responseCode );
      JOptionPane.showMessageDialog( uiContext, Messages.getInstance().getString(
          "PublishToServerAction.FailedAccess" ), Messages.getInstance().getString(
          "PublishToServerAction.FailedAccessTitle" ), JOptionPane.ERROR_MESSAGE );
    } else {
      logger.error( "Publish failed. Server responded with status-code " + responseCode );
      showErrorMessage();
    }
  } catch ( Exception exception ) {
    logger.error( "Publish failed. Unexpected error:", exception );
    showErrorMessage();
  }
}
 
Example 16
Source File: ProviderWriteTests.java    From commons-vfs with Apache License 2.0 4 votes vote down vote up
/**
 * Check listeners are notified of changes.
 */
public void testListener() throws Exception {
    final FileObject baseFile = createScratchFolder();

    final FileObject child = baseFile.resolveFile("newfile.txt");
    assertFalse(child.exists());

    final FileSystem fs = baseFile.getFileSystem();
    final TestListener listener = new TestListener(child);
    fs.addListener(child, listener);
    try {
        // Create as a folder
        listener.addCreateEvent();
        child.createFolder();
        listener.assertFinished();

        // Create the folder again. Should not get an event.
        child.createFolder();

        // Delete
        listener.addDeleteEvent();
        child.delete();
        listener.assertFinished();

        // Delete again. Should not get an event
        child.delete();

        // Create as a file
        listener.addCreateEvent();
        child.createFile();
        listener.assertFinished();

        // Create the file again. Should not get an event
        child.createFile();

        listener.addDeleteEvent();
        child.delete();

        // Create as a file, by writing to it.
        listener.addCreateEvent();
        child.getContent().getOutputStream().close();
        listener.assertFinished();

        // Recreate the file by writing to it
        child.getContent().getOutputStream().close();

        // Copy another file over the top
        final FileObject otherChild = baseFile.resolveFile("folder1");
        otherChild.createFolder();
        listener.addDeleteEvent();
        listener.addCreateEvent();
        child.copyFrom(otherChild, Selectors.SELECT_SELF);
        listener.assertFinished();

    } finally {
        fs.removeListener(child, listener);
    }
}
 
Example 17
Source File: AbstractProviderTestCase.java    From commons-vfs with Apache License 2.0 4 votes vote down vote up
protected FileSystem getFileSystem() {
    final FileObject rFolder = getReadFolder();
    Assert.assertNotNull("This test's read folder should not be null", rFolder);
    return rFolder.getFileSystem();
}
 
Example 18
Source File: AbstractFileObject.java    From commons-vfs with Apache License 2.0 2 votes vote down vote up
/**
 * Queries the object if a simple rename to the file name of {@code newfile} is possible.
 *
 * @param newfile the new file name
 * @return true if rename is possible
 */
@Override
public boolean canRenameTo(final FileObject newfile) {
    return fileSystem == newfile.getFileSystem();
}