Java Code Examples for org.eclipse.core.resources.IContainer#members()

The following examples show how to use org.eclipse.core.resources.IContainer#members() . 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: ResourceExtensionContentProvider.java    From translationstudio8 with GNU General Public License v2.0 6 votes vote down vote up
public boolean hasChildren(Object element) {
	try {
		if (element instanceof IContainer) {
			IContainer c = (IContainer) element;
			if (!c.isAccessible())
				return false;
			return c.members().length > 0;
		}
	} catch (CoreException ex) {
		WorkbenchNavigatorPlugin.getDefault().getLog().log(
				new Status(IStatus.ERROR, WorkbenchNavigatorPlugin.PLUGIN_ID, 0, ex.getMessage(), ex));
		return false;
	}

	return super.hasChildren(element);
}
 
Example 2
Source File: ProjectFileTracking.java    From texlipse with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Recursively scans the given container for files and adds them to the
 * given map, along with their time stamps. This does not list the
 * folders it recurses into.
 *
 * @param container container to scan for files
 * @param nameMap map of file paths to put the files and time stamps into
 * @param monitor progress monitor
 * @throws CoreException if an error occurs
 */
private void recursiveScanFiles(final IContainer container,
        final Map<IPath, Long> nameMap, IProgressMonitor monitor)
                throws CoreException {
    IResource[] res = container.members();
    for (IResource current : res) {
        if (current instanceof IFolder) {
            if (!excludeFolders.contains(current)) {
                // Recurse into subfolders
                IFolder subFolder = (IFolder) current;
                recursiveScanFiles(subFolder, nameMap, monitor);
            }
        }
        else if (!isProjectFile(current.getName())) {
            Long timestamp = new Long(current.getModificationStamp());
            nameMap.put(current.getProjectRelativePath(), timestamp);
        }
        monitor.worked(1);
    }
}
 
Example 3
Source File: BuilderParticipant.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
private void delete(IResource resource, OutputConfiguration config, EclipseResourceFileSystemAccess2 access,
		IProgressMonitor monitor) throws CoreException {
	if (monitor.isCanceled()) {
		throw new OperationCanceledException();
	}
	if (resource instanceof IContainer) {
		IContainer container = (IContainer) resource;
		for (IResource child : container.members()) {
			delete(child, config, access, monitor);
		}
		container.delete(IResource.FORCE | IResource.KEEP_HISTORY, monitor);
	} else if (resource instanceof IFile) {
		IFile file = (IFile) resource;
		access.deleteFile(file, config.getName(), monitor);
	} else {
		resource.delete(IResource.FORCE | IResource.KEEP_HISTORY, monitor);
	}
}
 
Example 4
Source File: MassOpenHandler.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
private void collectFiles(IContainer container, Set<String> names, Consumer<IFile> consumer) throws CoreException {
	final IResource[] members = container.members();
	for (IResource member : members) {
		if (member instanceof IContainer) {
			if (member instanceof IProject && !((IProject) member).isOpen()) {
				continue;
			}
			collectFiles((IContainer) member, names, consumer);
		} else if (member instanceof IFile) {
			final String fileName = member.getName();
			if (names.contains(fileName)) {
				consumer.accept((IFile) member);
			}
		}
	}
}
 
Example 5
Source File: ResourceExtensionContentProvider.java    From tmxeditor8 with GNU General Public License v2.0 6 votes vote down vote up
public boolean hasChildren(Object element) {
	try {
		if (element instanceof IContainer) {
			IContainer c = (IContainer) element;
			if (!c.isAccessible())
				return false;
			return c.members().length > 0;
		}
	} catch (CoreException ex) {
		WorkbenchNavigatorPlugin.getDefault().getLog().log(
				new Status(IStatus.ERROR, WorkbenchNavigatorPlugin.PLUGIN_ID, 0, ex.getMessage(), ex));
		return false;
	}

	return super.hasChildren(element);
}
 
Example 6
Source File: WebAppUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * This is nearly a clone of the method of the same name in BuildPathsBlock,
 * except here we force delete files, so out-of-sync files don't result in
 * exceptions.
 *
 * TODO: we can revert back to using BuildPathsBlock's method if we update
 * EnhancerJob to refresh any files it touches.
 */
private static void removeOldClassfiles(IResource resource)
    throws CoreException {
  if (resource.isDerived()) {
    resource.delete(true, null);
  } else {
    IContainer resourceAsContainer = AdapterUtilities.getAdapter(resource,
        IContainer.class);
    if (resourceAsContainer != null) {
      IResource[] members = resourceAsContainer.members();
      for (int i = 0; i < members.length; i++) {
        removeOldClassfiles(members[i]);
      }
    }
  }
}
 
