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

The following examples show how to use org.apache.commons.vfs2.FileSystemException. 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: spoofax   Source File: DefaultFileSystemManagerProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override public FileSystemManager get() {
    try {
        final DefaultFileSystemManager manager = new DefaultFileSystemManager();

        manager.setFilesCache(new DefaultFilesCache());
        manager.setCacheStrategy(CacheStrategy.ON_RESOLVE);

        final String baseTmpDir = System.getProperty("java.io.tmpdir");
        final File tempDir = new File(baseTmpDir, "vfs_cache" + new Random().nextLong()).getAbsoluteFile();
        final DefaultFileReplicator replicator = new DefaultFileReplicator(tempDir);
        manager.setTemporaryFileStore(replicator);
        manager.setReplicator(replicator);

        addDefaultProvider(manager);
        addProviders(manager);
        setBaseFile(manager);

        manager.init();

        return manager;
    } catch(FileSystemException e) {
        throw new RuntimeException("Cannot initialize resource service: " + e.getMessage(), e);
    }
}
 
Example 2
private Response deleteDir(FileObject fo, List<String> includes, List<String> excludes) throws FileSystemException {
    if ((includes == null || includes.isEmpty()) && (excludes == null || excludes.isEmpty())) {
        fo.delete(SELECT_ALL);
        fo.delete();
        return noContentRes();
    } else {
        List<FileObject> children = FileSystem.findFiles(fo, includes, excludes);
        for (FileObject child : children) {
            if (!child.delete()) {
                child.delete(SELECT_ALL);
                child.delete();
            }
        }
        return noContentRes();
    }
}
 
Example 3
Source Project: hop   Source File: SwtSvgImageUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Internal image loading from Hop's user.dir VFS.
 */
private static SwtUniversalImage loadFromBasedVFS( Display display, String location ) {
  try {
    FileObject imageFileObject = HopVfs.getFileSystemManager().resolveFile( base, location );
    InputStream s = HopVfs.getInputStream( imageFileObject );
    if ( s == null ) {
      return null;
    }
    try {
      return loadImage( display, s, location );
    } finally {
      IOUtils.closeQuietly( s );
    }
  } catch ( FileSystemException ex ) {
    return null;
  }
}
 
Example 4
public FileObjectResourceData( final ResourceKey key ) throws ResourceLoadingException {
  if ( key == null ) {
    throw new NullPointerException();
  }
  final FileObject fileObject = (FileObject) key.getIdentifier();
  try {
    if ( fileObject.exists() == false ) {
      throw new ResourceLoadingException( "File-handle given does not point to an existing file." );
    }
    if ( fileObject.isFile() == false ) {
      throw new ResourceLoadingException( "File-handle given does not point to a regular file." );
    }
    if ( fileObject.isReadable() == false ) {
      throw new ResourceLoadingException( "File '" + fileObject + "' is not readable." );
    }
  } catch ( FileSystemException fse ) {
    throw new ResourceLoadingException( "Unable to create FileObjectResourceData : ", fse );
  }

  this.key = key;
  this.fileObject = fileObject;
}
 
Example 5
Source Project: commons-vfs   Source File: GenericURLFileName.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets the path encoded suitable for url like file system e.g. (http, webdav).
 *
 * @param charset the charset used for the path encoding
 * @return The encoded path.
 * @throws URISyntaxException If an error occurs encoding the URI.
 * @throws FileSystemException If some other error occurs.
 */
public String getPathQueryEncoded(final String charset) throws URISyntaxException, FileSystemException {
    if (getQueryString() == null) {
        if (charset != null) {
            return URIUtils.encodePath(getPathDecoded(), charset);
        } else {
            return URIUtils.encodePath(getPathDecoded());
        }
    }

    final StringBuilder sb = new StringBuilder(BUFFER_SIZE);
    if (charset != null) {
        sb.append(URIUtils.encodePath(getPathDecoded(), charset));
    } else {
        sb.append(URIUtils.encodePath(getPathDecoded()));
    }
    sb.append("?");
    sb.append(getQueryString());
    return sb.toString();
}
 
