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

The following examples show how to use org.apache.commons.vfs2.FileType. 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
@Test
public void testGetElementForRow() {
  RepositoryTableModel repoTableModel = new RepositoryTableModel();
  assertNotNull( repoTableModel );
  repoTableModel.setSelectedPath( fileObject );

  try {
    doReturn( FileType.FOLDER ).when( fileObject ).getType();
    FileObject[] childFiles = new FileObject[] { childFile1, childFile2, childFile3 };
    doReturn( childFileName1 ).when( childFile1 ).getName();
    doReturn( childFileName2 ).when( childFile2 ).getName();
    doReturn( childFileName3 ).when( childFile3 ).getName();
    doReturn( "file1.txt" ).when( childFileName1 ).getBaseName();
    doReturn( "file2.txt" ).when( childFileName2 ).getBaseName();
    doReturn( "file3.txt" ).when( childFileName3 ).getBaseName();
    doReturn( childFiles ).when( fileObject ).getChildren();
    assertEquals( childFile2, repoTableModel.getElementForRow( 1 ) );
  } catch ( FileSystemException e ) {
    e.printStackTrace();
  }

}
 
Example 2
Source Project: hop   Source File: S3CommonFileObject.java    License: Apache License 2.0 6 votes vote down vote up
private void handleAttachExceptionFallback( String bucket, String keyWithDelimiter, AmazonS3Exception exception )
  throws FileSystemException {
  ListObjectsRequest listObjectsRequest = new ListObjectsRequest()
    .withBucketName( bucket )
    .withPrefix( keyWithDelimiter )
    .withDelimiter( DELIMITER );
  ObjectListing ol = fileSystem.getS3Client().listObjects( listObjectsRequest );

  if ( !( ol.getCommonPrefixes().isEmpty() && ol.getObjectSummaries().isEmpty() ) ) {
    injectType( FileType.FOLDER );
  } else {
    //Folders don't really exist - they will generate a "NoSuchKey" exception
    // confirms key doesn't exist but connection okay
    String errorCode = exception.getErrorCode();
    if ( !errorCode.equals( "NoSuchKey" ) ) {
      // bubbling up other connection errors
      logger.error( "Could not get information on " + getQualifiedName(),
        exception ); // make sure this gets printed for the user
      throw new FileSystemException( "vfs.provider/get-type.error", getQualifiedName(), exception );
    }
  }
}
 
Example 3
Source Project: hop   Source File: S3FileNameParser.java    License: Apache License 2.0 6 votes vote down vote up
public FileName parseUri( VfsComponentContext context, FileName base, String uri ) throws FileSystemException {
  StringBuilder name = new StringBuilder();

  String scheme = UriParser.extractScheme( uri, name );
  UriParser.canonicalizePath( name, 0, name.length(), this );

  // Normalize separators in the path
  UriParser.fixSeparators( name );

  // Normalise the path
  FileType fileType = UriParser.normalisePath( name );

  String fullPath = name.toString();
  // Extract bucket name
  final String bucketName = UriParser.extractFirstElement( name );

  return new S3FileName( scheme, bucketName, fullPath, fileType );
}
 
Example 4
Source Project: pentaho-kettle   Source File: Mail.java    License: Apache License 2.0 6 votes vote down vote up
public boolean includeFile( FileSelectInfo info ) {
  boolean returncode = false;
  try {
    if ( !info.getFile().toString().equals( sourceFolder ) ) {
      // Pass over the Base folder itself
      String short_filename = info.getFile().getName().getBaseName();

      if ( info.getFile().getParent().equals( info.getBaseFolder() )
        || ( ( !info.getFile().getParent().equals( info.getBaseFolder() ) && meta.isIncludeSubFolders() ) ) ) {
        if ( ( info.getFile().getType() == FileType.FILE && fileWildcard == null )
          || ( info.getFile().getType() == FileType.FILE && fileWildcard != null && GetFileWildcard(
            short_filename, fileWildcard ) ) ) {
          returncode = true;
        }
      }
    }
  } catch ( Exception e ) {
    logError( BaseMessages.getString( PKG, "Mail.Error.FindingFiles", info.getFile().toString(), e
      .getMessage() ) );
    returncode = false;
  }
  return returncode;
}
 