Example 7
Source File: EIPModelTreeContentProvider.java    From eip-designer with Apache License 2.0 6 votes vote down vote up
/** */
private static void findEIPModels(List<IResource> models, IPath path, IWorkspaceRoot workspaceRoot){
   IContainer container =  workspaceRoot.getContainerForLocation(path);

   try {
      IResource[] iResources = container.members();
      for (IResource iResource : iResources) {
         if ("eip".equalsIgnoreCase(iResource.getFileExtension())) {
            models.add(iResource);
         }
         if (iResource.getType() == IResource.FOLDER) {
            IPath tempPath = iResource.getLocation();
            findEIPModels(models, tempPath, workspaceRoot);
         }
      }
   } catch (CoreException e) {
      System.err.println("CoreException while browsing " + path);
   }
}
 
Example 8
Source File: SelectionFilesCollector.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private void collectResource(IContainer container, Set<IFile> collected) {
	try {
		IResource[] resources = container.members(IContainer.EXCLUDE_DERIVED);
		for (IResource resource : resources) {
			collectRelevantFiles(resource, collected);
		}
	} catch (CoreException c) {
		LOGGER.warn("Error while collecting files", c);
	}
}
 
Example 9
Source File: CopyFilesAndFoldersOperation.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Check if the destination is valid for the given source resource.
 *
 * @param destination
 *            destination container of the operation
 * @param source
 *            source resource
 * @return String error message or null if the destination is valid
 */
private String validateLinkedResource(IContainer destination, IResource source) {
    if (source.isLinked() == false) {
        return null;
    }
    IWorkspace workspace = destination.getWorkspace();
    IResource linkHandle = createLinkedResourceHandle(destination, source);
    IStatus locationStatus = workspace.validateLinkLocation(linkHandle, source.getRawLocation());

    if (locationStatus.getSeverity() == IStatus.ERROR) {
        return locationStatus.getMessage();
    }
    IPath sourceLocation = source.getLocation();
    if (source.getProject().equals(destination.getProject()) == false && source.getType() == IResource.FOLDER
            && sourceLocation != null) {
        // prevent merging linked folders that point to the same
        // file system folder
        try {
            IResource[] members = destination.members();
            for (int j = 0; j < members.length; j++) {
                if (sourceLocation.equals(members[j].getLocation())
                        && source.getName().equals(members[j].getName())) {
                    return NLS.bind(IDEWorkbenchMessages.CopyFilesAndFoldersOperation_sameSourceAndDest,
                            source.getName());
                }
            }
        } catch (CoreException exception) {
            displayError(NLS.bind(IDEWorkbenchMessages.CopyFilesAndFoldersOperation_internalError,
                    exception.getMessage()));
        }
    }
    return null;
}
 
Example 10
Source File: DotnetExportWizard.java    From aCute with Eclipse Public License 2.0 5 votes vote down vote up
public static IFile getProjectFile(IContainer container) {
	if (container != null) {
		try {
			for (IResource projResource : container.members()) {
				if (projResource.getFileExtension() != null && (projResource.getFileExtension().equals("csproj") //$NON-NLS-1$
						|| projResource.getName().equals("project.json"))) { //$NON-NLS-1$
					return (IFile) projResource;
				}
			}
		} catch (CoreException e) {
		}
	}
	return null;
}
 
Example 11
Source File: Utils.java    From CogniCrypt with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * This method searches the passed project for the class that contains the main method.
 *
 * @param project Project that is searched
 * @param requestor Object that handles the search results
 * @throws CoreException
 */
public static IFile findFileInProject(IContainer container, String name) throws CoreException {
	for (IResource res : container.members()) {
		if (res instanceof IContainer) {
			IFile file = findFileInProject((IContainer) res, name);
			if (file != null) {
				return file;
			}
		} else if (res instanceof IFile && (res.getName().equals(name.substring(name.lastIndexOf(".") + 1) + ".java"))) {
			return (IFile) res;
		}
	}

	return null;
}
 
