Java Code Examples for org.eclipse.jdt.internal.core.util.Util#isExcluded()

The following examples show how to use org.eclipse.jdt.internal.core.util.Util#isExcluded() . 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: HandleFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the package fragment root that contains the given resource path.
 */
private PackageFragmentRoot getPkgFragmentRoot(String pathString) {

	IPath path= new Path(pathString);
	IProject[] projects= ResourcesPlugin.getWorkspace().getRoot().getProjects();
	for (int i= 0, max= projects.length; i < max; i++) {
		try {
			IProject project = projects[i];
			if (!project.isAccessible()
				|| !project.hasNature(JavaCore.NATURE_ID)) continue;
			IJavaProject javaProject= this.javaModel.getJavaProject(project);
			IPackageFragmentRoot[] roots= javaProject.getPackageFragmentRoots();
			for (int j= 0, rootCount= roots.length; j < rootCount; j++) {
				PackageFragmentRoot root= (PackageFragmentRoot)roots[j];
				if (root.internalPath().isPrefixOf(path) && !Util.isExcluded(path, root.fullInclusionPatternChars(), root.fullExclusionPatternChars(), false)) {
					return root;
				}
			}
		} catch (CoreException e) {
			// CoreException from hasNature - should not happen since we check that the project is accessible
			// JavaModelException from getPackageFragmentRoots - a problem occured while accessing project: nothing we can do, ignore
		}
	}
	return null;
}
 
Example 2
Source File: JavaProject.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private boolean isOnClasspathEntry(IPath elementPath, boolean isFolderPath, boolean isPackageFragmentRoot, IClasspathEntry entry) {
	IPath entryPath = entry.getPath();
	if (isPackageFragmentRoot) {
		// package fragment roots must match exactly entry pathes (no exclusion there)
		if (entryPath.equals(elementPath))
			return true;
	} else {
		if (entryPath.isPrefixOf(elementPath)
				&& !Util.isExcluded(elementPath, ((ClasspathEntry)entry).fullInclusionPatternChars(), ((ClasspathEntry)entry).fullExclusionPatternChars(), isFolderPath))
			return true;
	}
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=276373
	if (entryPath.isAbsolute()
			&& entryPath.equals(ResourcesPlugin.getWorkspace().getRoot().getLocation().append(elementPath))) {
		return true;
	}
	return false;
}
 
Example 3
Source File: PackageFragment.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected IStatus validateExistence(IResource underlyingResource) {
	// check that the name of the package is valid (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=108456)
	if (!isValidPackageName())
		return newDoesNotExistStatus();

	// check whether this pkg can be opened
	if (underlyingResource != null && !resourceExists(underlyingResource))
		return newDoesNotExistStatus();

	// check that it is not excluded (https://bugs.eclipse.org/bugs/show_bug.cgi?id=138577)
	int kind;
	try {
		kind = getKind();
	} catch (JavaModelException e) {
		return e.getStatus();
	}
	if (kind == IPackageFragmentRoot.K_SOURCE && Util.isExcluded(this))
		return newDoesNotExistStatus();

	return JavaModelStatus.VERIFIED_OK;
}
 
Example 4
Source File: PackageFragment.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @see IPackageFragment#getCompilationUnits(WorkingCopyOwner)
 */
public ICompilationUnit[] getCompilationUnits(WorkingCopyOwner owner) {
	ICompilationUnit[] workingCopies = JavaModelManager.getJavaModelManager().getWorkingCopies(owner, false/*don't add primary*/);
	if (workingCopies == null) return JavaModelManager.NO_WORKING_COPY;
	int length = workingCopies.length;
	ICompilationUnit[] result = new ICompilationUnit[length];
	int index = 0;
	for (int i = 0; i < length; i++) {
		ICompilationUnit wc = workingCopies[i];
		if (equals(wc.getParent()) && !Util.isExcluded(wc)) { // 59933 - excluded wc shouldn't be answered back
			result[index++] = wc;
		}
	}
	if (index != length) {
		System.arraycopy(result, 0, result = new ICompilationUnit[index], 0, index);
	}
	return result;
}
 
