Java 类org.eclipse.jdt.core.ITypeHierarchy 实例源码

项目:gw4e.project    文件:JDTManager.java   
/**
 * @param testInterface
 * @return
 * @throws JavaModelException
 */
public static boolean isGraphWalkerExecutionContextClass(ICompilationUnit unit) throws JavaModelException {
    IType[] types = unit.getAllTypes();

    if (types == null || types.length == 0) {
        ResourceManager.logInfo(unit.getJavaProject().getProject().getName(),
                "getAllTypes return null" + unit.getPath());
        return false;
    }
    IType execContextType = unit.getJavaProject().findType(ExecutionContext.class.getName());

    for (int i = 0; i < types.length; i++) {
        IType type = types[i];
        String typeNname = type.getFullyQualifiedName();
        String compilationUnitName = JDTManager.getJavaFullyQualifiedName(unit);
        if (typeNname.equals(compilationUnitName)) {
            try {
                ITypeHierarchy th = types[0].newTypeHierarchy(new NullProgressMonitor());
                return th.contains(execContextType);
            } catch (Exception e) {
                ResourceManager.logException(e);
            }
        }
    }
    return false;
}
项目:google-cloud-eclipse    文件:TypeHierarchyPipelineOptionsHierarchyTest.java   
@Test
public void testGetPipelineOptionsTypeForTypeNotInProjectReturnsAbsent() throws Exception {
  IType rootType = mockType(PipelineOptionsNamespaces.rootType(version));
  when(rootType.getMethods()).thenReturn(new IMethod[0]);
  when(rootType.exists()).thenReturn(true);

  when(project.findType(PipelineOptionsNamespaces.rootType(version)))
      .thenReturn(rootType);

  String requestedTypeName = "foo.bar.RequestedType";
  when(project.findType(requestedTypeName)).thenReturn(null);

  ITypeHierarchy hierarchy = mock(ITypeHierarchy.class);
  when(rootType.newTypeHierarchy(Mockito.<IProgressMonitor>any())).thenReturn(hierarchy);

  PipelineOptionsType type =
      pipelineOptionsHierarchy.getPipelineOptionsType(requestedTypeName);

  assertNull(type);
}
项目:google-cloud-eclipse    文件:JavaProjectPipelineOptionsHierarchy.java   
/**
 * Creates a new {@link JavaProjectPipelineOptionsHierarchy}. This can be a long-running method,
 * as it fetches the type hierarchy of the provided project.
 *
 * @throws JavaModelException
 */
public JavaProjectPipelineOptionsHierarchy(
    IJavaProject project, MajorVersion version, IProgressMonitor monitor)
    throws JavaModelException {
  IType rootType = project.findType(PipelineOptionsNamespaces.rootType(version));
  Preconditions.checkNotNull(rootType, "project has no PipelineOptions type");
  Preconditions.checkArgument(rootType.exists(), "PipelineOptions does not exist in project");

  // Flatten the class hierarchy, recording all the classes present
  ITypeHierarchy hierarchy = rootType.newTypeHierarchy(monitor);

  this.project = project;
  this.hierarchy = hierarchy;
  this.majorVersion = version;
  this.knownTypes = new HashMap<>();
}
项目:o3smeasures-tool    文件:DepthOfInheritanceTreeJavaModel.java   
/**
 * @see IJavaModel#calculateValue
 */
@Override
public void calculateValue(ICompilationUnit unit) {

    int length = 0;

    try {
        IType[] types = unit.getAllTypes();
        for (IType type : types) {
            IJavaProject ancestor = (IJavaProject) type.getAncestor(IJavaElement.JAVA_PROJECT);
            ITypeHierarchy th= type.newTypeHierarchy(ancestor, null);

            if (th != null) superclassesList = th.getAllSuperclasses(type);

            if (superclassesList != null) length = superclassesList.length;

            Double value = new BigDecimal(length, new MathContext(2, RoundingMode.UP)).doubleValue();
            setDitValue(value);
        }

    }catch (JavaModelException javaException) {
        logger.error(javaException);
    }catch (NullPointerException nullPointerException){
        logger.error(nullPointerException);
    }
}
项目:o3smeasures-tool    文件:NumberOfChildrenJavaModel.java   
/**
 * @see IJavaModel#calculateValue
 */