Example 12
Source File: PythonModulePickerDialog.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Object[] getChildren(Object element) {

    if (element instanceof IContainer) {
        IContainer container = (IContainer) element;

        if (container.isAccessible()) {
            try {
                List<IResource> children = new ArrayList<IResource>();

                IResource[] members = container.members();

                for (int i = 0; i < members.length; i++) {

                    if (members[i] instanceof IFile) {

                        IFile file = (IFile) members[i];

                        if (PythonPathHelper.isValidSourceFile(file)) {
                            children.add(file);
                        }
                    } else if (members[i] instanceof IContainer) {
                        children.add(members[i]);
                    }
                }
                return children.toArray();
            } catch (CoreException e) {
                // this should never happen because we call #isAccessible before invoking #members
            }
        }
    }

    return new Object[0];
}
 
Example 13
Source File: FileMetaDataProvider.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
public List<IFile> getSupportFilesOf(final IFile f) {
	if (f == null) { return Collections.EMPTY_LIST; }
	if (!getContentTypeId(f).equals(SHAPEFILE_CT_ID)) { return Collections.EMPTY_LIST; }
	final IContainer c = f.getParent();
	final List<IFile> result = new ArrayList<>();
	try {
		for (final IResource r : c.members()) {
			if (r instanceof IFile && isSupport(f, (IFile) r)) {
				result.add((IFile) r);
			}
		}
	} catch (final CoreException e) {}
	return result;
}
 
Example 14
Source File: ContainerContentProvider.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @see ITreeContentProvider#getChildren
 */
public Object[] getChildren(Object element) {
	if (element instanceof IWorkspace) {
		// check if closed projects should be shown
		IProject[] allProjects = ((IWorkspace) element).getRoot().getProjects();
		if (showClosedProjects)
			return allProjects;
		
		ArrayList accessibleProjects = new ArrayList();
		for (int i = 0; i < allProjects.length; i++){
			if (allProjects[i].isOpen()){
				accessibleProjects.add(allProjects[i]);
			}
		}
		return accessibleProjects.toArray();
	} else if (element instanceof IContainer) {
		IContainer container = (IContainer)element;
		if (container.isAccessible()) {
		    try {
			    List children = new ArrayList();
			    IResource[] members = container.members();
			    for (int i = 0; i < members.length; i++) {
				    if (members[i].getType() != IResource.FILE) {
					    children.add(members[i]);
				    }
			    }
			    return children.toArray();
			} catch (CoreException e) {
				// this should never happen because we call #isAccessible before invoking #members
			}
		}
	}
	return new Object[0];
}
 
Example 15
Source File: TmfExperimentElement.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
private void deleteTraceResource(IResource resource) throws CoreException {
    resource.delete(true, null);
    IContainer parent = resource.getParent();
    // delete empty folders up to the parent experiment folder
    if (!parent.equals(getResource()) && parent.exists() && parent.members().length == 0) {
        deleteTraceResource(parent);
    }
}
 
Example 16
Source File: ExampleModelOpener.java    From statecharts with Eclipse Public License 1.0 5 votes vote down vote up
public List<IFile> findAllFilesRecursively(IContainer container, String fileEnding) throws CoreException {
	List<IFile> files = Lists.newArrayList();
	for (IResource r : container.members()) {
		if (r instanceof IContainer) {
			files.addAll(findAllFilesRecursively((IContainer) r, fileEnding));
		} else if (r instanceof IFile && r.getName().endsWith(fileEnding)) {
			files.add((IFile) r);
		}
	}
	return files;
}
 
Example 17
Source File: DeleteModifications.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * This method collects file and folder deletion for notifying
 * participants. Participants will get notified of
 *
 * * deletion of the package (in any case)
 * * deletion of files within the package if only the files are deleted without
 *   the package folder ("package cleaning")
 * * deletion of the package folder if it is not only cleared and if its parent
 *   is not removed as well.
 *
 * All deleted resources are added to <code>resourcesCollector</code>
 * @param pack the package
 *
 * @param resourcesCollector a collector for IResources to be deleted
 * @throws CoreException
 */