Example 5
Source File: AbstractImageBuilder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected SourceFile findSourceFile(IFile file, boolean mustExist) {
	if (mustExist && !file.exists()) return null;

	// assumes the file exists in at least one of the source folders & is not excluded
	ClasspathMultiDirectory md = this.sourceLocations[0];
	if (this.sourceLocations.length > 1) {
		IPath sourceFileFullPath = file.getFullPath();
		for (int j = 0, m = this.sourceLocations.length; j < m; j++) {
			if (this.sourceLocations[j].sourceFolder.getFullPath().isPrefixOf(sourceFileFullPath)) {
				md = this.sourceLocations[j];
				if (md.exclusionPatterns == null && md.inclusionPatterns == null)
					break;
				if (!Util.isExcluded(file, md.inclusionPatterns, md.exclusionPatterns))
					break;
			}
		}
	}
	return new SourceFile(file, md);
}
 
Example 6
Source File: CopyResourceElementsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Sets the deltas to register the changes resulting from this operation
 * for this source element and its destination.
 * If the operation is a cross project operation<ul>
 * <li>On a copy, the delta should be rooted in the dest project
 * <li>On a move, two deltas are generated<ul>
 * 			<li>one rooted in the source project
 *			<li>one rooted in the destination project
 * <li> When a CU is being overwritten, the delta on the destination will be of type F_CONTENT </ul></ul>
 * If the operation is rooted in a single project, the delta is rooted in that project
 *
 */
protected void prepareDeltas(IJavaElement sourceElement, IJavaElement destinationElement, boolean isMove, boolean overWriteCU) {
	if (Util.isExcluded(sourceElement) || Util.isExcluded(destinationElement)) return;
	
	IJavaProject destProject = destinationElement.getJavaProject();
	if (isMove) {
		IJavaProject sourceProject = sourceElement.getJavaProject();
		getDeltaFor(sourceProject).movedFrom(sourceElement, destinationElement);
		if (!overWriteCU) {
			getDeltaFor(destProject).movedTo(destinationElement, sourceElement);
			return;
		}
	} else {
		if (!overWriteCU) {
			getDeltaFor(destProject).added(destinationElement);
			return;
		}
	}
	getDeltaFor(destinationElement.getJavaProject()).changed(destinationElement, IJavaElementDelta.F_CONTENT);
}
 
Example 7
Source File: CompilationUnit.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected IStatus validateCompilationUnit(IResource resource) {
	IPackageFragmentRoot root = getPackageFragmentRoot();
	// root never null as validation is not done for working copies
	try {
		if (root.getKind() != IPackageFragmentRoot.K_SOURCE)
			return new JavaModelStatus(IJavaModelStatusConstants.INVALID_ELEMENT_TYPES, root);
	} catch (JavaModelException e) {
		return e.getJavaModelStatus();
	}
	if (resource != null) {
		char[][] inclusionPatterns = ((PackageFragmentRoot)root).fullInclusionPatternChars();
		char[][] exclusionPatterns = ((PackageFragmentRoot)root).fullExclusionPatternChars();
		if (Util.isExcluded(resource, inclusionPatterns, exclusionPatterns))
			return new JavaModelStatus(IJavaModelStatusConstants.ELEMENT_NOT_ON_CLASSPATH, this);
		if (!resource.isAccessible())
			return new JavaModelStatus(IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST, this);
	}
	IJavaProject project = getJavaProject();
	return JavaConventions.validateCompilationUnitName(getElementName(),project.getOption(JavaCore.COMPILER_SOURCE, true), project.getOption(JavaCore.COMPILER_COMPLIANCE, true));
}
 
Example 8
Source File: ClasspathChange.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private ArrayList determineAffectedPackageFragments(IPath location) throws JavaModelException {
	ArrayList fragments = new ArrayList();

	// see if this will cause any package fragments to be affected
	IWorkspace workspace = ResourcesPlugin.getWorkspace();
	IResource resource = null;
	if (location != null) {
		resource = workspace.getRoot().findMember(location);
	}
	if (resource != null && resource.getType() == IResource.FOLDER) {
		IFolder folder = (IFolder) resource;
		// only changes if it actually existed
		IClasspathEntry[] classpath = this.project.getExpandedClasspath();
		for (int i = 0; i < classpath.length; i++) {
			IClasspathEntry entry = classpath[i];
			IPath path = classpath[i].getPath();
			if (entry.getEntryKind() != IClasspathEntry.CPE_PROJECT && path.isPrefixOf(location) && !path.equals(location)) {
				IPackageFragmentRoot[] roots = this.project.computePackageFragmentRoots(classpath[i]);
				PackageFragmentRoot root = (PackageFragmentRoot) roots[0];
				// now the output location becomes a package fragment - along with any subfolders
				ArrayList folders = new ArrayList();
				folders.add(folder);
				collectAllSubfolders(folder, folders);
				Iterator elements = folders.iterator();
				int segments = path.segmentCount();
				while (elements.hasNext()) {
					IFolder f = (IFolder) elements.next();
					IPath relativePath = f.getFullPath().removeFirstSegments(segments);
					String[] pkgName = relativePath.segments();
					IPackageFragment pkg = root.getPackageFragment(pkgName);
					if (!Util.isExcluded(pkg))
						fragments.add(pkg);
				}
			}
		}
	}
	return fragments;
}
 
