Java Code Examples for org.eclipse.jdt.core.IType#getAncestor()

The following examples show how to use org.eclipse.jdt.core.IType#getAncestor() . 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: CallHierarchyHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Gets the location of the Java {@code element} based on the desired
 * {@code locationType}.
 */
private Location getLocation(IJavaElement element, LocationType locationType) throws JavaModelException {
	Assert.isNotNull(element, "element");
	Assert.isNotNull(locationType, "locationType");

	Location location = locationType.toLocation(element);
	if (location == null && element instanceof IType) {
		IType type = (IType) element;
		ICompilationUnit unit = (ICompilationUnit) type.getAncestor(COMPILATION_UNIT);
		IClassFile classFile = (IClassFile) type.getAncestor(CLASS_FILE);
		if (unit != null || (classFile != null && classFile.getSourceRange() != null)) {
			location = locationType.toLocation(type);
		}
	}
	if (location == null && element instanceof IMember && ((IMember) element).getClassFile() != null) {
		location = JDTUtils.toLocation(((IMember) element).getClassFile());
	}
	return location;
}
 
Example 2
Source File: GotoTypeAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void gotoType(IType type) {
	ICompilationUnit cu= (ICompilationUnit) type.getAncestor(IJavaElement.COMPILATION_UNIT);
	IJavaElement element= null;
	if (cu != null) {
		element= cu.getPrimary();
	}
	else {
		element= type.getAncestor(IJavaElement.CLASS_FILE);
	}
	if (element != null) {
		PackageExplorerPart view= PackageExplorerPart.openInActivePerspective();
		if (view != null) {
			view.selectReveal(new StructuredSelection(element));
			if (!element.equals(getSelectedElement(view))) {
				MessageDialog.openInformation(fPackageExplorer.getSite().getShell(),
					getDialogTitle(),
					Messages.format(PackagesMessages.PackageExplorer_element_not_present, JavaElementLabels.getElementLabel(element, JavaElementLabels.ALL_DEFAULT)));
			}
		}
	}
}
 
Example 3
Source File: HierarchyLabelProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected boolean isInDifferentHierarchyScope(IType type) {
	if (fFilter != null && !fFilter.select(null, null, type)) {
		return true;
	}
	IJavaElement[] input= fHierarchy.getInputElements();
	if (input == null)
		return false;
	for (int i= 0; i < input.length; i++) {
		if (input[i] == null || input[i].getElementType() == IJavaElement.TYPE) {
			return false;
		}
		IJavaElement parent= type.getAncestor(input[i].getElementType());
		if (input[i].getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
			if (parent == null || parent.getElementName().equals(input[i].getElementName())) {
				return false;
			}
		} else if (input[i].equals(parent)) {
			return false;
		}
	}
	return true;
}
 
Example 4
Source File: TypeHierarchyContentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private boolean isInHierarchyOfInputElements(IType type) {
	if (fWorkingSetFilter != null && !fWorkingSetFilter.select(null, null, type)) {
		return false;
	}

	IJavaElement[] input= fTypeHierarchy.getInputElements();
	if (input == null)
		return false;
	for (int i= 0; i < input.length; i++) {
		int inputType= input[i].getElementType();
		if (inputType == IJavaElement.TYPE) {
			return true;
		}

		IJavaElement parent= type.getAncestor(inputType);
		if (inputType == IJavaElement.PACKAGE_FRAGMENT) {
			if (parent == null || parent.getElementName().equals(input[i].getElementName())) {
				return true;
			}
		} else if (input[i].equals(parent)) {
			return true;
		}
	}
	return false;
}
 
Example 5
Source File: NamedMember.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected String getKey(IType type, boolean forceOpen) throws JavaModelException {
	StringBuffer key = new StringBuffer();
	key.append('L');
	String packageName = type.getPackageFragment().getElementName();
	key.append(packageName.replace('.', '/'));
	if (packageName.length() > 0)
		key.append('/');
	String typeQualifiedName = type.getTypeQualifiedName('$');
	ICompilationUnit cu = (ICompilationUnit) type.getAncestor(IJavaElement.COMPILATION_UNIT);
	if (cu != null) {
		String cuName = cu.getElementName();
		String mainTypeName = cuName.substring(0, cuName.lastIndexOf('.'));
		int end = typeQualifiedName.indexOf('$');
		if (end == -1)
			end = typeQualifiedName.length();
		String topLevelTypeName = typeQualifiedName.substring(0, end);
		if (!mainTypeName.equals(topLevelTypeName)) {
			key.append(mainTypeName);
			key.append('~');
		}
	}
	key.append(typeQualifiedName);
	key.append(';');
	return key.toString();
}
 