private void handlePackageFragmentDelete(IPackageFragment pack, ArrayList<IResource> resourcesCollector) throws CoreException {
	final IContainer container= (IContainer)pack.getResource();
	if (container == null)
		return;

	final IResource[] members= container.members();

	/*
	 * Check whether this package is removed completely or only cleared.
	 * The default package can never be removed completely.
	 */
	if (!pack.isDefaultPackage() && canRemoveCompletely(pack)) {
		// This package is removed completely, which means its folder will be
		// deleted as well. We only notify participants of the folder deletion
		// if the parent folder of this folder will not be deleted as well:
		boolean parentIsMarked= false;
		final IPackageFragment parent= JavaElementUtil.getParentSubpackage(pack);
		if (parent == null) {
			// "Parent" is the default package which will never be
			// deleted physically
			parentIsMarked= false;
		} else {
			// Parent is marked if it is in the list
			parentIsMarked= fPackagesToDelete.contains(parent);
		}

		if (parentIsMarked) {
			// Parent is marked, but is it really deleted or only cleared?
			if (canRemoveCompletely(parent)) {
				// Parent can be removed completely, so we do not add
				// this folder to the list.
			} else {
				// Parent cannot be removed completely, but as this folder
				// can be removed, we notify the participant
				resourcesCollector.add(container);
				getResourceModifications().addDelete(container);
			}
		} else {
			// Parent will not be removed, but we will
			resourcesCollector.add(container);
			getResourceModifications().addDelete(container);
		}
	} else {
		// This package is only cleared because it has subpackages (=subfolders)
		// which are not deleted. As the package is only cleared, its folder
		// will not be removed and so we must notify the participant of the deleted children.
		for (int m= 0; m < members.length; m++) {
			IResource member= members[m];
			if (member instanceof IFile) {
				IFile file= (IFile)member;
				if ("class".equals(file.getFileExtension()) && file.isDerived()) //$NON-NLS-1$
					continue;
				if (pack.isDefaultPackage() && ! JavaCore.isJavaLikeFileName(file.getName()))
					continue;
				resourcesCollector.add(member);
				getResourceModifications().addDelete(member);
			}
			if (!pack.isDefaultPackage() && member instanceof IFolder) {
				// Normally, folder children of packages are packages
				// as well, but in case they have been removed from the build
				// path, notify the participant
				IPackageFragment frag= (IPackageFragment) JavaCore.create(member);
				if (frag == null) {
					resourcesCollector.add(member);
					getResourceModifications().addDelete(member);
				}
			}
		}
	}
}
 
Example 18
Source File: PartialBuildAction.java    From texlipse with Eclipse Public License 1.0 4 votes vote down vote up
/**
    * 
 */
public void run(IAction action) {
    
       String value = action.isChecked() ? "true" : null;
       IProject project = ((FileEditorInput)editor.getEditorInput()).getFile().getProject();
       TexlipseProperties.setProjectProperty(project, TexlipseProperties.PARTIAL_BUILD_PROPERTY, value);
       if (value == null) {
           TexlipseProperties.setSessionProperty(project, TexlipseProperties.PARTIAL_BUILD_FILE, null);
           // delete all tempPartial0000 files
           try {
               IResource[] res;
               IFolder projectOutputDir = TexlipseProperties.getProjectOutputDir(project);
               if (projectOutputDir != null)
                   res = projectOutputDir.members();
               else
                   res = project.members();
               for (int i = 0; i < res.length; i++) {
                   if (res[i].getName().startsWith("tempPartial0000"))
                       res[i].delete(true, null);
               }
               
               IFolder projectTempDir = TexlipseProperties.getProjectTempDir(project);
               if (projectTempDir != null && projectTempDir.exists())
                   res = projectTempDir.members();
               else
                   res = project.members();
               
               for (int i = 0; i < res.length; i++) {
                   if (res[i].getName().startsWith("tempPartial0000"))
                       res[i].delete(true, null);
               }
               IContainer sourceDir = TexlipseProperties.getProjectSourceDir(project);
               res = sourceDir.members();
               for (int i = 0; i < res.length; i++) {
                   if (res[i].getName().startsWith("tempPartial0000"))
                       res[i].delete(true, null);
               }

           } catch (CoreException e) {
               TexlipsePlugin.log("Error while deleting temp files", e);
           }
       }
}
 