Example 9
Source File: CopyResourceElementsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates any destination package fragment(s) which do not exists yet.
 * Return true if a read-only package fragment has been found among package fragments, false otherwise
 */
private boolean createNeededPackageFragments(IContainer sourceFolder, PackageFragmentRoot root, String[] newFragName, boolean moveFolder) throws JavaModelException {
	boolean containsReadOnlyPackageFragment = false;
	IContainer parentFolder = (IContainer) root.resource();
	JavaElementDelta projectDelta = null;
	String[] sideEffectPackageName = null;
	char[][] inclusionPatterns = root.fullInclusionPatternChars();
	char[][] exclusionPatterns = root.fullExclusionPatternChars();
	for (int i = 0; i < newFragName.length; i++) {
		String subFolderName = newFragName[i];
		sideEffectPackageName = Util.arrayConcat(sideEffectPackageName, subFolderName);
		IResource subFolder = parentFolder.findMember(subFolderName);
		if (subFolder == null) {
			// create deepest folder only if not a move (folder will be moved in processPackageFragmentResource)
			if (!(moveFolder && i == newFragName.length-1)) {
				createFolder(parentFolder, subFolderName, this.force);
			}
			parentFolder = parentFolder.getFolder(new Path(subFolderName));
			sourceFolder = sourceFolder.getFolder(new Path(subFolderName));
			if (Util.isReadOnly(sourceFolder)) {
				containsReadOnlyPackageFragment = true;
			}
			IPackageFragment sideEffectPackage = root.getPackageFragment(sideEffectPackageName);
			if (i < newFragName.length - 1 // all but the last one are side effect packages
					&& !Util.isExcluded(parentFolder, inclusionPatterns, exclusionPatterns)) {
				if (projectDelta == null) {
					projectDelta = getDeltaFor(root.getJavaProject());
				}
				projectDelta.added(sideEffectPackage);
			}
			this.createdElements.add(sideEffectPackage);
		} else {
			parentFolder = (IContainer) subFolder;
		}
	}
	return containsReadOnlyPackageFragment;
}
 
Example 10
Source File: CreateElementInCUOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Execute the operation - generate new source for the compilation unit
 * and save the results.
 *
 * @exception JavaModelException if the operation is unable to complete
 */
protected void executeOperation() throws JavaModelException {
	try {
		beginTask(getMainTaskName(), getMainAmountOfWork());
		JavaElementDelta delta = newJavaElementDelta();
		ICompilationUnit unit = getCompilationUnit();
		generateNewCompilationUnitAST(unit);
		if (this.creationOccurred) {
			//a change has really occurred
			unit.save(null, false);
			boolean isWorkingCopy = unit.isWorkingCopy();
			if (!isWorkingCopy)
				setAttribute(HAS_MODIFIED_RESOURCE_ATTR, TRUE);
			worked(1);
			this.resultElements = generateResultHandles();
			if (!isWorkingCopy // if unit is working copy, then save will have already fired the delta
					&& !Util.isExcluded(unit)
					&& unit.getParent().exists()) {
				for (int i = 0; i < this.resultElements.length; i++) {
					delta.added(this.resultElements[i]);
				}
				addDelta(delta);
			} // else unit is created outside classpath
			  // non-java resource delta will be notified by delta processor
		}
	} finally {
		done();
	}
}
 