Example 6
Source File: XbaseUIValidator.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected RestrictionKind computeRestriction(IJavaProject project, IType type) {
	try {
		IPackageFragmentRoot root = (IPackageFragmentRoot) type.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
		if (root == null) {
			return RestrictionKind.VALID;
		}
		IClasspathEntry entry = getResolvedClasspathEntry(project, root);
		if (entry == null) {
			return RestrictionKind.VALID;
		}
		IAccessRule[] rules = entry.getAccessRules();
		String typePath = type.getFullyQualifiedName().replace('.', '/');
		char[] typePathAsArray = typePath.toCharArray();
		for(IAccessRule rule: rules) {
			char[] patternArray = ((ClasspathAccessRule)rule).pattern;
			if (CharOperation.pathMatch(patternArray, typePathAsArray, true, '/')) {
				if (rule.getKind() == IAccessRule.K_DISCOURAGED) {
					return RestrictionKind.DISCOURAGED;
				} else if (rule.getKind() == IAccessRule.K_NON_ACCESSIBLE) {
					return RestrictionKind.FORBIDDEN;
				}
				return RestrictionKind.VALID;
			}
		}
	} catch(JavaModelException jme) {
		// ignore
	}
	return RestrictionKind.VALID;
}
 
Example 7
Source File: ClasspathUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Return the raw classpath entry on the project's classpath that contributes
 * the given type to the project.
 *
 * @param javaProject The java project
 * @param fullyQualifiedName The fully-qualified type name
 * @return The raw classpath entry that contributes the type to the project,
 *         or <code>null</code> if no such classpath entry can be found.
 * @throws JavaModelException
 */
public static IClasspathEntry findRawClasspathEntryFor(
    IJavaProject javaProject, String fullyQualifiedName)
    throws JavaModelException {
  IType type = javaProject.findType(fullyQualifiedName);
  if (type != null) {
    IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) type.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);

    JavaProject jProject = (JavaProject) javaProject;

    IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
    for (IClasspathEntry rawClasspathEntry : rawClasspath) {
      IClasspathEntry[] resolvedClasspath = jProject.resolveClasspath(new IClasspathEntry[] {rawClasspathEntry});

      // was this - which is no longer, internal api refactor
      //IPackageFragmentRoot[] computePackageFragmentRoots = jProject.computePackageFragmentRoots(resolvedClasspath, true, null);

      // now this - from IPackage
      List<IPackageFragmentRoot> fragmentRoots = new ArrayList<IPackageFragmentRoot>();
      for (IClasspathEntry classPathEntry : resolvedClasspath) {
        IPackageFragmentRoot[] foundRoots = javaProject.findPackageFragmentRoots(classPathEntry);
        fragmentRoots.addAll(Arrays.asList(foundRoots));
      }

      IPackageFragmentRoot[] computePackageFragmentRoots = new IPackageFragmentRoot[fragmentRoots.size()];
      fragmentRoots.toArray(computePackageFragmentRoots);

      if (Arrays.asList(computePackageFragmentRoots).contains(
          packageFragmentRoot)) {
        return rawClasspathEntry;
      }
    }

    return packageFragmentRoot.getRawClasspathEntry();
  }

  return null;
}
 
Example 8
Source File: GWTMavenRuntime.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Find the classpath for get-dev.jar which is used to run super dev mode.
 *
 * @return IClasspathEntry for the path to gwt-dev.jar
 * @throws JavaModelException
 */
private IClasspathEntry findGwtCodeServerClasspathEntry() throws JavaModelException {
  IType type = javaProject.findType(GwtLaunchConfigurationProcessorUtilities.GWT_CODE_SERVER);
  if (type == null) {
    return null;
  }

  IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) type
      .getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
  if (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_BINARY) {
    return JavaCore.newLibraryEntry(packageFragmentRoot.getPath(), null, null);
  }

  return null;
}
 
Example 9
Source File: GWTMavenRuntime.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
private IClasspathEntry findGwtUserClasspathEntry() throws JavaModelException {
  /*
   * Note that the type that we're looking for to determine if we're part of the gwt-user library is different than
   * the one that is used by the superclass. This is because the class that the superclass is querying for,
   * "com.google.gwt.core.client.GWT", also exists in the gwt-servlet library, and for some reason, this sometimes
   * ends up on the build path for Maven projects.
   *
   * TODO: See why Maven is putting gwt-servlet on the build path.
   *
   * TODO: Change the class query in the superclass to "com.google.gwt.junit.client.GWTTestCase"
   */
  IType type = javaProject.findType("com.google.gwt.junit.client.GWTTestCase");

  if (type == null) {
    return null;
  }

  IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) type
      .getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
  if (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_BINARY) {
    // TODO: If the Maven javadoc and source libs for gwt-dev.jar are
    // available, attach them here.
    return JavaCore.newLibraryEntry(packageFragmentRoot.getPath(), null, null);
  }

  return null;
}
 