Example 6
Source Project: commons-vfs   Source File: WebdavFileObject.java    License: Apache License 2.0 6 votes vote down vote up
DavPropertySet getProperties(final URLFileName name, final int type, final DavPropertyNameSet nameSet,
        final boolean addEncoding) throws FileSystemException {
    try {
        final String urlStr = toUrlString(name);
        final PropFindMethod method = new PropFindMethod(urlStr, type, nameSet, DavConstants.DEPTH_0);
        setupMethod(method);
        execute(method);
        if (method.succeeded()) {
            final MultiStatus multiStatus = method.getResponseBodyAsMultiStatus();
            final MultiStatusResponse response = multiStatus.getResponses()[0];
            final DavPropertySet props = response.getProperties(HttpStatus.SC_OK);
            if (addEncoding) {
                final DavProperty prop = new DefaultDavProperty(RESPONSE_CHARSET, method.getResponseCharSet());
                props.add(prop);
            }
            return props;
        }
        return new DavPropertySet();
    } catch (final FileSystemException fse) {
        throw fse;
    } catch (final Exception e) {
        throw new FileSystemException("vfs.provider.webdav/get-property.error", e, getName(), name, type,
                nameSet.getContent(), addEncoding);
    }
}
 
Example 7
Source Project: commons-vfs   Source File: AgeFileFilterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAgeFileFilterFileBoolean() throws FileSystemException {

    AgeFileFilter testee;

    testee = new AgeFileFilter(currentFileInfo.getFile(), true);
    Assert.assertTrue(testee.accept(oldFileInfo));
    Assert.assertTrue(testee.accept(currentFileInfo));
    Assert.assertFalse(testee.accept(newFileInfo));

    testee = new AgeFileFilter(currentFileInfo.getFile(), false);
    Assert.assertFalse(testee.accept(oldFileInfo));
    Assert.assertFalse(testee.accept(currentFileInfo));
    Assert.assertTrue(testee.accept(newFileInfo));

}
 
Example 8
Source Project: spoofax   Source File: CommonPaths.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable protected FileObject find(Iterable<FileObject> dirs, String relativePath) {
    FileObject file = null;
    for(FileObject dir : dirs) {
        try {
            FileObject candidate = dir.resolveFile(relativePath);
            if(candidate.exists()) {
                if(file != null) {
                    throw new MetaborgRuntimeException("Found multiple candidates for " + relativePath);
                } else {
                    file = candidate;
                }
            }
        } catch(FileSystemException e) {
            logger.warn("Error when trying to resolve {} in {}", e, relativePath, dir);
        }
    }
    return file;
}
 
Example 9
Source Project: commons-vfs   Source File: NameFileFilterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAcceptStringIOCaseInsensitive() throws FileSystemException {

    // PREPARE
    final NameFileFilter filter = new NameFileFilter(IOCase.INSENSITIVE, "test2.txt");

    // TEST
    Assert.assertFalse(filter.accept(createFileSelectInfo(new File("test1.txt"))));
    Assert.assertTrue(filter.accept(createFileSelectInfo(new File("test2.txt"))));
    Assert.assertTrue(filter.accept(createFileSelectInfo(new File("Test2.txt"))));
    Assert.assertFalse(filter.accept(createFileSelectInfo(new File("test.xxx"))));

}
 
Example 10
@Override
public boolean isFolder(String dataspace, String pathname) throws NotConnectedException, PermissionException {
    try {
        return resolveFile(dataspace, pathname).isFolder();
    } catch (FileSystemException e) {
        logger.debug(String.format("Can't parse the file [%s] in the dataspace [%s].", pathname, dataspace), e);
        return false;
    }
}
 