Example 5
Source Project: commons-vfs   Source File: FtpFileObject.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the file's list of children.
 *
 * @return The list of children
 * @throws FileSystemException If there was a problem listing children
 * @see AbstractFileObject#getChildren()
 * @since 2.0
 */
@Override
public FileObject[] getChildren() throws FileSystemException {
    try {
        if (doGetType() != FileType.FOLDER) {
            throw new FileNotFolderException(getName());
        }
    } catch (final Exception ex) {
        throw new FileNotFolderException(getName(), ex);
    }

    try {
        /*
         * Wrap our parent implementation, noting that we're refreshing so that we don't refresh() ourselves and
         * each of our parents for each children. Note that refresh() will list children. Meaning, if if this file
         * has C children, P parents, there will be (C * P) listings made with (C * (P + 1)) refreshes, when there
         * should really only be 1 listing and C refreshes.
         */
        this.inRefresh.set(true);
        return super.getChildren();
    } finally {
        this.inRefresh.set(false);
    }
}
 
Example 6
@Test
public void testGetChildCount() {
  RepositoryTreeModel treeModel = new RepositoryTreeModel();
  assertNotNull( treeModel );
  treeModel.setFileSystemRoot( repositoryRoot );
  assertEquals( 0, treeModel.getChildCount( repositoryRoot ) );

  FileObject[] childFiles = new FileObject[] { childFile1, childFile2, childFile3 };
  try {
    doReturn( childFiles ).when( repositoryRoot ).getChildren();
    doReturn( FileType.FOLDER ).when( repositoryRoot ).getType();
    doReturn( FileType.FOLDER ).when( childFile1 ).getType();
    doReturn( FileType.FOLDER ).when( childFile2 ).getType();
    doReturn( FileType.FOLDER ).when( childFile3 ).getType();
  } catch ( FileSystemException e ) {
    e.printStackTrace();
  }
  assertEquals( 3, treeModel.getChildCount( repositoryRoot ) );
}
 
Example 7
Source Project: hop   Source File: S3FileObjectTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDoRename() throws Exception {
  String someNewBucketName = "someNewBucketName";
  String someNewKey = "some/newKey";
  S3FileName newFileName = new S3FileName( SCHEME, someNewBucketName, someNewBucketName + "/" + someNewKey, FileType.FILE );
  S3FileObject newFile = new S3FileObject( newFileName, fileSystemSpy );
  ArgumentCaptor<CopyObjectRequest> copyObjectRequestArgumentCaptor = ArgumentCaptor.forClass( CopyObjectRequest.class );
  when( s3ServiceMock.doesBucketExistV2( someNewBucketName ) ).thenReturn( true );
  s3FileObjectFileSpy.doAttach();
  s3FileObjectFileSpy.moveTo( newFile );

  verify( s3ServiceMock ).copyObject( copyObjectRequestArgumentCaptor.capture() );
  assertEquals( someNewBucketName, copyObjectRequestArgumentCaptor.getValue().getDestinationBucketName() );
  assertEquals( someNewKey, copyObjectRequestArgumentCaptor.getValue().getDestinationKey() );
  assertEquals( BUCKET_NAME, copyObjectRequestArgumentCaptor.getValue().getSourceBucketName() );
  assertEquals( origKey, copyObjectRequestArgumentCaptor.getValue().getSourceKey() );
}
 