Example 10
Source File: GWTMavenRuntime.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
private IClasspathEntry findJavaXValidationClasspathEntry() throws JavaModelException {
  IType type = javaProject.findType("javax.validation.Constraint");

  if (type == null) {
    return null;
  }

  IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) type
      .getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
  if (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_BINARY) {
    return JavaCore.newLibraryEntry(packageFragmentRoot.getPath(), null, null);
  }

  return null;
}
 
Example 11
Source File: ExtractClassRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private RefactoringStatus checkPackageClass() {
	RefactoringStatus status= new RefactoringStatus();
	IType type= fDescriptor.getType();
	IPackageFragmentRoot ancestor= (IPackageFragmentRoot) type.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
	IPackageFragment packageFragment= ancestor.getPackageFragment(fDescriptor.getPackage());
	if (packageFragment.getCompilationUnit(fDescriptor.getClassName() + JavaModelUtil.DEFAULT_CU_SUFFIX).exists())
		status.addError(Messages.format(RefactoringCoreMessages.ExtractClassRefactoring_error_toplevel_name_clash, new Object[] { BasicElementLabels.getJavaElementName(fDescriptor.getClassName()), BasicElementLabels.getJavaElementName(fDescriptor.getPackage()) }));
	return status;
}
 
Example 12
Source File: NameLookup.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private AccessRestriction getViolatedRestriction(String typeName, String packageName, IType type, AccessRestriction accessRestriction) {
	PackageFragmentRoot root = (PackageFragmentRoot) type.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
	ClasspathEntry entry = (ClasspathEntry) this.rootToResolvedEntries.get(root);
	if (entry != null) { // reverse map always contains resolved CP entry
		AccessRuleSet accessRuleSet = entry.getAccessRuleSet();
		if (accessRuleSet != null) {
			// TODO (philippe) improve char[] <-> String conversions to avoid performing them on the fly
			char[][] packageChars = CharOperation.splitOn('.', packageName.toCharArray());
			char[] typeChars = typeName.toCharArray();
			accessRestriction = accessRuleSet.getViolatedRestriction(CharOperation.concatWith(packageChars, typeChars, '/'));
		}
	}
	return accessRestriction;
}
 
Example 13
Source File: SearchableEnvironmentRequestor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see IJavaElementRequestor
 */
public void acceptType(IType type) {
	try {
		if (this.unitToSkip != null && this.unitToSkip.equals(type.getCompilationUnit())){
			return;
		}
		char[] packageName = type.getPackageFragment().getElementName().toCharArray();
		boolean isBinary = type instanceof BinaryType;

		// determine associated access restriction
		AccessRestriction accessRestriction = null;

		if (this.checkAccessRestrictions && (isBinary || !type.getJavaProject().equals(this.project))) {
			PackageFragmentRoot root = (PackageFragmentRoot)type.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
			ClasspathEntry entry = (ClasspathEntry) this.nameLookup.rootToResolvedEntries.get(root);
			if (entry != null) { // reverse map always contains resolved CP entry
				AccessRuleSet accessRuleSet = entry.getAccessRuleSet();
				if (accessRuleSet != null) {
					// TODO (philippe) improve char[] <-> String conversions to avoid performing them on the fly
					char[][] packageChars = CharOperation.splitOn('.', packageName);
					char[] fileWithoutExtension = type.getElementName().toCharArray();
					accessRestriction = accessRuleSet.getViolatedRestriction(CharOperation.concatWith(packageChars, fileWithoutExtension, '/'));
				}
			}
		}
		this.requestor.acceptType(packageName, type.getElementName().toCharArray(), null, type.getFlags(), accessRestriction);
	} catch (JavaModelException jme) {
		// ignore
	}
}
 
Example 14
Source File: JdtUtils.java    From spotbugs with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * @param type
 *            should be inner type.
 * @return true, if given element is a type defined in the initializer block
 */
private static boolean isFromInitBlock(IType type) {
    IJavaElement ancestor = type.getAncestor(IJavaElement.INITIALIZER);
    return ancestor != null;
}