@Override
public void calculateValue(ICompilationUnit unit) {

    try {
        int length = 0;

        IType[] types = unit.getAllTypes();
        for (IType type : types) {
            ITypeHierarchy th= type.newTypeHierarchy((IJavaProject) type.getAncestor(IJavaElement.JAVA_PROJECT), null);

            if (th != null) subtypesList = th.getAllSubtypes(type);

            if (subtypesList != null) length = subtypesList.length;

            Double value = new BigDecimal(length, new MathContext(2, RoundingMode.UP)).doubleValue();
            setNocValue(value);
        }

    }catch (JavaModelException exception1) {
        logger.error(exception1);
    }catch (NullPointerException exception2){
        logger.error(exception2);
    }
}
项目:eclipse.jdt.ls    文件:TypeProposalUtils.java   
static IType[] computeInheritancePath(IType subType, IType superType) throws JavaModelException {
    if (superType == null) {
        return null;
    }

    // optimization: avoid building the type hierarchy for the identity case
    if (superType.equals(subType)) {
        return new IType[] { subType };
    }

    ITypeHierarchy hierarchy= subType.newSupertypeHierarchy(new NullProgressMonitor());
    if (!hierarchy.contains(superType))
    {
        return null; // no path
    }

    List<IType> path= new LinkedList<>();
    path.add(superType);
    do {
        // any sub type must be on a hierarchy chain from superType to subType
        superType= hierarchy.getSubtypes(superType)[0];
        path.add(superType);
    } while (!superType.equals(subType)); // since the equality case is handled above, we can spare one check

    return path.toArray(new IType[path.size()]);
}
项目:eclipse.jdt.ls    文件:RippleMethodFinder.java   
private ITypeHierarchy getCachedHierarchy(IType type, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaModelException {
    IType rep = fUnionFind.find(type);
    if (rep != null) {
        Collection<IType> collection = fRootReps.get(rep);
        for (Iterator<IType> iter = collection.iterator(); iter.hasNext();) {
            IType root = iter.next();
            ITypeHierarchy hierarchy = fRootHierarchies.get(root);
            if (hierarchy == null) {
                hierarchy = root.newTypeHierarchy(owner, new SubProgressMonitor(monitor, 1));
                fRootHierarchies.put(root, hierarchy);
            }
            if (hierarchy.contains(type)) {
                return hierarchy;
            }
        }
    }
    return null;
}
项目:eclipse.jdt.ls    文件:JavadocContentAccess.java   
private static Reader findDocInHierarchy(IMethod method, boolean useAttachedJavadoc) throws JavaModelException {
    /*
     * Catch ExternalJavaProject in which case
     * no hierarchy can be built.
     */
    if (!method.getJavaProject().exists()) {
        return null;
    }

    IType type= method.getDeclaringType();
    ITypeHierarchy hierarchy= type.newSupertypeHierarchy(null);

    MethodOverrideTester tester= new MethodOverrideTester(type, hierarchy);

    IType[] superTypes= hierarchy.getAllSupertypes(type);
    for (IType curr : superTypes) {
        IMethod overridden= tester.findOverriddenMethodInType(curr, method);
        if (overridden != null) {
            Reader reader = getHTMLContentReader(overridden, false, useAttachedJavadoc);
            if (reader != null) {
                return reader;
            }
        }
    }
    return null;
}
项目:code    文件:CachedTypeHierarchyEx.java   
/**
 * 
 * @param qName
 * @param doClasses
 * @return the new typeNode for this type, fully completed
 */
private void loadNewTree(String qName) {
    try {
        IType baseType = project.findType(qName);

        if (baseType != null) {
            ITypeHierarchy hierarchy = baseType.newTypeHierarchy(project, null);        
            addInHierarchy(baseType, hierarchy);            

            //XXX. DO NOT call GC directly!
            //Yeah...that just wasted a bunch of resources. Clean up now...
            // Runtime r = Runtime.getRuntime();
            // r.gc();
        }
    } catch (JavaModelException e) {
        //can't really do anything...
        e.printStackTrace();
    }
}
项目:code    文件:CachedTypeHierarchyEx.java   
private void addInHierarchy(IType type, ITypeHierarchy hierarchy) throws JavaModelException {
    String qName = type.getFullyQualifiedName('.');
    TypeNode node = getOrCreateType(qName);

    if (node.isCompleteDown())
        return;

    //Recurse on children
    for (IType sub : hierarchy.getSubtypes(type)) {
        String subName = sub.getFullyQualifiedName('.');
        TypeNode subNode = getOrCreateType(subName);

        node.addSubtype(subNode);
        subNode.addSupertype(node);
        addInHierarchy(sub, hierarchy);
    }
    //we now have everything below this node in the hierarchy.
    node.completedDown();
}
项目:Migrate-Skeletal-Implementation-to-Interface-Refactoring    文件:SkeletalImplementatonClassRemovalUtils.java   
private static boolean superClassImplementsDestinationInterface(IType type, IType destinationInterface,
        Optional<IProgressMonitor> monitor) throws JavaModelException {
    monitor.ifPresent(m -> m.beginTask("Checking superclass ...", IProgressMonitor.UNKNOWN));
    try {
        if (type.getSuperclassName() != null) { // there's a superclass.
            ITypeHierarchy superTypeHierarchy = MigrateSkeletalImplementationToInterfaceRefactoringProcessor
                    .getSuperTypeHierarchy(type,
                            monitor.map(m -> new SubProgressMonitor(m, IProgressMonitor.UNKNOWN)));
            IType superclass = superTypeHierarchy.getSuperclass(type);
            return Arrays.stream(superTypeHierarchy.getAllSuperInterfaces(superclass))
                    .anyMatch(i -> i.equals(destinationInterface));
        }
    } finally {
        monitor.ifPresent(IProgressMonitor::done);
    }

    return true; // vacuously true since there's no superclass.
}
项目:Migrate-Skeletal-Implementation-to-Interface-Refactoring    文件:MigrateSkeletalImplementationToInterfaceRefactoringProcessor.java   
public static ITypeHierarchy getSuperTypeHierarchy(IType type, final Optional<IProgressMonitor> monitor)
        throws JavaModelException {
    try {
        monitor.ifPresent(m -> m.subTask("Retrieving declaring super type hierarchy..."));

        if (getTypeToSuperTypeHierarchyMap().containsKey(type))
            return getTypeToSuperTypeHierarchyMap().get(type);
        else {
            ITypeHierarchy newSupertypeHierarchy = type
                    .newSupertypeHierarchy(monitor.orElseGet(NullProgressMonitor::new));
            getTypeToSuperTypeHierarchyMap().put(type, newSupertypeHierarchy);
            return newSupertypeHierarchy;
        }
    } finally {
        monitor.ifPresent(IProgressMonitor::done);
    }
}
项目:Migrate-Skeletal-Implementation-to-Interface-Refactoring    文件:MigrateSkeletalImplementationToInterfaceRefactoringProcessor.java   
private RefactoringStatus checkAccessedTypes(IMethod sourceMethod, final Optional<IProgressMonitor> monitor,
        final ITypeHierarchy hierarchy) throws JavaModelException {
    final RefactoringStatus result = new RefactoringStatus();
    final IType[] accessedTypes = getTypesReferencedInMovedMembers(sourceMethod, monitor);
    final IType destination = getDestinationInterface(sourceMethod).get();
    final List<IMember> pulledUpList = Arrays.asList(sourceMethod);
    for (IType type : accessedTypes) {
        if (!type.exists())
            continue;

        if (!canBeAccessedFrom(sourceMethod, type, destination, hierarchy) && !pulledUpList.contains(type)) {
            final String message = org.eclipse.jdt.internal.corext.util.Messages.format(
                    PreconditionFailure.TypeNotAccessible.getMessage(),
                    new String[] { JavaElementLabels.getTextLabel(type, JavaElementLabels.ALL_FULLY_QUALIFIED),
                            JavaElementLabels.getTextLabel(destination, JavaElementLabels.ALL_FULLY_QUALIFIED) });
            result.addEntry(RefactoringStatus.ERROR, message, JavaStatusContext.create(type),
                    MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID,
                    PreconditionFailure.TypeNotAccessible.ordinal(), sourceMethod);
            this.getUnmigratableMethods().add(sourceMethod);
        }
    }
    monitor.ifPresent(IProgressMonitor::done);
    return result;
}
项目:Migrate-Skeletal-Implementation-to-Interface-Refactoring    文件:MigrateSkeletalImplementationToInterfaceRefactoringProcessor.java   
private RefactoringStatus checkDeclaringTypeHierarchy(IMethod sourceMethod, Optional<IProgressMonitor> monitor)
        throws JavaModelException {
    try {
        RefactoringStatus status = new RefactoringStatus();
        monitor.ifPresent(m -> m.subTask("Checking declaring type hierarchy..."));

        final ITypeHierarchy declaringTypeHierarchy = this.getDeclaringTypeHierarchy(sourceMethod, monitor);

        status.merge(checkValidClassesInDeclaringTypeHierarchy(sourceMethod, declaringTypeHierarchy));
        status.merge(checkValidInterfacesInDeclaringTypeHierarchy(sourceMethod, monitor));

        return status;
    } finally {
        monitor.ifPresent(IProgressMonitor::done);
    }
}
项目:Migrate-Skeletal-Implementation-to-Interface-Refactoring    文件:MigrateSkeletalImplementationToInterfaceRefactoringProcessor.java   
private RefactoringStatus checkValidClassesInDeclaringTypeHierarchy(IMethod sourceMethod,
        final ITypeHierarchy declaringTypeHierarchy) throws JavaModelException {
    RefactoringStatus status = new RefactoringStatus();

    IType[] allDeclaringTypeSuperclasses = declaringTypeHierarchy
            .getAllSuperclasses(sourceMethod.getDeclaringType());

    // is the source method overriding anything in the declaring type
    // hierarchy? If so, don't allow the refactoring to proceed #107.
    if (Stream.of(allDeclaringTypeSuperclasses).parallel().anyMatch(c -> {
        IMethod[] methods = c.findMethods(sourceMethod);
        return methods != null && methods.length > 0;
    }))
        addErrorAndMark(status, PreconditionFailure.SourceMethodOverridesMethod, sourceMethod);

    return status;
}
项目:che    文件:JavaTypeHierarchy.java   
private void findTypesWithSubMethods(IJavaElement element, List<Type> implementations)
    throws JavaModelException {
  IMethod selectedMethod = (IMethod) element;
  IType parentType = selectedMethod.getDeclaringType();
  if (parentType == null) {
    return;
  }
  ITypeHierarchy typeHierarchy = parentType.newTypeHierarchy(new NullProgressMonitor());
  IType[] subTypes = typeHierarchy.getAllSubtypes(parentType);

  MethodOverrideTester methodOverrideTester = new MethodOverrideTester(parentType, typeHierarchy);

  for (IType type : subTypes) {
    IMethod method = methodOverrideTester.findOverridingMethodInType(type, selectedMethod);
    if (method == null) {
      continue;
    }
    Type openDeclaration = convertToTypeDTO(type);
    setRange(openDeclaration, method);
    implementations.add(openDeclaration);
  }
}
项目:che    文件:SuperTypeHierarchyCache.java   
public static MethodOverrideTester getMethodOverrideTester(IType type) throws JavaModelException {
  MethodOverrideTester test = null;
  synchronized (fgMethodOverrideTesterCache) {
    test = fgMethodOverrideTesterCache.get(type);
  }
  if (test == null) {
    ITypeHierarchy hierarchy = getTypeHierarchy(type); // don't nest the locks
    synchronized (fgMethodOverrideTesterCache) {
      test =
          fgMethodOverrideTesterCache.get(
              type); // test again after waiting a long time for 'getTypeHierarchy'
      if (test == null) {
        test = new MethodOverrideTester(type, hierarchy);
        fgMethodOverrideTesterCache.put(type, test);
      }
    }
  }
  return test;
}
项目:che    文件:SuperTypeHierarchyCache.java   
private static ITypeHierarchy findTypeHierarchyInCache(IType type) {
  synchronized (fgHierarchyCache) {
    for (int i = fgHierarchyCache.size() - 1; i >= 0; i--) {
      HierarchyCacheEntry curr = fgHierarchyCache.get(i);
      ITypeHierarchy hierarchy = curr.getTypeHierarchy();
      if (!hierarchy.exists()) {
        removeHierarchyEntryFromCache(curr);
      } else {
        if (hierarchy.contains(type)) {
          curr.markAsAccessed();
          return hierarchy;
        }
      }
    }
  }
  return null;
}
项目:che    文件:RenameFieldProcessor.java   
/**
 * @return Error message or <code>null</code> if getter can be renamed.
 * @throws CoreException should not happen
 */
public String canEnableGetterRenaming() throws CoreException {
  if (fField.getDeclaringType().isInterface())
    return getGetter() == null ? "" : null; // $NON-NLS-1$

  IMethod getter = getGetter();
  if (getter == null) return ""; // $NON-NLS-1$
  final NullProgressMonitor monitor = new NullProgressMonitor();
  if (MethodChecks.isVirtual(getter)) {
    final ITypeHierarchy hierarchy = getter.getDeclaringType().newTypeHierarchy(monitor);
    if (MethodChecks.isDeclaredInInterface(getter, hierarchy, monitor) != null
        || MethodChecks.overridesAnotherMethod(getter, hierarchy) != null)
      return RefactoringCoreMessages.RenameFieldRefactoring_declared_in_supertype;
  }
  return null;
}
项目:che    文件:RenameFieldProcessor.java   
/**
 * @return Error message or <code>null</code> if setter can be renamed.
 * @throws CoreException should not happen
 */
public String canEnableSetterRenaming() throws CoreException {
  if (fField.getDeclaringType().isInterface())
    return getSetter() == null ? "" : null; // $NON-NLS-1$

  IMethod setter = getSetter();
  if (setter == null) return ""; // $NON-NLS-1$
  final NullProgressMonitor monitor = new NullProgressMonitor();
  if (MethodChecks.isVirtual(setter)) {
    final ITypeHierarchy hierarchy = setter.getDeclaringType().newTypeHierarchy(monitor);
    if (MethodChecks.isDeclaredInInterface(setter, hierarchy, monitor) != null
        || MethodChecks.overridesAnotherMethod(setter, hierarchy) != null)
      return RefactoringCoreMessages.RenameFieldRefactoring_declared_in_supertype;
  }
  return null;
}
项目:che    文件:MethodChecks.java   
public static RefactoringStatus checkIfOverridesAnother(IMethod method, ITypeHierarchy hierarchy)
    throws JavaModelException {
  IMethod overrides = MethodChecks.overridesAnotherMethod(method, hierarchy);
  if (overrides == null) return null;

  RefactoringStatusContext context = JavaStatusContext.create(overrides);
  String message =
      Messages.format(
          RefactoringCoreMessages.MethodChecks_overrides,
          new String[] {
            JavaElementUtil.createMethodSignature(overrides),
            JavaElementLabels.getElementLabel(
                overrides.getDeclaringType(), JavaElementLabels.ALL_FULLY_QUALIFIED)
          });
  return RefactoringStatus.createStatus(
      RefactoringStatus.FATAL,
      message,
      context,
      Corext.getPluginId(),
      RefactoringStatusCodes.OVERRIDES_ANOTHER_METHOD,
      overrides);
}
项目:che    文件:MethodChecks.java   
public static RefactoringStatus checkIfComesFromInterface(
    IMethod method, ITypeHierarchy hierarchy, IProgressMonitor monitor)
    throws JavaModelException {
  IMethod inInterface = MethodChecks.isDeclaredInInterface(method, hierarchy, monitor);

  if (inInterface == null) return null;

  RefactoringStatusContext context = JavaStatusContext.create(inInterface);
  String message =
      Messages.format(
          RefactoringCoreMessages.MethodChecks_implements,
          new String[] {
            JavaElementUtil.createMethodSignature(inInterface),
            JavaElementLabels.getElementLabel(
                inInterface.getDeclaringType(), JavaElementLabels.ALL_FULLY_QUALIFIED)
          });
  return RefactoringStatus.createStatus(
      RefactoringStatus.FATAL,
      message,
      context,
      Corext.getPluginId(),
      RefactoringStatusCodes.METHOD_DECLARED_IN_INTERFACE,
      inInterface);
}
项目:che    文件:MethodChecks.java   
/**
 * Locates the topmost method of an override ripple and returns it. If none is found, null is
 * returned.
 *
 * @param method the IMethod which may be part of a ripple
 * @param typeHierarchy a ITypeHierarchy of the declaring type of the method. May be null
 * @param monitor an IProgressMonitor
 * @return the topmost method of the ripple, or null if none
 * @throws JavaModelException
 */
public static IMethod getTopmostMethod(
    IMethod method, ITypeHierarchy typeHierarchy, IProgressMonitor monitor)
    throws JavaModelException {

  Assert.isNotNull(method);

  ITypeHierarchy hierarchy = typeHierarchy;
  IMethod topmostMethod = null;
  final IType declaringType = method.getDeclaringType();
  if (!declaringType.isInterface()) {
    if ((hierarchy == null) || !declaringType.equals(hierarchy.getType()))
      hierarchy = declaringType.newTypeHierarchy(monitor);

    IMethod inInterface = isDeclaredInInterface(method, hierarchy, monitor);
    if (inInterface != null && !inInterface.equals(method)) topmostMethod = inInterface;
  }
  if (topmostMethod == null) {
    if (hierarchy == null) hierarchy = declaringType.newSupertypeHierarchy(monitor);
    IMethod overrides = overridesAnotherMethod(method, hierarchy);
    if (overrides != null && !overrides.equals(method)) topmostMethod = overrides;
  }
  return topmostMethod;
}
项目:che    文件:RenameMethodProcessor.java   
private static IMethod[] classesDeclareMethodName(
    ITypeHierarchy hier, List<IType> classes, IMethod method, String newName)
    throws CoreException {
  Set<IMethod> result = new HashSet<IMethod>();
  IType type = method.getDeclaringType();
  List<IType> subtypes = Arrays.asList(hier.getAllSubtypes(type));

  int parameterCount = method.getParameterTypes().length;
  boolean isMethodPrivate = JdtFlags.isPrivate(method);

  for (Iterator<IType> iter = classes.iterator(); iter.hasNext(); ) {
    IType clazz = iter.next();
    IMethod[] methods = clazz.getMethods();
    boolean isSubclass = subtypes.contains(clazz);
    for (int j = 0; j < methods.length; j++) {
      IMethod foundMethod =
          Checks.findMethod(newName, parameterCount, false, new IMethod[] {methods[j]});
      if (foundMethod == null) continue;
      if (isSubclass || type.equals(clazz)) result.add(foundMethod);
      else if ((!isMethodPrivate) && (!JdtFlags.isPrivate(methods[j]))) result.add(foundMethod);
    }
  }
  return result.toArray(new IMethod[result.size()]);
}
项目:che    文件:RenameMethodProcessor.java   
static final IMethod[] hierarchyDeclaresMethodName(
    IProgressMonitor pm, ITypeHierarchy hierarchy, IMethod method, String newName)
    throws CoreException {
  try {
    Set<IMethod> result = new HashSet<IMethod>();
    IType type = method.getDeclaringType();
    IMethod foundMethod =
        Checks.findMethod(newName, method.getParameterTypes().length, false, type);
    if (foundMethod != null) result.add(foundMethod);
    IMethod[] foundInHierarchyClasses =
        classesDeclareMethodName(
            hierarchy, Arrays.asList(hierarchy.getAllClasses()), method, newName);
    if (foundInHierarchyClasses != null) result.addAll(Arrays.asList(foundInHierarchyClasses));
    IType[] implementingClasses = hierarchy.getImplementingClasses(type);
    IMethod[] foundInImplementingClasses =
        classesDeclareMethodName(hierarchy, Arrays.asList(implementingClasses), method, newName);
    if (foundInImplementingClasses != null)
      result.addAll(Arrays.asList(foundInImplementingClasses));
    return result.toArray(new IMethod[result.size()]);
  } finally {
    if (pm != null) {
      pm.done();
    }
  }
}
项目:che    文件:RippleMethodFinder2.java   
private ITypeHierarchy getCachedHierarchy(
    IType type, WorkingCopyOwner owner, IProgressMonitor monitor) throws JavaModelException {
  IType rep = fUnionFind.find(type);
  if (rep != null) {
    Collection<IType> collection = fRootReps.get(rep);
    for (Iterator<IType> iter = collection.iterator(); iter.hasNext(); ) {
      IType root = iter.next();
      ITypeHierarchy hierarchy = fRootHierarchies.get(root);
      if (hierarchy == null) {
        hierarchy = root.newTypeHierarchy(owner, new SubProgressMonitor(monitor, 1));
        fRootHierarchies.put(root, hierarchy);
      }
      if (hierarchy.contains(type)) return hierarchy;
    }
  }
  return null;
}
项目:che    文件:InlineMethodRefactoring.java   
private void checkOverridden(RefactoringStatus status, IProgressMonitor pm)
    throws JavaModelException {
  pm.beginTask("", 9); // $NON-NLS-1$
  pm.setTaskName(RefactoringCoreMessages.InlineMethodRefactoring_checking_overridden);
  MethodDeclaration decl = fSourceProvider.getDeclaration();
  IMethod method = (IMethod) decl.resolveBinding().getJavaElement();
  if (method == null || Flags.isPrivate(method.getFlags())) {
    pm.worked(8);
    return;
  }
  IType type = method.getDeclaringType();
  ITypeHierarchy hierarchy = type.newTypeHierarchy(new SubProgressMonitor(pm, 6));
  checkSubTypes(status, method, hierarchy.getAllSubtypes(type), new SubProgressMonitor(pm, 1));
  checkSuperClasses(
      status, method, hierarchy.getAllSuperclasses(type), new SubProgressMonitor(pm, 1));
  checkSuperInterfaces(
      status, method, hierarchy.getAllSuperInterfaces(type), new SubProgressMonitor(pm, 1));
  pm.setTaskName(""); // $NON-NLS-1$
}
项目:che    文件:ReplaceInvocationsRefactoring.java   
private void checkOverridden(RefactoringStatus status, IProgressMonitor pm)
    throws JavaModelException {
  pm.beginTask("", 9); // $NON-NLS-1$
  pm.setTaskName(RefactoringCoreMessages.InlineMethodRefactoring_checking_overridden);
  MethodDeclaration decl = fSourceProvider.getDeclaration();
  IMethod method = (IMethod) decl.resolveBinding().getJavaElement();
  if (method == null || Flags.isPrivate(method.getFlags())) {
    pm.worked(8);
    return;
  }
  IType type = method.getDeclaringType();
  ITypeHierarchy hierarchy = type.newTypeHierarchy(new SubProgressMonitor(pm, 6));
  checkSubTypes(status, method, hierarchy.getAllSubtypes(type), new SubProgressMonitor(pm, 1));
  checkSuperClasses(
      status, method, hierarchy.getAllSuperclasses(type), new SubProgressMonitor(pm, 1));
  checkSuperInterfaces(
      status, method, hierarchy.getAllSuperInterfaces(type), new SubProgressMonitor(pm, 1));
  pm.setTaskName(""); // $NON-NLS-1$
}
项目:che    文件:LazyGenericTypeProposal.java   
/**
 * Computes one inheritance path from <code>superType</code> to <code>subType</code> or <code>null
 * </code> if <code>subType</code> does not inherit from <code>superType</code>. Note that there
 * may be more than one inheritance path - this method simply returns one.
 *
 * <p>The returned array contains <code>superType</code> at its first index, and <code>subType
 * </code> at its last index. If <code>subType</code> equals <code>superType</code> , an array of
 * length 1 is returned containing that type.
 *
 * @param subType the sub type
 * @param superType the super type
 * @return an inheritance path from <code>superType</code> to <code>subType</code>, or <code>null
 *     </code> if <code>subType</code> does not inherit from <code>superType</code>
 * @throws org.eclipse.jdt.core.JavaModelException if this element does not exist or if an
 *     exception occurs while accessing its corresponding resource
 */
private IType[] computeInheritancePath(IType subType, IType superType) throws JavaModelException {
  if (superType == null) return null;

  // optimization: avoid building the type hierarchy for the identity case
  if (superType.equals(subType)) return new IType[] {subType};

  ITypeHierarchy hierarchy = subType.newSupertypeHierarchy(getProgressMonitor());
  if (!hierarchy.contains(superType)) return null; // no path

  List<IType> path = new LinkedList<IType>();
  path.add(superType);
  do {
    // any sub type must be on a hierarchy chain from superType to subType
    superType = hierarchy.getSubtypes(superType)[0];
    path.add(superType);
  } while (!superType.equals(
      subType)); // since the equality case is handled above, we can spare one check

  return path.toArray(new IType[path.size()]);
}
项目:che    文件:ContentAssistHistory.java   
/**
 * Remembers the selection of a right hand side type (proposal type) for a certain left hand side
 * (expected type) in content assist.
 *
 * @param lhs the left hand side / expected type
 * @param rhs the selected right hand side
 */
public void remember(IType lhs, IType rhs) {
  Assert.isLegal(lhs != null);
  Assert.isLegal(rhs != null);

  try {
    if (!isCacheableRHS(rhs)) return;
    ITypeHierarchy hierarchy = rhs.newSupertypeHierarchy(getProgressMonitor());
    if (hierarchy.contains(lhs)) {
      // TODO remember for every member of the LHS hierarchy or not? Yes for now.
      IType[] allLHSides = hierarchy.getAllSupertypes(lhs);
      String rhsQualifiedName = rhs.getFullyQualifiedName();
      for (int i = 0; i < allLHSides.length; i++)
        rememberInternal(allLHSides[i], rhsQualifiedName);
      rememberInternal(lhs, rhsQualifiedName);
    }
  } catch (JavaModelException x) {
    JavaPlugin.log(x);
  }
}
项目:che    文件:JavadocContentAccess2.java   
/**
 * Finds the first available attached Javadoc in the hierarchy of the given method.
 *
 * @param method the method
 * @return the inherited Javadoc from the Javadoc attachment, or <code>null</code> if none
 * @throws org.eclipse.jdt.core.JavaModelException unexpected problem
 */
private static String findAttachedDocInHierarchy(final IMethod method) throws JavaModelException {
  IType type = method.getDeclaringType();
  ITypeHierarchy hierarchy = SuperTypeHierarchyCache.getTypeHierarchy(type);
  final MethodOverrideTester tester = SuperTypeHierarchyCache.getMethodOverrideTester(type);

  return (String)
      new InheritDocVisitor() {
        @Override
        public Object visit(IType currType) throws JavaModelException {
          IMethod overridden = tester.findOverriddenMethodInType(currType, method);
          if (overridden == null) return InheritDocVisitor.CONTINUE;

          if (overridden.getOpenable().getBuffer() == null) { // only if no source available
            // TODO: BaseURL for method can be wrong for attached Javadoc from overridden
            // (e.g. when overridden is from rt.jar). Fix would be to add baseURL here.
            String attachedJavadoc = overridden.getAttachedJavadoc(null);
            if (attachedJavadoc != null) return attachedJavadoc;
          }
          return CONTINUE;
        }
      }.visitInheritDoc(type, hierarchy);
}
项目:gwt-eclipse-plugin    文件:TypeHierarchyCache.java   
public void typeHierarchyChanged(ITypeHierarchy typeHierarchy) {
  try {
    IType type = typeHierarchy.getType();
    if (type.exists()) {
      typeHierarchy.refresh(null);
    } else {
      synchronized (hierarchies) {
        // Prune non-existent types from the cache
        hierarchies.remove(type);
      }
    }
  } catch (JavaModelException e) {
    CorePluginLog.logError(e, "Could not refresh the type hierarchy of "
        + typeHierarchy.getType().getElementName());
  }
}
项目:gwt-eclipse-plugin    文件:ResourceTypeDefaultExtensions.java   
/**
 * Find all default extensions for this resource type. If the type itself does
 * not declare any extensions, it may inherit extensions from any of the
 * interfaces in its super type hierarchy.
 */
public static String[] getDefaultExtensions(IType resourceType)
    throws JavaModelException {
  String[] extensions = getDeclaredDefaultExtensions(resourceType);

  // Check the super interface hierarchy for @DefaultExtensions
  if (extensions.length == 0) {
    ITypeHierarchy superHierarchy = resourceType.newSupertypeHierarchy(null);
    IType[] superInterfaces = superHierarchy.getAllSuperInterfaces(resourceType);
    for (IType superInterface : superInterfaces) {
      extensions = getDeclaredDefaultExtensions(superInterface);
      if (extensions.length > 0) {
        break;
      }
    }
  }
  return extensions;
}
项目:gwt-eclipse-plugin    文件:GWTJUnitPropertyTester.java   
private static boolean isGWTTestCaseOrSuite(IType type) {
  try {
    ITypeHierarchy hierarchy = type.newSupertypeHierarchy(null);
    IType[] superclasses = hierarchy.getAllSuperclasses(type);
    for (IType superclass : superclasses) {
      if (GWT_TEST_CASE.equals(superclass.getFullyQualifiedName())
          || GWT_TEST_SUITE.equals(superclass.getFullyQualifiedName())) {
        return true;
      }
    }
    return false;
  } catch (CoreException e) {
    GWTPluginLog.logError(e);
    return false;
  }
}
项目:jenerate    文件:DialogFactoryHelperImpl.java   
@Override
public boolean isOverriddenInSuperclass(IType objectClass, String methodName,
        String[] methodParameterTypeSignatures, String originalClassFullyQualifiedName) throws JavaModelException {
    ITypeHierarchy typeHierarchy = objectClass.newSupertypeHierarchy(null);
    IType[] superclasses = typeHierarchy.getAllSuperclasses(objectClass);

    if (superclasses.length == 0) {
        return false;
    }

    for (IType superclass : superclasses) {
        if (superclass.getFullyQualifiedName().equals(originalClassFullyQualifiedName)) {
            return false;
        }

        IMethod method = superclass.getMethod(methodName, methodParameterTypeSignatures);
        if (method.exists()) {
            return !Flags.isAbstract(method.getFlags());
        }
    }

    return false;
}
项目:jenerate    文件:JavaInterfaceCodeAppenderImpl.java   
@Override
public boolean isImplementedInSupertype(final IType objectClass, final String interfaceName)
        throws JavaModelException {

    String simpleName = getSimpleInterfaceName(interfaceName);

    ITypeHierarchy typeHierarchy = objectClass.newSupertypeHierarchy(null);
    IType[] interfaces = typeHierarchy.getAllInterfaces();
    for (int i = 0; i < interfaces.length; i++) {
        if (interfaces[i].getElementName().equals(simpleName)) {
            IType in = interfaces[i];
            IType[] types = typeHierarchy.getImplementingClasses(in);
            for (int j = 0; j < types.length; j++) {
                if (!types[j].getFullyQualifiedName().equals(objectClass.getFullyQualifiedName())) {
                    return true;
                }
            }
            break;
        }
    }
    return false;
}
项目:jenerate    文件:JavaInterfaceCodeAppenderImpl.java   
@Override
public boolean isImplementedOrExtendedInSupertype(final IType objectClass, final String interfaceName)
        throws JavaModelException {

    if (isImplementedInSupertype(objectClass, interfaceName)) {
        return true;
    }

    String simpleName = getSimpleInterfaceName(interfaceName);

    ITypeHierarchy typeHierarchy = objectClass.newSupertypeHierarchy(null);
    IType[] interfaces = typeHierarchy.getAllInterfaces();
    for (int i = 0; i < interfaces.length; i++) {
        if (interfaces[i].getElementName().equals(simpleName)) {
            IType in = interfaces[i];
            IType[] types = typeHierarchy.getExtendingInterfaces(in);
            for (int j = 0; j < types.length; j++) {
                if (!types[j].getFullyQualifiedName().equals(objectClass.getFullyQualifiedName())) {
                    return true;
                }
            }
            break;
        }
    }
    return false;
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:SuperTypeHierarchyCache.java   
private static ITypeHierarchy findTypeHierarchyInCache(IType type) {
    synchronized (fgHierarchyCache) {
        for (int i= fgHierarchyCache.size() - 1; i>= 0; i--) {
            HierarchyCacheEntry curr= fgHierarchyCache.get(i);
            ITypeHierarchy hierarchy= curr.getTypeHierarchy();
            if (!hierarchy.exists()) {
                removeHierarchyEntryFromCache(curr);
            } else {
                if (hierarchy.contains(type)) {
                    curr.markAsAccessed();
                    return hierarchy;
                }
            }
        }
    }
    return null;
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:PushDownRefactoringProcessor.java   
private RefactoringStatus checkAccessedFields(IType[] subclasses, IProgressMonitor pm) throws JavaModelException {
    RefactoringStatus result= new RefactoringStatus();
    IMember[] membersToPushDown= MemberActionInfo.getMembers(getInfosForMembersToBeCreatedInSubclassesOfDeclaringClass());
    List<IMember> pushedDownList= Arrays.asList(membersToPushDown);
    IField[] accessedFields= ReferenceFinderUtil.getFieldsReferencedIn(membersToPushDown, pm);
    for (int i= 0; i < subclasses.length; i++) {
        IType targetClass= subclasses[i];
        ITypeHierarchy targetSupertypes= targetClass.newSupertypeHierarchy(null);
        for (int j= 0; j < accessedFields.length; j++) {
            IField field= accessedFields[j];
            boolean isAccessible= pushedDownList.contains(field) || canBeAccessedFrom(field, targetClass, targetSupertypes) || Flags.isEnum(field.getFlags());
            if (!isAccessible) {
                String message= Messages.format(RefactoringCoreMessages.PushDownRefactoring_field_not_accessible, new String[] { JavaElementLabels.getTextLabel(field, JavaElementLabels.ALL_FULLY_QUALIFIED), JavaElementLabels.getTextLabel(targetClass, JavaElementLabels.ALL_FULLY_QUALIFIED) });
                result.addError(message, JavaStatusContext.create(field));
            }
        }
    }
    pm.done();
    return result;
}
项目:Eclipse-Postfix-Code-Completion-Juno38    文件:PullUpRefactoringProcessor.java   
private Set<IType> getSkippedSuperTypes(final IProgressMonitor monitor) throws JavaModelException {
    monitor.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking, 1);
    try {
        if (fCachedSkippedSuperTypes != null && getDestinationTypeHierarchy(new SubProgressMonitor(monitor, 1)).getType().equals(getDestinationType()))
            return fCachedSkippedSuperTypes;
        final ITypeHierarchy hierarchy= getDestinationTypeHierarchy(new SubProgressMonitor(monitor, 1));
        fCachedSkippedSuperTypes= new HashSet<IType>(2);
        IType current= hierarchy.getSuperclass(getDeclaringType());
        while (current != null && !current.equals(getDestinationType())) {
            fCachedSkippedSuperTypes.add(current);
            current= hierarchy.getSuperclass(current);
        }
        return fCachedSkippedSuperTypes;
    } finally {
        monitor.done();
    }
}