Example 8
Source Project: hop   Source File: S3FileObjectTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testHandleAttachExceptionEmptyFolder() throws FileSystemException {
  String testKey = BUCKET_NAME + "/" + origKey;
  String testBucket = "badBucketName";
  AmazonS3Exception exception = new AmazonS3Exception( "NoSuchKey" );
  exception.setErrorCode( "NoSuchKey" );

  //test the case where the folder exists and contains things; no exception should be thrown
  when( s3ServiceMock.getObject( BUCKET_NAME, origKey + "/" ) ).thenThrow( exception );
  childObjectListing = mock( ObjectListing.class );
  when( childObjectListing.getObjectSummaries() ).thenReturn( new ArrayList<>() );
  when( childObjectListing.getCommonPrefixes() ).thenReturn( new ArrayList<>() );
  when( s3ServiceMock.listObjects( any( ListObjectsRequest.class ) ) ).thenReturn( childObjectListing );
  try {
    s3FileObjectFileSpy.handleAttachException( testKey, testBucket );
  } catch ( FileSystemException e ) {
    fail( "Caught exception " + e.getMessage() );
  }
  assertEquals( FileType.IMAGINARY, s3FileObjectFileSpy.getType() );
}
 
Example 9
Source Project: commons-vfs   Source File: AbstractFileObject.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Called when this file is deleted. Updates cached info and notifies subclasses, parent and file system.
 *
 * @throws Exception if an error occurs.
 */
protected void handleDelete() throws Exception {
    synchronized (fileSystem) {
        if (attached) {
            // Fix up state
            injectType(FileType.IMAGINARY);
            removeChildrenCache();

            // Notify subclass
            onChange();
        }

        // Notify parent that its child list may no longer be valid
        notifyParent(this.getName(), FileType.IMAGINARY);

        // Notify the file system
        fileSystem.fireFileDeleted(this);
    }
}
 
Example 10
Source Project: hop   Source File: S3NFileObjectTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testHandleAttachExceptionFileNotFound() throws FileSystemException {
  AmazonS3Exception notFoundException = new AmazonS3Exception( "404 Not Found" );
  notFoundException.setErrorCode( "404 Not Found" );
  AmazonS3Exception noSuchKeyException = new AmazonS3Exception( "NoSuchKey" );
  noSuchKeyException.setErrorCode( "NoSuchKey" );

  //test the case where the file is not found; no exception should be thrown
  when( s3ServiceMock.getObject( BUCKET_NAME, origKey ) ).thenThrow( notFoundException );
  when( s3ServiceMock.getObject( BUCKET_NAME, origKey + "/" ) ).thenThrow( noSuchKeyException );
  childObjectListing = mock( ObjectListing.class );
  when( childObjectListing.getObjectSummaries() ).thenReturn( new ArrayList<>() );
  when( childObjectListing.getCommonPrefixes() ).thenReturn( new ArrayList<>() );
  when( s3ServiceMock.listObjects( any( ListObjectsRequest.class ) ) ).thenReturn( childObjectListing );
  try {
    s3FileObjectFileSpy.doAttach();
  } catch ( Exception e ) {
    fail( "Caught exception " + e.getMessage() );
  }
  assertEquals( FileType.IMAGINARY, s3FileObjectFileSpy.getType() );
}
 
Example 11
Source Project: commons-vfs   Source File: ContentTests.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests existence determination.
 */
public void testExists() throws Exception {
    // Test a file
    FileObject file = getReadFolder().resolveFile("file1.txt");
    assertTrue("file exists", file.exists());
    assertNotSame("file exists", file.getType(), FileType.IMAGINARY);

    // Test a folder
    file = getReadFolder().resolveFile("dir1");
    assertTrue("folder exists", file.exists());
    assertNotSame("folder exists", file.getType(), FileType.IMAGINARY);

    // Test an unknown file
    file = getReadFolder().resolveFile("unknown-child");
    assertFalse("unknown file does not exist", file.exists());
    assertSame("unknown file does not exist", file.getType(), FileType.IMAGINARY);

    // Test an unknown file in an unknown folder
    file = getReadFolder().resolveFile("unknown-folder/unknown-child");
    assertFalse("unknown file does not exist", file.exists());
    assertSame("unknown file does not exist", file.getType(), FileType.IMAGINARY);
}
 
