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

The following examples show how to use org.apache.commons.vfs2.FileObject#isReadable() . 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: FileObjectResourceData.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 2
Source File: JobEntryTalendJobExec.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
public Result execute( Result previousResult, int nr ) {
  Result result = previousResult;
  result.setResult( false );

  if ( filename != null ) {
    String realFilename = getRealFilename();
    try {
      FileObject file = KettleVFS.getFileObject( realFilename, this );
      if ( file.exists() && file.isReadable() ) {
        result = executeTalenJob( file, result, nr );
      } else {
        logDetailed( BaseMessages.getString( PKG, "JobEntryTalendJobExec.File_Does_Not_Exist", realFilename ) );
      }
    } catch ( Exception e ) {
      result.setNrErrors( 1 );
      logError(
        BaseMessages.getString( PKG, "JobEntryTalendJobExec.ERROR_0004_IO_Exception", e.getMessage() ), e );
    }
  } else {
    result.setNrErrors( 1 );
    logError( BaseMessages.getString( PKG, "JobEntryTalendJobExec.ERROR_0005_No_Filename_Defined" ) );
  }

  return result;
}
 
Example 3
Source File: HopVfsFileDialog.java    From hop with 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 4
Source File: ActionFileExists.java    From hop with Apache License 2.0 5 votes vote down vote up
public Result execute( Result previousResult, int nr ) {
  Result result = previousResult;
  result.setResult( false );
  result.setNrErrors( 0 );

  if ( filename != null ) {

    String realFilename = getRealFilename();
    try {
      FileObject file = HopVfs.getFileObject( realFilename );
      if ( file.exists() && file.isReadable() ) {
        logDetailed( BaseMessages.getString( PKG, "ActionFileExists.File_Exists", realFilename ) );
        result.setResult( true );
      } else {
        logDetailed( BaseMessages.getString( PKG, "ActionFileExists.File_Does_Not_Exist", realFilename ) );
      }
    } catch ( Exception e ) {
      result.setNrErrors( 1 );
      logError( BaseMessages.getString( PKG, "ActionFileExists.ERROR_0004_IO_Exception", e.getMessage() ), e );
    }
  } else {
    result.setNrErrors( 1 );
    logError( BaseMessages.getString( PKG, "ActionFileExists.ERROR_0005_No_Filename_Defined" ) );
  }

  return result;
}
 
Example 5
Source File: PubmedArchiveCollectionReader.java    From bluima with 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 6
Source File: PubmedCentralCollectionReader.java    From bluima with 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 7
Source File: PubmedArchiveCollectionReader2.java    From bluima with 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 8
Source File: JobEntryFileExists.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public Result execute( Result previousResult, int nr ) {
  Result result = previousResult;
  result.setResult( false );
  result.setNrErrors( 0 );

  if ( filename != null ) {
    //Set Embedded NamedCluter MetatStore Provider Key so that it can be passed to VFS
    if ( parentJobMeta.getNamedClusterEmbedManager() != null ) {
      parentJobMeta.getNamedClusterEmbedManager()
        .passEmbeddedMetastoreKey( this, parentJobMeta.getEmbeddedMetastoreProviderKey() );
    }

    String realFilename = getRealFilename();
    try {
      FileObject file = KettleVFS.getFileObject( realFilename, this );
      if ( file.exists() && file.isReadable() ) {
        logDetailed( BaseMessages.getString( PKG, "JobEntryFileExists.File_Exists", realFilename ) );
        result.setResult( true );
      } else {
        logDetailed( BaseMessages.getString( PKG, "JobEntryFileExists.File_Does_Not_Exist", realFilename ) );
      }
    } catch ( Exception e ) {
      result.setNrErrors( 1 );
      logError( BaseMessages.getString( PKG, "JobEntryFileExists.ERROR_0004_IO_Exception", e.getMessage() ), e );
    }
  } else {
    result.setNrErrors( 1 );
    logError( BaseMessages.getString( PKG, "JobEntryFileExists.ERROR_0005_No_Filename_Defined" ) );
  }

  return result;
}
 
Example 9
Source File: ResourceAgent.java    From spoofax with Apache License 2.0 5 votes vote down vote up
@Override public boolean readable(String fn) {
    try {
        final FileObject resource = resourceService.resolve(workingDir, fn);
        return resource.isReadable();
    } catch(FileSystemException e) {
        throw new RuntimeException("Could not check if file " + fn + " is readable", e);
    }
}
 