Example 11
Source Project: hop   Source File: SimpleResourceNaming.java    License: Apache License 2.0 5 votes vote down vote up
public String nameResource( FileObject fileObject, IVariables variables, boolean includeFileName ) throws FileSystemException {
  if ( includeFileName ) {
    return handleDataFile( fileObject.getName().getBaseName(), fileObject.getParent().getURL().toString(), "" );
  } else {
    return handleDataFile( "", fileObject.getURL().toString(), "" );
  }
}
 
Example 12
Source Project: commons-vfs   Source File: TarFileSystem.java    License: Apache License 2.0 5 votes vote down vote up
protected void resetTarFile() throws FileSystemException {
    // Reading specific entries requires skipping through the tar file from the beginning
    // Not especially elegant, but we don't have the ability to seek to specific positions
    // with an input stream.
    if (this.file.exists()) {
        recreateTarFile();
    }
}
 
Example 13
Source Project: commons-vfs   Source File: DefaultFileContent.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void close() throws FileSystemException {
    try {
        super.close();
    } catch (final IOException e) {
        throw new FileSystemException("vfs.provider/close-rac.error", file, e);
    }
}
 
Example 14
Source Project: commons-vfs   Source File: DelegateFileObject.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Close the delegated file.
 *
 * @throws FileSystemException if an error occurs.
 */
@Override
public void close() throws FileSystemException {
    super.close();

    if (file != null) {
        file.close();
    }
}
 
Example 15
Source Project: commons-vfs   Source File: NamingTests.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that a particular relative name is invalid for a particular scope.
 */
private void assertBadName(final FileName name, final String relName, final NameScope scope) {
    try {
        getManager().resolveName(name, relName, scope);
        fail("expected failure");
    } catch (final FileSystemException e) {
        // TODO - should check error message
    }
}
 
Example 16
Source Project: commons-vfs   Source File: EmptyFileFilterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAcceptNotEmpty() throws FileSystemException {

    final FileFilter testee = EmptyFileFilter.NOT_EMPTY;

    Assert.assertTrue(testee.accept(notEmptyFileInfo));
    Assert.assertFalse(testee.accept(emptyFileInfo));
    Assert.assertTrue(testee.accept(notEmptyDirInfo));
    Assert.assertFalse(testee.accept(emptyDirInfo));
    Assert.assertFalse(testee.accept(notExistingFileInfo));

}
 
Example 17
public FileSystem fileSystem(Session session)
        throws FileSystemException, NotConnectedException, PermissionException {
    FileSystem fs = session.fileSystem();
    if (fs == null) {
        synchronized (session) {
            fs = session.fileSystem();
            if (fs == null) {
                fs = FileSystem.Builder.create(session.getScheduler());
                session.fileSystem(fs);
            }
        }
    }
    return fs;
}
 
Example 18
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 19
Source Project: otroslogviewer   Source File: Utils.java    License: Apache License 2.0 5 votes vote down vote up
public static void closeQuietly(FileObject fileObject) {

    if (fileObject != null) {
      String friendlyURI = fileObject.getName().getFriendlyURI();
      try {
        LOGGER.info(String.format("Closing file %s", friendlyURI));
        fileObject.close();
        LOGGER.info(String.format("File %s closed", friendlyURI));
      } catch (FileSystemException ignore) {
        LOGGER.error(String.format("File %s is not closed: %s", friendlyURI, ignore.getMessage()));
      }
    }
  }
 
Example 20
Source Project: commons-vfs   Source File: ResourceFileName.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the decoded URI of the file.
 *
 * @return the FileName as a URI.
 */
@Override
public String toString() {
    try {
        return UriParser.decode(super.getURI());
    } catch (final FileSystemException e) {
        return super.getURI();
    }
}
 
Example 21
Source Project: commons-vfs   Source File: FileObjectUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testReadPropertiesInto() throws FileSystemException, IOException {
    final Properties p = new Properties();
    p.setProperty("extraKey", "extraValue");
    assertProperties(FileObjectUtils
        .readProperties(VFS.getManager().toFileObject(new File("src/test/resources/test.properties")), p));
    Assert.assertEquals("extraValue", p.getProperty("extraKey"));
}
 