Example 19
Source File: JarFileExportOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private Map<String, ArrayList<IResource>> buildJavaToClassMap(IContainer container, IProgressMonitor monitor) throws CoreException {
	if (container == null || !container.isAccessible())
		return new HashMap<String, ArrayList<IResource>>(0);
	/*
	 * XXX: Bug 6584: Need a way to get class files for a java file (or CU)
	 */
	IClassFileReader cfReader= null;
	IResource[] members= container.members();
	Map<String, ArrayList<IResource>> map= new HashMap<String, ArrayList<IResource>>(members.length);
	for (int i= 0;  i < members.length; i++) {
		if (isClassFile(members[i])) {
			IFile classFile= (IFile)members[i];
			URI location= classFile.getLocationURI();
			if (location != null) {
				InputStream contents= null;
				try {
					contents= EFS.getStore(location).openInputStream(EFS.NONE, monitor);
					cfReader= ToolFactory.createDefaultClassFileReader(contents, IClassFileReader.CLASSFILE_ATTRIBUTES);
				} finally {
					try {
						if (contents != null)
							contents.close();
					} catch (IOException e) {
						throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.ERROR,
							Messages.format(JarPackagerMessages.JarFileExportOperation_errorCannotCloseConnection, BasicElementLabels.getURLPart(Resources.getLocationString(classFile))),
							e));
					}
				}
				if (cfReader != null) {
					ISourceAttribute sourceAttribute= cfReader.getSourceFileAttribute();
					if (sourceAttribute == null) {
						/*
						 * Can't fully build the map because one or more
						 * class file does not contain the name of its
						 * source file.
						 */
						addWarning(Messages.format(
							JarPackagerMessages.JarFileExportOperation_classFileWithoutSourceFileAttribute,
							BasicElementLabels.getURLPart(Resources.getLocationString(classFile))), null);
						return null;
					}
					String javaName= new String(sourceAttribute.getSourceFileName());
					ArrayList<IResource> classFiles= map.get(javaName);
					if (classFiles == null) {
						classFiles= new ArrayList<IResource>(3);
						map.put(javaName, classFiles);
					}
					classFiles.add(classFile);
				}
			}
		}
	}
	return map;
}
 
Example 20
Source File: PackageFragmentRootInfo.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Starting at this folder, create non-java resources for this package fragment root
 * and add them to the non-java resources collection.
 *
 * @exception JavaModelException  The resource associated with this package fragment does not exist
 */
static Object[] computeFolderNonJavaResources(IPackageFragmentRoot root, IContainer folder, char[][] inclusionPatterns, char[][] exclusionPatterns) throws JavaModelException {
	IResource[] nonJavaResources = new IResource[5];
	int nonJavaResourcesCounter = 0;
	try {
		IResource[] members = folder.members();
		int length = members.length;
		if (length > 0) {
			// if package fragment root refers to folder in another IProject, then
			// folder.getProject() is different than root.getJavaProject().getProject()
			// use the other java project's options to verify the name
			IJavaProject otherJavaProject = JavaCore.create(folder.getProject());
			String sourceLevel = otherJavaProject.getOption(JavaCore.COMPILER_SOURCE, true);
			String complianceLevel = otherJavaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);
			JavaProject javaProject = (JavaProject) root.getJavaProject();
			IClasspathEntry[] classpath = javaProject.getResolvedClasspath();
			nextResource: for (int i = 0; i < length; i++) {
				IResource member = members[i];
				switch (member.getType()) {
					case IResource.FILE :
						String fileName = member.getName();

						// ignore .java files that are not excluded
						if (Util.isValidCompilationUnitName(fileName, sourceLevel, complianceLevel) && !Util.isExcluded(member, inclusionPatterns, exclusionPatterns))
							continue nextResource;
						// ignore .class files
						if (Util.isValidClassFileName(fileName, sourceLevel, complianceLevel))
							continue nextResource;
						// ignore .zip or .jar file on classpath
						if (isClasspathEntry(member.getFullPath(), classpath))
							continue nextResource;
						break;

					case IResource.FOLDER :
						// ignore valid packages or excluded folders that correspond to a nested pkg fragment root
						if (Util.isValidFolderNameForPackage(member.getName(), sourceLevel, complianceLevel)
								&& (!Util.isExcluded(member, inclusionPatterns, exclusionPatterns)
										|| isClasspathEntry(member.getFullPath(), classpath)))
							continue nextResource;
						break;
				}
				if (nonJavaResources.length == nonJavaResourcesCounter) {
					// resize
					System.arraycopy(nonJavaResources, 0, (nonJavaResources = new IResource[nonJavaResourcesCounter * 2]), 0, nonJavaResourcesCounter);
				}
				nonJavaResources[nonJavaResourcesCounter++] = member;
			}
		}
		if (ExternalFoldersManager.isInternalPathForExternalFolder(folder.getFullPath())) {
			IJarEntryResource[] jarEntryResources = new IJarEntryResource[nonJavaResourcesCounter];
			for (int i = 0; i < nonJavaResourcesCounter; i++) {
				jarEntryResources[i] = new NonJavaResource(root, nonJavaResources[i]);
			}
			return jarEntryResources;
		} else if (nonJavaResources.length != nonJavaResourcesCounter) {
			System.arraycopy(nonJavaResources, 0, (nonJavaResources = new IResource[nonJavaResourcesCounter]), 0, nonJavaResourcesCounter);
		}
		return nonJavaResources;
	} catch (CoreException e) {
		throw new JavaModelException(e);
	}
}