Example 12
public FileObject getElementForRow( final int row ) {
  if ( selectedPath == null ) {
    return null;
  }

  try {
    if ( selectedPath.getType() != FileType.FOLDER ) {
      return null;
    }

    final FileObject[] children = selectedPath.getChildren();
    int count = 0;
    for ( int i = 0; i < children.length; i++ ) {
      final FileObject child = children[i];
      if ( isShowHiddenFiles() == false && child.isHidden() ) {
        continue;
      }
      if ( child.getType() != FileType.FOLDER ) {
        if ( PublishUtil.acceptFilter( filters, child.getName().getBaseName() ) == false ) {
          continue;
        }
      }

      if ( count == row ) {
        return child;
      }
      count += 1;
    }
    return null;
  } catch ( FileSystemException fse ) {
    UncaughtExceptionsModel.getInstance().addException( fse );
    return null;
  }
}
 
Example 13
Source Project: commons-vfs   Source File: HttpFileObject.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Determines the type of this file. Must not return null. The return value of this method is cached, so the
 * implementation can be expensive.
 */
@Override
protected FileType doGetType() throws Exception {
    // Use the HEAD method to probe the file.
    final int status = this.getHeadMethod().getStatusCode();
    if (status == HttpURLConnection.HTTP_OK
            || status == HttpURLConnection.HTTP_BAD_METHOD /* method is bad, but resource exist */) {
        return FileType.FILE;
    } else if (status == HttpURLConnection.HTTP_NOT_FOUND || status == HttpURLConnection.HTTP_GONE) {
        return FileType.IMAGINARY;
    } else {
        throw new FileSystemException("vfs.provider.http/head.error", getName(), Integer.valueOf(status));
    }
}
 
Example 14
Source Project: commons-vfs   Source File: MimeFileProvider.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates the file system.
 */
@Override
protected FileSystem doCreateFileSystem(final String scheme, final FileObject file,
        final FileSystemOptions fileSystemOptions) throws FileSystemException {
    final FileName name = new LayeredFileName(scheme, file.getName(), FileName.ROOT_PATH, FileType.FOLDER);
    return new MimeFileSystem(name, file, fileSystemOptions);
}
 
Example 15
Source Project: commons-configuration   Source File: VFSFileSystem.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public OutputStream getOutputStream(final URL url) throws ConfigurationException
{
    try
    {
        final FileSystemOptions opts = getOptions(url.getProtocol());
        final FileSystemManager fsManager = VFS.getManager();
        final FileObject file = opts == null ? fsManager.resolveFile(url.toString())
                : fsManager.resolveFile(url.toString(), opts);
        // throw an exception if the target URL is a directory
        if (file == null || file.getType() == FileType.FOLDER)
        {
            throw new ConfigurationException("Cannot save a configuration to a directory");
        }
        final FileContent content = file.getContent();

        if (content == null)
        {
            throw new ConfigurationException("Cannot access content of " + url);
        }
        return content.getOutputStream();
    }
    catch (final FileSystemException fse)
    {
        throw new ConfigurationException("Unable to access " + url, fse);
    }
}
 
Example 16
Source Project: hop   Source File: S3NFileName.java    License: Apache License 2.0 5 votes vote down vote up
public S3NFileName( String scheme, String bucketId, String path, FileType type ) {
  super( scheme, path, type );

  this.bucketId = bucketId;

  if ( path.length() > 1 ) {
    this.bucketRelativePath = path.substring( 1 );
    if ( type.equals( FileType.FOLDER ) ) {
      this.bucketRelativePath += DELIMITER;
    }
  } else {
    this.bucketRelativePath = "";
  }
}
 
Example 17
Source Project: commons-vfs   Source File: VerifyingFileSelector.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Determines whether a folder should be traversed.
 */