Example 22
Source Project: otroslogviewer   Source File: VfsBrowser.java    License: Apache License 2.0 5 votes vote down vote up
public void setSelectionMode(SelectionMode mode) {
  if (selectionMode == mode) {
    return;
  }
  SelectionMode oldValue = selectionMode;
  this.selectionMode = mode;
  firePropertyChange(MULTI_SELECTION_MODE_CHANGED_PROPERTY, oldValue, selectionMode);
  try {
    selectionChanged();
  } catch (FileSystemException e) {
    LOGGER.error("Error during update state", e);
  }
}
 
Example 23
Source Project: commons-vfs   Source File: Vfs444TestCase.java    License: Apache License 2.0 5 votes vote down vote up
public void testResolvePartialPath2() throws FileSystemException {
    final FileName root = getManager().resolveURI("res:test-data");
    final FileName file = getManager().resolveName(root, "test.zip");
    final String uri = file.getURI();
    final FileObject result = getManager().resolveFile(uri);
    Assert.assertNotNull(result);
    Assert.assertTrue(result.exists());
}
 
Example 24
Source Project: pentaho-kettle   Source File: ConnectionFileSystem.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public FileObject resolveFile( FileName name ) throws FileSystemException {
  try {
    return this.createFile( (AbstractFileName) name );
  } catch ( Exception e ) {
    throw new FileSystemException( "vfs.provider/resolve-file.error", name, e );
  }
}
 
Example 25
Source Project: pentaho-kettle   Source File: RepositoryExporter.java    License: Apache License 2.0 5 votes vote down vote up
private String calcRepositoryDirectory( KettleFileRepository fileRep, FileObject fileObject ) throws FileSystemException {
  String path = fileObject.getParent().getName().getPath();
  String baseDirectory = fileRep.getRepositoryMeta().getBaseDirectory();
  // Double check!
  //
  if ( path.startsWith( baseDirectory ) ) {
    return path.substring( baseDirectory.length() );
  } else {
    return path;
  }
}
 
Example 26
public void testSchemaResolve() throws FileSystemException {
  final URL url = Prd3139Test.class.getResource
    ( "/org/pentaho/reporting/engine/classic/extensions/datasources/mondrian/steelwheels.mondrian.xml" );
  final String fileTxt = url.getFile();
  final File file = new File( fileTxt ).getAbsoluteFile();
  assertTrue( file.canRead() );
  assertNotNull(
    SchemaResolver.resolveSchema( null, null, "../../../../../../../../../../../../../../" + file.getPath() ) );
}
 
Example 27
Source Project: spoofax   Source File: ResourceAgent.java    License: Apache License 2.0 5 votes vote down vote up
@Override public boolean writable(String fn) {
    try {
        final FileObject resource = resourceService.resolve(workingDir, fn);
        return resource.isWriteable();
    } catch(FileSystemException e) {
        throw new RuntimeException("Could not check if file " + fn + " is writeable", e);
    }
}
 
Example 28
Source Project: spoofax   Source File: ResourceAgent.java    License: Apache License 2.0 5 votes vote down vote up
@Override public boolean exists(String fn) {
    try {
        final FileObject resource = resourceService.resolve(workingDir, fn);
        return resource.exists();
    } catch(FileSystemException e) {
        throw new RuntimeException("Could not check if file " + fn + " exists", e);
    }
}
 
Example 29
Source Project: commons-vfs   Source File: AbstractFileObject.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns an iterator over a set of all FileObject in this file object.
 *
 * @return an Iterator.
 */
@Override
public Iterator<FileObject> iterator() {
    try {
        return listFiles(Selectors.SELECT_ALL).iterator();
    } catch (final FileSystemException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 30
@Override
public void close() throws VirtualFilesystemException {
    try {
        this.file.close();
    } catch (FileSystemException e) {
        throw new VirtualFilesystemException(e);
    }
}