Example 10
Source File: ActionFilesExist.java    From hop with Apache License 2.0 4 votes vote down vote up
public Result execute( Result previousResult, int nr ) {
  Result result = previousResult;
  result.setResult( false );
  result.setNrErrors( 0 );
  int missingfiles = 0;
  int nrErrors = 0;

  // see PDI-10270 for details
  boolean oldBehavior =
    "Y".equalsIgnoreCase( getVariable( Const.HOP_COMPATIBILITY_SET_ERROR_ON_SPECIFIC_WORKFLOW_ACTIONS, "N" ) );

  if ( arguments != null ) {
    for ( int i = 0; i < arguments.length && !parentWorkflow.isStopped(); i++ ) {
      FileObject file = null;

      try {
        String realFilefoldername = environmentSubstitute( arguments[ i ] );
        file = HopVfs.getFileObject( realFilefoldername );

        if ( file.exists() && file.isReadable() ) { // TODO: is it needed to check file for readability?
          if ( log.isDetailed() ) {
            logDetailed( BaseMessages.getString( PKG, "ActionFilesExist.File_Exists", realFilefoldername ) );
          }
        } else {
          missingfiles++;
          if ( log.isDetailed() ) {
            logDetailed( BaseMessages.getString(
              PKG, "ActionFilesExist.File_Does_Not_Exist", realFilefoldername ) );
          }
        }

      } catch ( Exception e ) {
        nrErrors++;
        missingfiles++;
        logError( BaseMessages.getString( PKG, "ActionFilesExist.ERROR_0004_IO_Exception", e.toString() ), e );
      } finally {
        if ( file != null ) {
          try {
            file.close();
            file = null;
          } catch ( IOException ex ) { /* Ignore */
          }
        }
      }
    }

  }

  result.setNrErrors( nrErrors );

  if ( oldBehavior ) {
    result.setNrErrors( missingfiles );
  }

  if ( missingfiles == 0 ) {
    result.setResult( true );
  }

  return result;
}
 
Example 11
Source File: AbstractReader.java    From bluima with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        FileSystemManager fsManager = VFS.getManager();
        final Pattern pmidP = Pattern
                .compile("<PMID Version=\"\\d+\">(.*?)</PMID>");

        DirectoryIterator it = new DefaultDirectoryIterator();
        it.setDirectory(new File(
        // "/Volumes/HDD2/ren_scratch/Dropbox/dev_shared/tmp3/"));
                "/Volumes/simulation/nip/pubmed_gzip/medline14/"));
        it.setExtensionFilter("xml.gz");
        it.setRecursive(false);
        Iterator<File> fit = it.iterator();

        while (fit.hasNext()) {
            File f = fit.next();

            // "medline14n0456.xml.gz" --> 456
            int archiveId = parseInt(f.getName().substring(10, 14));
            if (archiveId > 755) {

                try {
                    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();

                        String articles = IOUtils.toString(fc.getInputStream(),
                                "UTF-8");
                        String[] split = articles.split("<MedlineCitation");

                        for (int i = 1; i < split.length - 1; i++) {

                            String article = "<MedlineCitation" + split[i];
                            if (!article.startsWith("<MedlineCitationSet>")) {

                                Matcher matcher = pmidP.matcher(article);
                                if (matcher.find()) {
                                    int pmid = Integer.parseInt(matcher
                                            .group(1));
                                    String filePath = StructuredDirectory
                                            .getFilePath(pmid, "xml");
                                    File file = new File(
                                    // "/Volumes/HDD2/ren_scratch/Dropbox/dev_shared/tmp3/xml/"
                                            "/Volumes/simulation/nip/pubmed_xml/"
                                                    + filePath);
                                    file.getParentFile().mkdirs();

                                    // System.out.println(pmid);
                                    FileOutputStream out = new FileOutputStream(
                                            file);
                                    IOUtils.write(article, out);
                                    IOUtils.closeQuietly(out);
                                } else {
                                    System.err
                                            .println("could not extract pmid from "
                                                    + article);
                                }
                            }
                        }
                    }
                } catch (Throwable e) {
                    LOG.error("error with " + f.getName(), e);
                }
            }
        }
    }
 
Example 12
Source File: SchemaResolver.java    From pentaho-reporting with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static String resolveSchema( final ResourceManager resourceManager,
                                    final ResourceKey contextKey,
                                    String catalogUrl )
  throws FileSystemException {
  final FileSystemManager fsManager = VFS.getManager();
  if ( fsManager == null ) {
    throw Util.newError( "Cannot get virtual file system manager" );
  }

  // Workaround VFS bug.
  if ( catalogUrl.startsWith( "file://localhost" ) ) {
    catalogUrl = catalogUrl.substring( "file://localhost".length() );
  }
  if ( catalogUrl.startsWith( "file:" ) ) {
    catalogUrl = catalogUrl.substring( "file:".length() );
  }

  try {
    final File catalogFile = new File( catalogUrl ).getCanonicalFile();
    final FileObject file = fsManager.toFileObject( catalogFile );
    if ( file.isReadable() ) {
      return catalogFile.getPath();
    }
  } catch ( FileSystemException fse ) {
    logger.info( "Failed to resolve schema file '" + catalogUrl + "' as local file. Treating file as non-readable.",
      fse );
  } catch ( IOException e ) {
    logger
      .info( "Failed to resolve schema file '" + catalogUrl + "' as local file. Treating file as non-readable.", e );
  }

  if ( contextKey == null ) {
    return catalogUrl;
  }

  final File contextAsFile = getContextAsFile( contextKey );
  if ( contextAsFile == null ) {
    return catalogUrl;
  }

  final File resolvedFile = new File( contextAsFile.getParentFile(), catalogUrl );
  if ( resolvedFile.isFile() && resolvedFile.canRead() ) {
    return resolvedFile.getAbsolutePath();
  }

  return catalogUrl;
}
 