@Override
public boolean traverseDescendents(final FileSelectInfo fileInfo) throws FileSystemException {
    // Check that the given file is a folder
    final FileObject folder = FileObjectUtils.getAbstractFileObject(fileInfo.getFile());
    assertSame(FileType.FOLDER, folder.getType());
    assertTrue(folder.isFolder());

    // Locate the info for the folder
    final String baseName = folder.getName().getBaseName();
    if (currentFolder == null) {
        assertEquals(rootFile.baseName, baseName);
        currentFolderInfo = rootFile;
    } else {
        final AbstractFileObject parent = FileObjectUtils.getAbstractFileObject(folder.getParent());
        assertSame(currentFolder, parent);

        // Locate the info for the child, and make sure it is folder
        currentFolderInfo = getChild(baseName);
        assertSame(FileType.FOLDER, currentFolderInfo.type);
    }

    // Push the folder
    stack.add(0, children);
    children = new HashSet<>(currentFolderInfo.children.keySet());
    currentFolder = folder;

    return true;
}
 
Example 18
Source Project: hop   Source File: S3FileName.java    License: Apache License 2.0 5 votes vote down vote up
public S3FileName( String scheme, String bucketId, String path, FileType type ) {
  super( scheme, path, type );

  this.bucketId = bucketId;

  if ( path.length() > 1 ) {
    this.bucketRelativePath = path.substring( 1 );
    if ( type.equals( FileType.FOLDER ) ) {
      this.bucketRelativePath += DELIMITER;
    }
  } else {
    this.bucketRelativePath = "";
  }
}
 
Example 19
Source Project: hop   Source File: S3FileObject.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void handleAttachException( String key, String bucket ) throws FileSystemException {
  SimpleEntry<String, String> newPath = fixFilePath( key, bucket );
  String keyWithDelimiter = newPath.getKey() + DELIMITER;
  try {
    s3Object = getS3Object( keyWithDelimiter, newPath.getValue() );
    s3ObjectMetadata = s3Object.getObjectMetadata();
    injectType( FileType.FOLDER );
  } catch ( AmazonS3Exception e2 ) {
    ListObjectsRequest listObjectsRequest = new ListObjectsRequest()
            .withBucketName( newPath.getValue() )
            .withPrefix( keyWithDelimiter )
            .withDelimiter( DELIMITER );
    ObjectListing ol = fileSystem.getS3Client().listObjects( listObjectsRequest );

    if ( !( ol.getCommonPrefixes().isEmpty() && ol.getObjectSummaries().isEmpty() ) ) {
      injectType( FileType.FOLDER );
    } else {
      //Folders don't really exist - they will generate a "NoSuchKey" exception
      String errorCode = e2.getErrorCode();
      // confirms key doesn't exist but connection okay
      if ( !errorCode.equals( "NoSuchKey" ) ) {
        // bubbling up other connection errors
        logger.error( "Could not get information on " + getQualifiedName(),
                e2 ); // make sure this gets printed for the user
        throw new FileSystemException( "vfs.provider/get-type.error", getQualifiedName(), e2 );
      }
    }
  }
}
 
Example 20
Source Project: hop   Source File: S3AFileName.java    License: Apache License 2.0 5 votes vote down vote up
public S3AFileName( String scheme, String bucketId, String path, FileType type ) {
  super( scheme, path, type );

  this.bucketId = bucketId;

  if ( path.length() > 1 ) {
    this.bucketRelativePath = path.substring( 1 );
    if ( type.equals( FileType.FOLDER ) ) {
      this.bucketRelativePath += DELIMITER;
    }
  } else {
    this.bucketRelativePath = "";
  }
}
 
Example 21
Source Project: pentaho-kettle   Source File: KettleFileRepository.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String[] getJobNames( ObjectId id_directory, boolean includeDeleted ) throws KettleException {
  try {
    List<String> list = new ArrayList<String>();

    RepositoryDirectoryInterface tree = loadRepositoryDirectoryTree();
    RepositoryDirectoryInterface directory = tree.findDirectory( id_directory );

    String folderName = calcDirectoryName( directory );
    FileObject folder = KettleVFS.getFileObject( folderName );

    for ( FileObject child : folder.getChildren() ) {
      if ( child.getType().equals( FileType.FILE ) ) {
        if ( !child.isHidden() || !repositoryMeta.isHidingHiddenFiles() ) {
          String name = child.getName().getBaseName();

          if ( name.endsWith( EXT_JOB ) ) {

            String jobName = name.substring( 0, name.length() - 4 );
            list.add( jobName );
          }
        }
      }
    }

    return list.toArray( new String[list.size()] );
  } catch ( Exception e ) {
    throw new KettleException(
      "Unable to get list of transformations names in folder with id : " + id_directory, e );
  }
}
 
