Java Code Examples for org.apache.commons.vfs2.FileObject#getParent()
The following examples show how to use
org.apache.commons.vfs2.FileObject#getParent() .
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: VFSFileProvider.java From pentaho-kettle with Apache License 2.0 | 6 votes |
@Override public VFSFile getFile( VFSFile file ) { try { FileObject fileObject = KettleVFS .getFileObject( file.getPath(), new Variables(), VFSHelper.getOpts( file.getPath(), file.getConnection() ) ); if ( !fileObject.exists() ) { return null; } String parent = null; if ( fileObject.getParent() != null && fileObject.getParent().getName() != null ) { parent = fileObject.getParent().getName().getURI(); } else { parent = fileObject.getURL().getProtocol() + "://"; } if ( fileObject.getType().equals( FileType.FOLDER ) ) { return VFSDirectory.create( parent, fileObject, null, file.getDomain() ); } else { return VFSFile.create( parent, fileObject, null, file.getDomain() ); } } catch ( KettleFileException | FileSystemException e ) { // File does not exist } return null; }
Example 2
Source File: JunctionTests.java From commons-vfs with Apache License 2.0 | 6 votes |
/** * Checks ancestors are created when a junction is created. */ public void testAncestors() throws Exception { final FileSystem fs = getManager().createVirtualFileSystem("vfs://").getFileSystem(); final FileObject baseDir = getBaseDir(); // Make sure the file at the junction point and its ancestors do not exist FileObject file = fs.resolveFile("/a/b"); assertFalse(file.exists()); file = file.getParent(); assertFalse(file.exists()); file = file.getParent(); assertFalse(file.exists()); // Add the junction fs.addJunction("/a/b", baseDir); // Make sure the file at the junction point and its ancestors exist file = fs.resolveFile("/a/b"); assertTrue("Does not exist", file.exists()); file = file.getParent(); assertTrue("Does not exist", file.exists()); file = file.getParent(); assertTrue("Does not exist", file.exists()); }
Example 3
Source File: DefaultFileMonitor.java From commons-vfs with Apache License 2.0 | 6 votes |
/** * Removes a file from being monitored. * * @param file The FileObject to remove from monitoring. */ @Override public void removeFile(final FileObject file) { synchronized (this.monitorMap) { final FileName fn = file.getName(); if (this.monitorMap.get(fn) != null) { FileObject parent; try { parent = file.getParent(); } catch (final FileSystemException fse) { parent = null; } this.monitorMap.remove(fn); if (parent != null) { // Not the root final FileMonitorAgent parentAgent = this.monitorMap.get(parent.getName()); if (parentAgent != null) { parentAgent.resetChildrenList(); } } } } }
Example 4
Source File: ProjectsUtil.java From hop with Apache License 2.0 | 6 votes |
private static boolean isInSubDirectory( FileObject file, FileObject directory ) throws FileSystemException { String filePath = file.getName().getPath(); String directoryPath = directory.getName().getPath(); // Same? if ( filePath.equals( directoryPath ) ) { System.out.println( "Found " + filePath + " in directory " + directoryPath ); return true; } if ( filePath.startsWith( directoryPath ) ) { return true; } FileObject parent = file.getParent(); if ( parent != null && isInSubDirectory( parent, directory ) ) { return true; } return false; }
Example 5
Source File: RepositoryTreeModel.java From pentaho-reporting with GNU Lesser General Public License v2.1 | 6 votes |
public TreePath getTreePathForSelection( FileObject selectedFolder, final String selection ) throws FileSystemException { if ( root.getRoot() == null ) { return null; } if ( root.getRoot().equals( selectedFolder ) ) { return new TreePath( root ); } final LinkedList<Object> list = new LinkedList<Object>(); while ( selectedFolder != null ) { list.add( 0, selectedFolder ); final FileObject parent = selectedFolder.getParent(); if ( selectedFolder.equals( parent ) ) { break; } if ( root.getRoot().equals( parent ) ) { break; } selectedFolder = parent; } list.add( 0, root ); return new TreePath( list.toArray() ); }
Example 6
Source File: Resource.java From commons-vfs with Apache License 2.0 | 5 votes |
/** * Creates a new instance. * * @param root The code source FileObject. * @param resource The resource of the FileObject. */ public Resource(final String name, final FileObject root, final FileObject resource) throws FileSystemException { this.root = root; this.resource = resource; packageFolder = resource.getParent(); final int pos = name.lastIndexOf('/'); if (pos == -1) { packageName = null; } else { packageName = name.substring(0, pos).replace('/', '.'); } }
Example 7
Source File: HopVfs.java From hop with Apache License 2.0 | 5 votes |
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 8
Source File: KettleVFS.java From pentaho-kettle with Apache License 2.0 | 5 votes |
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, "KettleVFS.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 9
Source File: ConfigBasedProjectService.java From spoofax with Apache License 2.0 | 5 votes |
private IProject findProject(FileObject resource) { try { FileObject dir = (resource.isFolder() ? resource : resource.getParent()); while(dir != null) { FileName name = dir.getName(); if(projectConfigService.available(dir)) { final ConfigRequest<? extends IProjectConfig> configRequest = projectConfigService.get(dir); if(!configRequest.valid()) { logger.error("Errors occurred when retrieving project configuration from project directory {}", dir); configRequest.reportErrors(new StreamMessagePrinter(sourceTextService, false, false, logger)); } final IProjectConfig config = configRequest.config(); if(config == null) { logger.error("Could not retrieve project configuration from project directory {}", dir); return null; } final IProject project = new Project(dir, config); IProject prevProject; if((prevProject = projects.putIfAbsent(name, project)) != null) { logger.warn("Project with location {} already exists", name); return prevProject; } return project; } dir = dir.getParent(); } } catch(FileSystemException e) { logger.error("Error while searching for project configuration.",e); } logger.warn("No project configuration file was found for {}.",resource); return null; }
Example 10
Source File: DefaultURLStreamHandler.java From commons-vfs with Apache License 2.0 | 5 votes |
@Override protected void parseURL(final URL u, final String spec, final int start, final int limit) { try { final FileObject old = context.resolveFile(u.toExternalForm(), fileSystemOptions); FileObject newURL; if (start > 0 && spec.charAt(start - 1) == ':') { newURL = context.resolveFile(old, spec, fileSystemOptions); } else { if (old.isFile() && old.getParent() != null) { // for files we have to resolve relative newURL = old.getParent().resolveFile(spec); } else { newURL = old.resolveFile(spec); } } final String url = newURL.getName().getURI(); final StringBuilder filePart = new StringBuilder(); final String protocolPart = UriParser.extractScheme(context.getFileSystemManager().getSchemes(), url, filePart); setURL(u, protocolPart, "", -1, null, null, filePart.toString(), null, null); } catch (final FileSystemException fse) { // This is rethrown to MalformedURLException in URL anyway throw new RuntimeException(fse.getMessage()); } }
Example 11
Source File: RepositoryOpenDialog.java From pentaho-reporting with GNU Lesser General Public License v2.1 | 5 votes |
private ComboBoxModel createLocationModel( final FileObject selectedFolder ) { if ( fileSystemRoot == null ) { return new DefaultComboBoxModel(); } try { final ArrayList<FileObject> list = new ArrayList<FileObject>(); FileObject folder = selectedFolder; while ( folder != null ) { if ( fileSystemRoot.equals( folder ) ) { break; } if ( folder.getType() != FileType.FILE ) { list.add( folder ); } final FileObject parent = folder.getParent(); if ( folder.equals( parent ) ) { // protect yourself against infinite loops .. break; } folder = parent; } list.add( fileSystemRoot ); final DefaultComboBoxModel model = new DefaultComboBoxModel( list.toArray() ); model.setSelectedItem( list.get( 0 ) ); return model; } catch ( FileSystemException e ) { return new DefaultComboBoxModel(); } }
Example 12
Source File: VFSClassloaderUtil.java From metron with Apache License 2.0 | 5 votes |
/** * Resolve a set of URIs into FileObject objects. * This is not recursive. The URIs can refer directly to a file or directory or an optional regex at the end. * (NOTE: This is NOT a glob). * @param vfs The file system manager to use to resolve URIs * @param uris comma separated URIs and URI + globs * @return * @throws FileSystemException */ static FileObject[] resolve(FileSystemManager vfs, String uris) throws FileSystemException { if (uris == null) { return new FileObject[0]; } ArrayList<FileObject> classpath = new ArrayList<>(); for (String path : uris.split(",")) { path = path.trim(); if (path.equals("")) { continue; } FileObject fo = vfs.resolveFile(path); switch (fo.getType()) { case FILE: case FOLDER: classpath.add(fo); break; case IMAGINARY: // assume its a pattern String pattern = fo.getName().getBaseName(); if (fo.getParent() != null && fo.getParent().getType() == FileType.FOLDER) { FileObject[] children = fo.getParent().getChildren(); for (FileObject child : children) { if (child.getType() == FileType.FILE && child.getName().getBaseName().matches(pattern)) { classpath.add(child); } } } else { LOG.warn("ignoring classpath entry {}", fo); } break; default: LOG.warn("ignoring classpath entry {}", fo); break; } } return classpath.toArray(new FileObject[classpath.size()]); }
Example 13
Source File: PipelineUnitTest.java From hop with Apache License 2.0 | 4 votes |
public void setRelativeFilename( String referencePipelineFilename ) throws HopException { // Build relative path whenever a pipeline is saved // if ( StringUtils.isEmpty( referencePipelineFilename ) ) { return; // nothing we can do } // Set the filename to be safe // setPipelineFilename( referencePipelineFilename ); String base = getBasePath(); if ( StringUtils.isEmpty( base ) ) { base = getVariable( DataSetConst.VARIABLE_UNIT_TESTS_BASE_PATH ); } base = environmentSubstitute( base ); if ( StringUtils.isNotEmpty( base ) ) { // See if the base path is present in the filename // Then replace the filename // try { FileObject baseFolder = HopVfs.getFileObject( base ); FileObject pipelineFile = HopVfs.getFileObject( referencePipelineFilename ); FileObject parent = pipelineFile.getParent(); while ( parent != null ) { if ( parent.equals( baseFolder ) ) { // Here we are, we found the base folder in the pipeline file // String pipelineFileString = pipelineFile.toString(); String baseFolderName = parent.toString(); // Final validation & unit test filename correction // if ( pipelineFileString.startsWith( baseFolderName ) ) { String relativeFile = pipelineFileString.substring( baseFolderName.length() ); String relativeFilename; if ( relativeFile.startsWith( "/" ) ) { relativeFilename = "." + relativeFile; } else { relativeFilename = "./" + relativeFile; } // Set the pipeline filename to the relative path // setPipelineFilename( relativeFilename ); LogChannel.GENERAL.logDetailed( "Unit test '" + getName() + "' : saved relative path to pipeline: " + relativeFilename ); } } parent = parent.getParent(); } } catch ( Exception e ) { throw new HopException( "Error calculating relative unit test file path", e ); } } }
Example 14
Source File: DistributedCacheUtilImpl.java From pentaho-hadoop-shims with Apache License 2.0 | 4 votes |
/** * Extract a zip archive to a directory. * * @param archive Zip archive to extract * @param dest Destination directory. This must not exist! * @return Directory the zip was extracted into * @throws IllegalArgumentException when the archive file does not exist or the destination directory already exists * @throws IOException * @throws KettleFileException */ public FileObject extract( FileObject archive, FileObject dest ) throws IOException, KettleFileException { if ( !archive.exists() ) { throw new IllegalArgumentException( "archive does not exist: " + archive.getURL().getPath() ); } if ( dest.exists() ) { throw new IllegalArgumentException( "destination already exists" ); } dest.createFolder(); try { byte[] buffer = new byte[ DEFAULT_BUFFER_SIZE ]; int len = 0; ZipInputStream zis = new ZipInputStream( archive.getContent().getInputStream() ); try { ZipEntry ze; while ( ( ze = zis.getNextEntry() ) != null ) { FileObject entry = KettleVFS.getFileObject( dest + Const.FILE_SEPARATOR + ze.getName() ); FileObject parent = entry.getParent(); if ( parent != null ) { parent.createFolder(); } if ( ze.isDirectory() ) { entry.createFolder(); continue; } OutputStream os = KettleVFS.getOutputStream( entry, false ); try { while ( ( len = zis.read( buffer ) ) > 0 ) { os.write( buffer, 0, len ); } } finally { if ( os != null ) { os.close(); } } } } finally { if ( zis != null ) { zis.close(); } } } catch ( Exception ex ) { // Try to clean up the temp directory and all files if ( !deleteDirectory( dest ) ) { throw new KettleFileException( "Could not clean up temp dir after error extracting", ex ); } throw new KettleFileException( "error extracting archive", ex ); } return dest; }
Example 15
Source File: DataSetHelper.java From pentaho-pdi-dataset with Apache License 2.0 | 4 votes |
private void saveUnitTest( MetaStoreFactory<TransUnitTest> testFactory, TransUnitTest unitTest, TransMeta transMeta ) throws MetaStoreException { // Build relative path whenever a transformation is saved // if ( StringUtils.isNotEmpty( transMeta.getFilename() ) ) { // Set the filename to be safe // unitTest.setTransFilename( transMeta.getFilename() ); String basePath = unitTest.getBasePath(); if ( StringUtils.isEmpty( basePath ) ) { basePath = transMeta.getVariable( DataSetConst.VARIABLE_UNIT_TESTS_BASE_PATH ); } basePath = transMeta.environmentSubstitute( basePath ); if ( StringUtils.isNotEmpty( basePath ) ) { // See if the basePath is present in the filename // Then replace the filename // try { FileObject baseFolder = KettleVFS.getFileObject( basePath ); FileObject transFile = KettleVFS.getFileObject( transMeta.getFilename() ); FileObject parent = transFile.getParent(); while ( parent != null ) { if ( parent.equals( baseFolder ) ) { // Here we are, we found the base folder in the transformation file // String transFilename = transFile.toString(); String baseFoldername = parent.toString(); // Final validation & unit test filename correction // if ( transFilename.startsWith( baseFoldername ) ) { String relativeFile = transFilename.substring( baseFoldername.length() ); String filename; if ( relativeFile.startsWith( "/" ) ) { filename = "." + relativeFile; } else { filename = "./" + relativeFile; } // Set the transformation filename to the relative path // unitTest.setTransFilename( filename ); LogChannel.GENERAL.logBasic( "Unit test '" + unitTest.getName() + "' : Saved relative path to transformation: " + filename ); } } parent = parent.getParent(); } } catch ( Exception e ) { throw new MetaStoreException( "Error calculating relative unit test file path", e ); } } } testFactory.saveElement( unitTest ); }
Example 16
Source File: GPLoad.java From pentaho-kettle with Apache License 2.0 | 4 votes |
/** * Returns the path to the pathToFile. It should be the same as what was passed but this method will check the file * system to see if the path is valid. * * @param pathToFile * Path to the file to verify. * @param exceptionMessage * The message to use when the path is not provided. * @param checkExistence * When true the path's existence will be verified. * @return * @throws KettleException */ private String getPath( String pathToFile, String exceptionMessage, boolean checkExistenceOfFile ) throws KettleException { // Make sure the path is not empty if ( Utils.isEmpty( pathToFile ) ) { throw new KettleException( exceptionMessage ); } // make sure the variable substitution is not empty pathToFile = environmentSubstitute( pathToFile ).trim(); if ( Utils.isEmpty( pathToFile ) ) { throw new KettleException( exceptionMessage ); } FileObject fileObject = KettleVFS.getFileObject( pathToFile, getTransMeta() ); try { // we either check the existence of the file if ( checkExistenceOfFile ) { if ( !fileObject.exists() ) { throw new KettleException( BaseMessages.getString( PKG, "GPLoad.Execption.FileDoesNotExist", pathToFile ) ); } } else { // if the file does not have to exist, the parent, or source folder, does. FileObject parentFolder = fileObject.getParent(); if ( parentFolder.exists() ) { return KettleVFS.getFilename( fileObject ); } else { throw new KettleException( BaseMessages.getString( PKG, "GPLoad.Exception.DirectoryDoesNotExist", parentFolder.getURL().getPath() ) ); } } // if Windows is the OS if ( Const.getOS().startsWith( "Windows" ) ) { return addQuotes( pathToFile ); } else { return KettleVFS.getFilename( fileObject ); } } catch ( FileSystemException fsex ) { throw new KettleException( BaseMessages.getString( PKG, "GPLoad.Exception.GPLoadCommandBuild", fsex.getMessage() ) ); } }
Example 17
Source File: ExcelOutput.java From pentaho-kettle with Apache License 2.0 | 4 votes |
private boolean createParentFolder( FileObject file ) { boolean retval = true; // Check for parent folder FileObject parentfolder = null; try { // Get parent folder parentfolder = file.getParent(); if ( parentfolder.exists() ) { if ( isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "ExcelOutput.Log.ParentFolderExist", parentfolder .getName().toString() ) ); } } else { if ( isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "ExcelOutput.Log.ParentFolderNotExist", parentfolder .getName().toString() ) ); } if ( meta.isCreateParentFolder() ) { parentfolder.createFolder(); if ( isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "ExcelOutput.Log.ParentFolderCreated", parentfolder .getName().toString() ) ); } } else { retval = false; logError( BaseMessages.getString( PKG, "ExcelOutput.Error.CanNotFoundParentFolder", parentfolder .getName().toString(), file.getName().toString() ) ); } } } catch ( Exception e ) { retval = false; logError( BaseMessages.getString( PKG, "ExcelOutput.Log.CouldNotCreateParentFolder", parentfolder .getName().toString() ) ); } finally { if ( parentfolder != null ) { try { parentfolder.close(); } catch ( Exception ex ) { // Ignore } } } return retval; }
Example 18
Source File: SpoofaxIgnoresSelector.java From spoofax with Apache License 2.0 | 4 votes |
@Override public boolean traverseDescendents(FileSelectInfo fileInfo) throws Exception { final int depth = fileInfo.getDepth(); final FileObject resource = fileInfo.getFile(); final FileName name = resource.getName(); final String base = name.getBaseName(); switch(depth) { case 1: switch(base) { case "include": // Spoofax/Stratego case ".cache": // Spoofax/Stratego case "bin": // Eclipse case ".settings": // Eclipse case "target": // Maven case ".mvn": // Maven case "build": // Gradle case ".gradle": // Gradle case "out": // IntelliJ case ".idea": // IntelliJ case ".git": // Git return false; } break; case 3: switch(base) { // Ignore editor/java/trans and src-gen/stratego-java/trans. case "trans": { final FileObject parent1 = resource.getParent(); if(parent1 != null) { final String parent1base = parent1.getName().getBaseName(); if(parent1base.equals("java") || parent1base.equals("stratego-java")) { final FileObject parent2 = parent1.getParent(); if(parent2 != null) { final String parent2base = parent2.getName().getBaseName(); return !(parent2base.equals("editor") || parent2base.equals("src-gen")); } } } break; } } break; } return true; }
Example 19
Source File: ExcelOutput.java From hop with Apache License 2.0 | 4 votes |
private boolean createParentFolder( FileObject file ) { boolean retval = true; // Check for parent folder FileObject parentfolder = null; try { // Get parent folder parentfolder = file.getParent(); if ( parentfolder.exists() ) { if ( isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "ExcelOutput.Log.ParentFolderExist", parentfolder .getName().toString() ) ); } } else { if ( isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "ExcelOutput.Log.ParentFolderNotExist", parentfolder .getName().toString() ) ); } if ( meta.isCreateParentFolder() ) { parentfolder.createFolder(); if ( isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "ExcelOutput.Log.ParentFolderCreated", parentfolder .getName().toString() ) ); } } else { retval = false; logError( BaseMessages.getString( PKG, "ExcelOutput.Error.CanNotFoundParentFolder", parentfolder .getName().toString(), file.getName().toString() ) ); } } } catch ( Exception e ) { retval = false; logError( BaseMessages.getString( PKG, "ExcelOutput.Log.CouldNotCreateParentFolder", parentfolder .getName().toString() ) ); } finally { if ( parentfolder != null ) { try { parentfolder.close(); } catch ( Exception ex ) { // Ignore } } } return retval; }
Example 20
Source File: JobEntryPGPDecryptFiles.java From pentaho-kettle with Apache License 2.0 | 4 votes |
private boolean CreateDestinationFolder( FileObject filefolder ) { FileObject folder = null; try { if ( destination_is_a_file ) { folder = filefolder.getParent(); } else { folder = filefolder; } if ( !folder.exists() ) { if ( create_destination_folder ) { if ( isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "JobPGPDecryptFiles.Log.FolderNotExist", folder .getName().toString() ) ); } folder.createFolder(); if ( isDetailed() ) { logDetailed( BaseMessages.getString( PKG, "JobPGPDecryptFiles.Log.FolderWasCreated", folder .getName().toString() ) ); } } else { logError( BaseMessages.getString( PKG, "JobPGPDecryptFiles.Log.FolderNotExist", folder .getName().toString() ) ); return false; } } return true; } catch ( Exception e ) { logError( BaseMessages.getString( PKG, "JobPGPDecryptFiles.Log.CanNotCreateParentFolder", folder .getName().toString() ), e ); } finally { if ( folder != null ) { try { folder.close(); } catch ( Exception ex ) { /* Ignore */ } } } return false; }