Example 13
Source File: ShowProperties.java    From commons-vfs with Apache License 2.0 4 votes vote down vote up
public static void main(final String[] args) {
    if (args.length == 0) {
        System.err.println("Please pass the name of a file as parameter.");
        System.err.println("e.g. java org.apache.commons.vfs2.example.ShowProperties LICENSE.txt");
        return;
    }
    for (final String arg : args) {
        try {
            final FileSystemManager mgr = VFS.getManager();
            System.out.println();
            System.out.println("Parsing: " + arg);
            final FileObject file = mgr.resolveFile(arg);
            System.out.println("URL: " + file.getURL());
            System.out.println("getName(): " + file.getName());
            System.out.println("BaseName: " + file.getName().getBaseName());
            System.out.println("Extension: " + file.getName().getExtension());
            System.out.println("Path: " + file.getName().getPath());
            System.out.println("Scheme: " + file.getName().getScheme());
            System.out.println("URI: " + file.getName().getURI());
            System.out.println("Root URI: " + file.getName().getRootURI());
            System.out.println("Parent: " + file.getName().getParent());
            System.out.println("Type: " + file.getType());
            System.out.println("Exists: " + file.exists());
            System.out.println("Readable: " + file.isReadable());
            System.out.println("Writeable: " + file.isWriteable());
            System.out.println("Root path: " + file.getFileSystem().getRoot().getName().getPath());
            if (file.exists()) {
                if (file.getType().equals(FileType.FILE)) {
                    System.out.println("Size: " + file.getContent().getSize() + " bytes");
                } else if (file.getType().equals(FileType.FOLDER) && file.isReadable()) {
                    final FileObject[] children = file.getChildren();
                    System.out.println("Directory with " + children.length + " files");
                    for (int iterChildren = 0; iterChildren < children.length; iterChildren++) {
                        System.out.println("#" + iterChildren + ": " + children[iterChildren].getName());
                        if (iterChildren > SHOW_MAX) {
                            break;
                        }
                    }
                }
                System.out.println("Last modified: "
                        + DateFormat.getInstance().format(new Date(file.getContent().getLastModifiedTime())));
            } else {
                System.out.println("The file does not exist");
            }
            file.close();
        } catch (final FileSystemException ex) {
            ex.printStackTrace();
        }
    }
}
 
Example 14
Source File: JobEntryFilesExist.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
public Result execute( Result previousResult, int nr ) {
  Result result = previousResult;
  result.setResult( false );
  result.setNrErrors( 0 );
  int missingfiles = 0;
  int nrErrors = 0;

  // see PDI-10270 for details
  boolean oldBehavior =
    "Y".equalsIgnoreCase( getVariable( Const.KETTLE_COMPATIBILITY_SET_ERROR_ON_SPECIFIC_JOB_ENTRIES, "N" ) );

  if ( arguments != null ) {
    for ( int i = 0; i < arguments.length && !parentJob.isStopped(); i++ ) {
      FileObject file = null;

      try {
        String realFilefoldername = environmentSubstitute( arguments[i] );
        //Set Embedded NamedCluter MetatStore Provider Key so that it can be passed to VFS
        if ( parentJobMeta.getNamedClusterEmbedManager() != null ) {
          parentJobMeta.getNamedClusterEmbedManager()
            .passEmbeddedMetastoreKey( this, parentJobMeta.getEmbeddedMetastoreProviderKey() );
        }
        file = KettleVFS.getFileObject( realFilefoldername, this );

        if ( file.exists() && file.isReadable() ) { // TODO: is it needed to check file for readability?
          if ( log.isDetailed() ) {
            logDetailed( BaseMessages.getString( PKG, "JobEntryFilesExist.File_Exists", realFilefoldername ) );
          }
        } else {
          missingfiles++;
          if ( log.isDetailed() ) {
            logDetailed( BaseMessages.getString(
              PKG, "JobEntryFilesExist.File_Does_Not_Exist", realFilefoldername ) );
          }
        }

      } catch ( Exception e ) {
        nrErrors++;
        missingfiles++;
        logError( BaseMessages.getString( PKG, "JobEntryFilesExist.ERROR_0004_IO_Exception", e.toString() ), e );
      } finally {
        if ( file != null ) {
          try {
            file.close();
            file = null;
          } catch ( IOException ex ) { /* Ignore */
          }
        }
      }
    }

  }

  result.setNrErrors( nrErrors );

  if ( oldBehavior ) {
    result.setNrErrors( missingfiles );
  }

  if ( missingfiles == 0 ) {
    result.setResult( true );
  }

  return result;
}