Example 11
Source File: IncrementalImageBuilder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected boolean checkForClassFileChanges(IResourceDelta binaryDelta, ClasspathMultiDirectory md, int segmentCount) throws CoreException {
	IResource resource = binaryDelta.getResource();
	// remember that if inclusion & exclusion patterns change then a full build is done
	boolean isExcluded = (md.exclusionPatterns != null || md.inclusionPatterns != null)
		&& Util.isExcluded(resource, md.inclusionPatterns, md.exclusionPatterns);
	switch(resource.getType()) {
		case IResource.FOLDER :
			if (isExcluded && md.inclusionPatterns == null)
		        return true; // no need to go further with this delta since its children cannot be included

			IResourceDelta[] children = binaryDelta.getAffectedChildren();
			for (int i = 0, l = children.length; i < l; i++)
				if (!checkForClassFileChanges(children[i], md, segmentCount))
					return false;
			return true;
		case IResource.FILE :
			if (!isExcluded && org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(resource.getName())) {
				// perform full build if a managed class file has been changed
				IPath typePath = resource.getFullPath().removeFirstSegments(segmentCount).removeFileExtension();
				if (this.newState.isKnownType(typePath.toString())) {
					if (JavaBuilder.DEBUG)
						System.out.println("MUST DO FULL BUILD. Found change to class file " + typePath); //$NON-NLS-1$
					return false;
				}
				return true;
			}
	}
	return true;
}
 
Example 12
Source File: PackageFragment.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public boolean exists() {
	// super.exist() only checks for the parent and the resource existence
	// so also ensure that:
	//  - the package is not excluded (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=138577)
	//  - its name is valide (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=108456)
	return super.exists() && !Util.isExcluded(this) && isValidPackageName();
}
 
Example 13
Source File: JavaProject.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public boolean isOnClasspath(IResource resource) {
	IPath exactPath = resource.getFullPath();
	IPath path = exactPath;

	// ensure that folders are only excluded if all of their children are excluded
	int resourceType = resource.getType();
	boolean isFolderPath = resourceType == IResource.FOLDER || resourceType == IResource.PROJECT;

	IClasspathEntry[] classpath;
	try {
		classpath = this.getResolvedClasspath();
	} catch(JavaModelException e){
		return false; // not a Java project
	}
	for (int i = 0; i < classpath.length; i++) {
		IClasspathEntry entry = classpath[i];
		IPath entryPath = entry.getPath();
		if (entryPath.equals(exactPath)) { // package fragment roots must match exactly entry pathes (no exclusion there)
			return true;
		}
		// https://bugs.eclipse.org/bugs/show_bug.cgi?id=276373
		// When a classpath entry is absolute, convert the resource's relative path to a file system path and compare
		// e.g - /P/lib/variableLib.jar and /home/P/lib/variableLib.jar when compared should return true
		if (entryPath.isAbsolute()
				&& entryPath.equals(ResourcesPlugin.getWorkspace().getRoot().getLocation().append(exactPath))) {
			return true;
		}
		if (entryPath.isPrefixOf(path)
				&& !Util.isExcluded(path, ((ClasspathEntry)entry).fullInclusionPatternChars(), ((ClasspathEntry)entry).fullExclusionPatternChars(), isFolderPath)) {
			return true;
		}
	}
	return false;
}
 
Example 14
Source File: RemoveFolderFromIndex.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public boolean execute(IProgressMonitor progressMonitor) {

		if (this.isCancelled || progressMonitor != null && progressMonitor.isCanceled()) return true;

		/* ensure no concurrent write access to index */
		Index index = this.manager.getIndex(this.containerPath, true, /*reuse index file*/ false /*create if none*/);
		if (index == null) return true;
		ReadWriteMonitor monitor = index.monitor;
		if (monitor == null) return true; // index got deleted since acquired

		try {
			monitor.enterRead(); // ask permission to read
			String containerRelativePath = Util.relativePath(this.folderPath, this.containerPath.segmentCount());
			String[] paths = index.queryDocumentNames(containerRelativePath);
			// all file names belonging to the folder or its subfolders and that are not excluded (see http://bugs.eclipse.org/bugs/show_bug.cgi?id=32607)
			if (paths != null) {
				if (this.exclusionPatterns == null && this.inclusionPatterns == null) {
					for (int i = 0, max = paths.length; i < max; i++) {
						this.manager.remove(paths[i], this.containerPath); // write lock will be acquired by the remove operation
					}
				} else {
					for (int i = 0, max = paths.length; i < max; i++) {
						String documentPath =  this.containerPath.toString() + '/' + paths[i];
						if (!Util.isExcluded(new Path(documentPath), this.inclusionPatterns, this.exclusionPatterns, false))
							this.manager.remove(paths[i], this.containerPath); // write lock will be acquired by the remove operation
					}
				}
			}
		} catch (IOException e) {
			if (JobManager.VERBOSE) {
				Util.verbose("-> failed to remove " + this.folderPath + " from index because of the following exception:", System.err); //$NON-NLS-1$ //$NON-NLS-2$
				e.printStackTrace();
			}
			return false;
		} finally {
			monitor.exitRead(); // free read lock
		}
		return true;
	}
 