Example 22
Source Project: pentaho-kettle   Source File: KettleFileRepository.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public List<RepositoryElementMetaInterface> getTransformationObjects( ObjectId idDirectory,
  boolean includeDeleted ) throws KettleException {

  try {
    List<RepositoryElementMetaInterface> list = new ArrayList<RepositoryElementMetaInterface>();

    RepositoryDirectoryInterface tree = loadRepositoryDirectoryTree();
    RepositoryDirectoryInterface directory = tree.findDirectory( idDirectory );

    String folderName = calcDirectoryName( directory );
    FileObject folder = KettleVFS.getFileObject( folderName );

    for ( FileObject child : folder.getChildren() ) {
      if ( child.getType().equals( FileType.FILE ) ) {
        if ( !child.isHidden() || !repositoryMeta.isHidingHiddenFiles() ) {

          String name = child.getName().getBaseName();

          if ( name.endsWith( EXT_TRANSFORMATION ) ) {

            String transName = name.substring( 0, name.length() - 4 );

            ObjectId id = new StringObjectId( calcObjectId( directory, transName, EXT_TRANSFORMATION ) );
            Date date = new Date( child.getContent().getLastModifiedTime() );
            list.add( new RepositoryObject(
              id, transName, directory, "-", date, RepositoryObjectType.TRANSFORMATION, "", false ) );
          }
        }
      }
    }

    return list;
  } catch ( Exception e ) {
    throw new KettleException( "Unable to get list of transformations in folder with id : " + idDirectory, e );
  }
}
 
Example 23
Source Project: hop   Source File: S3FileNameTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAppendRootUriWithNonDefaultPort() {
  String fooFolder = "FooFolder";
  String fooBucket = "FooBucket";
  fileName = new S3FileName( SCHEME, DELIMITER, fooFolder, FileType.FOLDER );
  String expectedUri = SCHEME + SCHEME_DELIMITER + fooFolder;
  assertEquals( expectedUri, fileName.getURI() );

  fileName = new S3FileName( SCHEME, fooBucket, fooBucket + DELIMITER + fooFolder, FileType.FOLDER );
  expectedUri = SCHEME + SCHEME_DELIMITER + fooBucket + DELIMITER + fooFolder;
  assertEquals( expectedUri, fileName.getURI() );
}
 
Example 24
Source Project: commons-vfs   Source File: HdfsFileObject.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @see org.apache.commons.vfs2.provider.AbstractFileObject#doListChildren()
 */
@Override
protected String[] doListChildren() throws Exception {
    if (this.doGetType() != FileType.FOLDER) {
        throw new FileNotFolderException(this);
    }

    final FileStatus[] files = this.hdfs.listStatus(this.path);
    final String[] children = new String[files.length];
    int i = 0;
    for (final FileStatus status : files) {
        children[i++] = status.getPath().getName();
    }
    return children;
}
 
Example 25
Source Project: hop   Source File: S3FileObjectTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDoGetTypeFolder() throws Exception {
  FileName mockFile = mock( FileName.class );
  when( s3FileObjectBucketSpy.getName() ).thenReturn( mockFile );
  when( mockFile.getPath() ).thenReturn( S3FileObject.DELIMITER );
  assertEquals( FileType.FOLDER, s3FileObjectBucketSpy.getType() );
}
 
Example 26
Source Project: commons-vfs   Source File: ContentTests.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests that input streams are cleaned up on file close.
 */