Example 15
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);
	}
}
 
Example 16
Source File: XtendResourceUiServiceProvider.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
public boolean isExcluded(IClasspathEntry entry, IPath path) {
	char[][] inclusionPatterns = getInclusionPatterns(entry);
	char[][] exclusionPatterns = getExclusionPatterns(entry);
	return Util.isExcluded(path, inclusionPatterns, exclusionPatterns, false);
}
 
Example 17
Source File: ClasspathMultiDirectory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
protected boolean isExcluded(IResource resource) {
	if (this.exclusionPatterns != null || this.inclusionPatterns != null)
		if (this.sourceFolder.equals(this.binaryFolder))
			return Util.isExcluded(resource, this.inclusionPatterns, this.exclusionPatterns);
	return false;
}
 
Example 18
Source File: PackageFragment.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * @see Openable
 */
protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements, IResource underlyingResource) throws JavaModelException {
	// add compilation units/class files from resources
	HashSet vChildren = new HashSet();
	int kind = getKind();
	try {
	    PackageFragmentRoot root = getPackageFragmentRoot();
		char[][] inclusionPatterns = root.fullInclusionPatternChars();
		char[][] exclusionPatterns = root.fullExclusionPatternChars();
		IResource[] members = ((IContainer) underlyingResource).members();
		int length = members.length;
		if (length > 0) {
			IJavaProject project = getJavaProject();
			String sourceLevel = project.getOption(JavaCore.COMPILER_SOURCE, true);
			String complianceLevel = project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
			for (int i = 0; i < length; i++) {
				IResource child = members[i];
				if (child.getType() != IResource.FOLDER
						&& !Util.isExcluded(child, inclusionPatterns, exclusionPatterns)) {
					IJavaElement childElement;
					if (kind == IPackageFragmentRoot.K_SOURCE && Util.isValidCompilationUnitName(child.getName(), sourceLevel, complianceLevel)) {
						childElement = new CompilationUnit(this, child.getName(), DefaultWorkingCopyOwner.PRIMARY);
						vChildren.add(childElement);
					} else if (kind == IPackageFragmentRoot.K_BINARY && Util.isValidClassFileName(child.getName(), sourceLevel, complianceLevel)) {
						childElement = getClassFile(child.getName());
						vChildren.add(childElement);
					}
				}
			}
		}
	} catch (CoreException e) {
		throw new JavaModelException(e);
	}

	if (kind == IPackageFragmentRoot.K_SOURCE) {
		// add primary compilation units
		ICompilationUnit[] primaryCompilationUnits = getCompilationUnits(DefaultWorkingCopyOwner.PRIMARY);
		for (int i = 0, length = primaryCompilationUnits.length; i < length; i++) {
			ICompilationUnit primary = primaryCompilationUnits[i];
			vChildren.add(primary);
		}
	}

	IJavaElement[] children = new IJavaElement[vChildren.size()];
	vChildren.toArray(children);
	info.setChildren(children);
	return true;
}
 
Example 19
Source File: JavaModelManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Returns the package fragment root represented by the resource, or
 * the package fragment the given resource is located in, or <code>null</code>
 * if the given resource is not on the classpath of the given project.
 */