public void testByteArrayReadAll() throws Exception {
    // Get the test file
    try (final FileObject file = getReadFolder().resolveFile("file1.txt")) {
        assertEquals(FileType.FILE, file.getType());
        assertTrue(file.isFile());

        assertEquals(FILE1_CONTENT, new String(file.getContent().getByteArray()));
    }
}
 
Example 27
Source Project: commons-vfs   Source File: ContentTests.java    License: Apache License 2.0 5 votes vote down vote up
public void testGetString_String() throws Exception {
    // Get the test file
    try (final FileObject file = getReadFolder().resolveFile("file1.txt")) {
        assertEquals(FileType.FILE, file.getType());
        assertTrue(file.isFile());

        assertEquals(FILE1_CONTENT, new String(file.getContent().getString(StandardCharsets.UTF_8.name())));
    }
}
 
Example 28
Source Project: hop   Source File: S3NFileObjectTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDoGetTypeFolder() throws Exception {
  FileName mockFile = mock( FileName.class );
  when( s3FileObjectBucketSpy.getName() ).thenReturn( mockFile );
  when( mockFile.getPath() ).thenReturn( S3NFileObject.DELIMITER );
  assertEquals( FileType.FOLDER, s3FileObjectBucketSpy.getType() );
}
 
Example 29
/**
 * Returns the child of <code>parent</code> at index <code>index</code> in the parent's child array.
 * <code>parent</code> must be a node previously obtained from this data source. This should not return
 * <code>null</code> if <code>index</code> is a valid index for <code>parent</code> (that is <code>index >= 0 && index
 * < getChildCount(parent</code>)).
 *
 * @param parent
 *          a node in the tree, obtained from this data source
 * @return the child of <code>parent</code> at index <code>index</code>
 */
public Object getChild( Object parent, final int index ) {
  if ( parent instanceof RepositoryTreeRoot ) {
    final RepositoryTreeRoot root1 = (RepositoryTreeRoot) parent;
    parent = root1.getRoot();
    if ( parent == null ) {
      return null;
    }
  }

  try {
    final FileObject parElement = (FileObject) parent;
    final FileObject[] children = parElement.getChildren();
    int count = 0;
    for ( int i = 0; i < children.length; i++ ) {
      final FileObject child = children[i];
      if ( isShowFoldersOnly() && child.getType() != FileType.FOLDER ) {
        continue;
      }
      if ( isShowHiddenFiles() == false && child.isHidden() ) {
        continue;
      }
      if ( child.getType() != FileType.FOLDER
          && PublishUtil.acceptFilter( filters, child.getName().getBaseName() ) == false ) {
        continue;
      }

      if ( count == index ) {
        return child;
      }

      count += 1;
    }
    return children[index];
  } catch ( FileSystemException fse ) {
    logger.debug( "Failed", fse );
    return null;
  }
}
 
Example 30
Source Project: commons-vfs   Source File: AbstractFileObject.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates this folder, if it does not exist. Also creates any ancestor files which do not exist.
 *
 * @throws FileSystemException if an error occurs.
 */
@Override
public void createFolder() throws FileSystemException {
    synchronized (fileSystem) {
        // VFS-210: we create a folder only if it does not already exist. So this check should be safe.
        if (getType().hasChildren()) {
            // Already exists as correct type
            return;
        }
        if (getType() != FileType.IMAGINARY) {
            throw new FileSystemException("vfs.provider/create-folder-mismatched-type.error", fileName);
        }
        /*
         * VFS-210: checking for writeable is not always possible as the security constraint might be more complex
         * if (!isWriteable()) { throw new FileSystemException("vfs.provider/create-folder-read-only.error", name);
         * }
         */

        // Traverse up the hierarchy and make sure everything is a folder
        final FileObject parent = getParent();
        if (parent != null) {
            parent.createFolder();
        }

        try {
            // Create the folder
            doCreateFolder();

            // Update cached info
            handleCreate(FileType.FOLDER);
        } catch (final RuntimeException re) {
            throw re;
        } catch (final Exception exc) {
            throw new FileSystemException("vfs.provider/create-folder.error", fileName, exc);
        }
    }
}