public static IJavaElement determineIfOnClasspath(IResource resource, IJavaProject project) {
	IPath resourcePath = resource.getFullPath();
	boolean isExternal = ExternalFoldersManager.isInternalPathForExternalFolder(resourcePath);
	if (isExternal)
		resourcePath = resource.getLocation();

	try {
		JavaProjectElementInfo projectInfo = (JavaProjectElementInfo) getJavaModelManager().getInfo(project);
		ProjectCache projectCache = projectInfo == null ? null : projectInfo.projectCache;
		HashtableOfArrayToObject allPkgFragmentsCache = projectCache == null ? null : projectCache.allPkgFragmentsCache;
		boolean isJavaLike = org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(resourcePath.lastSegment());
		IClasspathEntry[] entries = isJavaLike ? project.getRawClasspath() // JAVA file can only live inside SRC folder (on the raw path)
				: ((JavaProject)project).getResolvedClasspath();

		int length	= entries.length;
		if (length > 0) {
			String sourceLevel = project.getOption(JavaCore.COMPILER_SOURCE, true);
			String complianceLevel = project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
			for (int i = 0; i < length; i++) {
				IClasspathEntry entry = entries[i];
				if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) continue;
				IPath rootPath = entry.getPath();
				if (rootPath.equals(resourcePath)) {
					if (isJavaLike) 
						return null;
					return project.getPackageFragmentRoot(resource);
				} else if (rootPath.isPrefixOf(resourcePath)) {
					// allow creation of package fragment if it contains a .java file that is included
					if (!Util.isExcluded(resource, ((ClasspathEntry)entry).fullInclusionPatternChars(), ((ClasspathEntry)entry).fullExclusionPatternChars())) {
						// given we have a resource child of the root, it cannot be a JAR pkg root
						PackageFragmentRoot root =
							isExternal ?
								new ExternalPackageFragmentRoot(rootPath, (JavaProject) project) :
								(PackageFragmentRoot) ((JavaProject) project).getFolderPackageFragmentRoot(rootPath);
						if (root == null) return null;
						IPath pkgPath = resourcePath.removeFirstSegments(rootPath.segmentCount());

						if (resource.getType() == IResource.FILE) {
							// if the resource is a file, then remove the last segment which
							// is the file name in the package
							pkgPath = pkgPath.removeLastSegments(1);
						}
						String[] pkgName = pkgPath.segments();

						// if package name is in the cache, then it has already been validated
						// (see https://bugs.eclipse.org/bugs/show_bug.cgi?id=133141)
						if (allPkgFragmentsCache != null && allPkgFragmentsCache.containsKey(pkgName))
							return root.getPackageFragment(pkgName);

						if (pkgName.length != 0 && JavaConventions.validatePackageName(Util.packageName(pkgPath, sourceLevel, complianceLevel), sourceLevel, complianceLevel).getSeverity() == IStatus.ERROR) {
							return null;
						}
						return root.getPackageFragment(pkgName);
					}
				}
			}
		}
	} catch (JavaModelException npe) {
		return null;
	}
	return null;
}
 
Example 20
Source File: CreateCompilationUnitOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates a compilation unit.
 *
 * @exception JavaModelException if unable to create the compilation unit.
 */
protected void executeOperation() throws JavaModelException {
	try {
		beginTask(Messages.operation_createUnitProgress, 2);
		JavaElementDelta delta = newJavaElementDelta();
		ICompilationUnit unit = getCompilationUnit();
		IPackageFragment pkg = (IPackageFragment) getParentElement();
		IContainer folder = (IContainer) pkg.getResource();
		worked(1);
		IFile compilationUnitFile = folder.getFile(new Path(this.name));
		if (compilationUnitFile.exists()) {
			// update the contents of the existing unit if fForce is true
			if (this.force) {
				IBuffer buffer = unit.getBuffer();
				if (buffer == null) return;
				buffer.setContents(this.source);
				unit.save(new NullProgressMonitor(), false);
				this.resultElements = new IJavaElement[] {unit};
				if (!Util.isExcluded(unit)
						&& unit.getParent().exists()) {
					for (int i = 0; i < this.resultElements.length; i++) {
						delta.changed(this.resultElements[i], IJavaElementDelta.F_CONTENT);
					}
					addDelta(delta);
				}
			} else {
				throw new JavaModelException(new JavaModelStatus(
					IJavaModelStatusConstants.NAME_COLLISION,
					Messages.bind(Messages.status_nameCollision, compilationUnitFile.getFullPath().toString())));
			}
		} else {
			try {
				String encoding = null;
				try {
					encoding = folder.getDefaultCharset(); // get folder encoding as file is not accessible
				}
				catch (CoreException ce) {
					// use no encoding
				}
				InputStream stream = new ByteArrayInputStream(encoding == null ? this.source.getBytes() : this.source.getBytes(encoding));
				createFile(folder, unit.getElementName(), stream, this.force);
				this.resultElements = new IJavaElement[] {unit};
				if (!Util.isExcluded(unit)
						&& unit.getParent().exists()) {
					for (int i = 0; i < this.resultElements.length; i++) {
						delta.added(this.resultElements[i]);
					}
					addDelta(delta);
				}
			} catch (IOException e) {
				throw new JavaModelException(e, IJavaModelStatusConstants.IO_EXCEPTION);
			}
		}
		worked(1);
	} finally {
		done();
	}
}