public static IMethod getGetter(IField field) throws JavaModelException {
   String getterName = getGetterName(field, EMPTY, true);
   IMethod primaryCandidate =
       JavaModelUtil.findMethod(getterName, new String[0], false, field.getDeclaringType());
   if (!JavaModelUtil.isBoolean(field) || (primaryCandidate != null && primaryCandidate.exists()))
     return primaryCandidate;
   // bug 30906 describes why we need to look for other alternatives here (try with get... for
   // booleans)
   String secondCandidateName = getGetterName(field, EMPTY, false);
   return JavaModelUtil.findMethod(
       secondCandidateName, new String[0], false, field.getDeclaringType());
 }
  private void rewriteImports() {
    if (fImportRewrite == null) return;

    if (isReadOnly()) return;

    ICompilationUnit cu = getCompilationUnit();
    if (cu == null) return;

    try {
      Position position = new Position(getCompletionOffset(), 0);
      IDocument document = getDocument();
      final String category =
          "__template_position_importer" + System.currentTimeMillis(); // $NON-NLS-1$
      IPositionUpdater updater = new DefaultPositionUpdater(category);
      document.addPositionCategory(category);
      document.addPositionUpdater(updater);
      document.addPosition(position);

      try {
        JavaModelUtil.applyEdit(cu, fImportRewrite.rewriteImports(null), false, null);

        setCompletionOffset(position.getOffset());
      } catch (CoreException e) {
        handleException(null, e);
      } finally {
        document.removePosition(position);
        document.removePositionUpdater(updater);
        document.removePositionCategory(category);
      }
    } catch (BadLocationException e) {
      handleException(null, e);
    } catch (BadPositionCategoryException e) {
      handleException(null, e);
    }
  }
  public static ICleanUpFix createCleanUp(
      CompilationUnit compilationUnit,
      IProblemLocation[] problems,
      boolean addOverrideAnnotation,
      boolean addOverrideInterfaceAnnotation,
      boolean addDeprecatedAnnotation,
      boolean rawTypeReferences) {

    ICompilationUnit cu = (ICompilationUnit) compilationUnit.getJavaElement();
    if (!JavaModelUtil.is50OrHigher(cu.getJavaProject())) return null;

    if (!addOverrideAnnotation && !addDeprecatedAnnotation && !rawTypeReferences) return null;

    List /*<CompilationUnitRewriteOperation>*/ operations = new ArrayList();

    if (addOverrideAnnotation)
      createAddOverrideAnnotationOperations(
          compilationUnit, addOverrideInterfaceAnnotation, problems, operations);

    if (addDeprecatedAnnotation)
      createAddDeprecatedAnnotationOperations(compilationUnit, problems, operations);

    if (rawTypeReferences) createRawTypeReferenceOperations(compilationUnit, problems, operations);

    if (operations.size() == 0) return null;

    CompilationUnitRewriteOperation[] operationsArray =
        (CompilationUnitRewriteOperation[])
            operations.toArray(new CompilationUnitRewriteOperation[operations.size()]);
    return new Java50Fix(
        FixMessages.Java50Fix_add_annotations_change_name, compilationUnit, operationsArray);
  }
Exemplo n.º 4
0
  public static URL getJavadocBaseLocation(IJavaElement element) throws JavaModelException {
    if (element.getElementType() == IJavaElement.JAVA_PROJECT) {
      return getProjectJavadocLocation((IJavaProject) element);
    }

    IPackageFragmentRoot root = JavaModelUtil.getPackageFragmentRoot(element);
    if (root == null) {
      return null;
    }

    if (root.getKind() == IPackageFragmentRoot.K_BINARY) {
      IClasspathEntry entry = root.getResolvedClasspathEntry();
      URL javadocLocation = getLibraryJavadocLocation(entry);
      if (javadocLocation != null) {
        return getLibraryJavadocLocation(entry);
      }
      entry = root.getRawClasspathEntry();
      switch (entry.getEntryKind()) {
        case IClasspathEntry.CPE_LIBRARY:
        case IClasspathEntry.CPE_VARIABLE:
          return getLibraryJavadocLocation(entry);
        default:
          return null;
      }
    } else {
      return getProjectJavadocLocation(root.getJavaProject());
    }
  }
 /**
  * Initializes the source folder field with a valid package fragment root. The package fragment
  * root is computed from the given Java element.
  *
  * @param elem the Java element used to compute the initial package fragment root used as the
  *     source folder
  */
 protected void initContainerPage(IJavaElement elem) {
   IPackageFragmentRoot initRoot = null;
   if (elem != null) {
     initRoot = JavaModelUtil.getPackageFragmentRoot(elem);
     try {
       if (initRoot == null || initRoot.getKind() != IPackageFragmentRoot.K_SOURCE) {
         IJavaProject jproject = elem.getJavaProject();
         if (jproject != null) {
           initRoot = null;
           if (jproject.exists()) {
             IPackageFragmentRoot[] roots = jproject.getPackageFragmentRoots();
             for (int i = 0; i < roots.length; i++) {
               if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
                 initRoot = roots[i];
                 break;
               }
             }
           }
           if (initRoot == null) {
             initRoot = jproject.getPackageFragmentRoot(jproject.getResource());
           }
         }
       }
     } catch (JavaModelException e) {
       JavaPlugin.log(e);
     }
   }
   setPackageFragmentRoot(initRoot, true);
 }
Exemplo n.º 6
0
  public void switchToJavaEditor(IType type, String methodName, List<String> parameterTypes) {
    JavaEditor javaEditor = openJavaEditor(type);
    if (javaEditor == null) {
      return;
    }

    IMethod newMethod = null;
    try {
      String[] parameterTypeSignatures = new String[parameterTypes.size()];
      for (int i = 0; i < parameterTypeSignatures.length; i++) {
        String qualifiedName = parameterTypes.get(i);
        String signature = Signature.createTypeSignature(qualifiedName, true);
        parameterTypeSignatures[i] = signature;
      }

      newMethod = JavaModelUtil.findMethod(methodName, parameterTypeSignatures, false, type);
    } catch (JavaModelException e) {
      // ignore this
    }

    if (newMethod == null) {
      return;
    }

    javaEditor.setSelection(newMethod);
  }
Exemplo n.º 7
0
 public String getNewSetterName() throws CoreException {
   return GetterSetterUtil.getSetterName(
       fField.getJavaProject(),
       getNewElementName(),
       fField.getFlags(),
       JavaModelUtil.isBoolean(fField),
       null);
 }
Exemplo n.º 8
0
  private IField getFieldInWorkingCopy(
      ICompilationUnit newWorkingCopyOfDeclaringCu, String elementName) {
    IType type = fField.getDeclaringType();
    IType typeWc = (IType) JavaModelUtil.findInCompilationUnit(newWorkingCopyOfDeclaringCu, type);
    if (typeWc == null) return null;

    return typeWc.getField(elementName);
  }
Exemplo n.º 9
0
 @Override
 public void selectionChanged(IStructuredSelection selection) {
   try {
     setEnabled(RefactoringAvailabilityTester.isGeneralizeTypeAvailable(selection));
   } catch (JavaModelException e) {
     if (JavaModelUtil.isExceptionToBeLogged(e)) JavaPlugin.log(e);
     setEnabled(false);
   }
 }
Exemplo n.º 10
0
 public String getNewGetterName() throws CoreException {
   IMethod primaryGetterCandidate =
       JavaModelUtil.findMethod(
           GetterSetterUtil.getGetterName(fField, new String[0]),
           new String[0],
           false,
           fField.getDeclaringType());
   if (!JavaModelUtil.isBoolean(fField)
       || (primaryGetterCandidate != null && primaryGetterCandidate.exists()))
     return GetterSetterUtil.getGetterName(
         fField.getJavaProject(),
         getNewElementName(),
         fField.getFlags(),
         JavaModelUtil.isBoolean(fField),
         null);
   // bug 30906 describes why we need to look for other alternatives here
   return GetterSetterUtil.getGetterName(
       fField.getJavaProject(), getNewElementName(), fField.getFlags(), false, null);
 }
 private static IMethod findIncludingSupertypes(
     IMethodBinding method, IType type, IProgressMonitor pm) throws JavaModelException {
   IMethod inThisType = Bindings.findMethod(method, type);
   if (inThisType != null) return inThisType;
   IType[] superTypes = JavaModelUtil.getAllSuperTypes(type, pm);
   for (int i = 0; i < superTypes.length; i++) {
     IMethod m = Bindings.findMethod(method, superTypes[i]);
     if (m != null) return m;
   }
   return null;
 }
Exemplo n.º 12
0
  private static void appendMethodReference(IMethod meth, StringBuffer buf)
      throws JavaModelException {
    buf.append(meth.getElementName());

    /*
     * The Javadoc tool for Java SE 8 changed the anchor syntax and now tries to avoid "strange" characters in URLs.
     * This breaks all clients that directly create such URLs.
     * We can't know what format is required, so we just guess by the project's compiler compliance.
     */
    boolean is18OrHigher = JavaModelUtil.is18OrHigher(meth.getJavaProject());
    buf.append(is18OrHigher ? '-' : '(');
    String[] params = meth.getParameterTypes();
    IType declaringType = meth.getDeclaringType();
    boolean isVararg = Flags.isVarargs(meth.getFlags());
    int lastParam = params.length - 1;
    for (int i = 0; i <= lastParam; i++) {
      if (i != 0) {
        buf.append(is18OrHigher ? "-" : ", "); // $NON-NLS-1$ //$NON-NLS-2$
      }
      String curr = Signature.getTypeErasure(params[i]);
      String fullName = JavaModelUtil.getResolvedTypeName(curr, declaringType);
      if (fullName == null) { // e.g. a type parameter "QE;"
        fullName = Signature.toString(Signature.getElementType(curr));
      }
      if (fullName != null) {
        buf.append(fullName);
        int dim = Signature.getArrayCount(curr);
        if (i == lastParam && isVararg) {
          dim--;
        }
        while (dim > 0) {
          buf.append(is18OrHigher ? ":A" : "[]"); // $NON-NLS-1$ //$NON-NLS-2$
          dim--;
        }
        if (i == lastParam && isVararg) {
          buf.append("..."); // $NON-NLS-1$
        }
      }
    }
    buf.append(is18OrHigher ? '-' : ')');
  }
  private RefactoringStatus analyzeRenameChanges(IProgressMonitor pm) throws CoreException {
    ICompilationUnit[] newDeclarationWCs = null;
    try {
      pm.beginTask("", 4); // $NON-NLS-1$
      RefactoringStatus result = new RefactoringStatus();
      ICompilationUnit[] declarationCUs = getDeclarationCUs();
      newDeclarationWCs =
          RenameAnalyzeUtil.createNewWorkingCopies(
              declarationCUs, fChangeManager, fWorkingCopyOwner, new SubProgressMonitor(pm, 1));

      IMethod[] wcOldMethods = new IMethod[fMethodsToRename.size()];
      IMethod[] wcNewMethods = new IMethod[fMethodsToRename.size()];
      int i = 0;
      for (Iterator<IMethod> iter = fMethodsToRename.iterator(); iter.hasNext(); i++) {
        IMethod method = iter.next();
        ICompilationUnit newCu =
            RenameAnalyzeUtil.findWorkingCopyForCu(newDeclarationWCs, method.getCompilationUnit());
        IType typeWc =
            (IType) JavaModelUtil.findInCompilationUnit(newCu, method.getDeclaringType());
        if (typeWc == null) {
          // should not happen
          i--;
          wcOldMethods =
              CollectionsUtil.toArray(
                  Arrays.asList(wcOldMethods).subList(0, wcOldMethods.length - 1), IMethod.class);
          wcNewMethods =
              CollectionsUtil.toArray(
                  Arrays.asList(wcNewMethods).subList(0, wcNewMethods.length - 1), IMethod.class);
          continue;
        }
        wcOldMethods[i] = getMethodInWorkingCopy(method, getCurrentElementName(), typeWc);
        wcNewMethods[i] = getMethodInWorkingCopy(method, getNewElementName(), typeWc);
      }

      //			SearchResultGroup[] newOccurrences= findNewOccurrences(newMethods, newDeclarationWCs, new
      // SubProgressMonitor(pm, 3));
      SearchResultGroup[] newOccurrences =
          batchFindNewOccurrences(
              wcNewMethods, wcOldMethods, newDeclarationWCs, new SubProgressMonitor(pm, 3), result);

      result.merge(
          RenameAnalyzeUtil.analyzeRenameChanges2(
              fChangeManager, fOccurrences, newOccurrences, getNewElementName()));
      return result;
    } finally {
      pm.done();
      if (newDeclarationWCs != null) {
        for (int i = 0; i < newDeclarationWCs.length; i++) {
          newDeclarationWCs[i].discardWorkingCopy();
        }
      }
    }
  }
 private static String getGetterName(
     IField field, String[] excludedNames, boolean useIsForBoolGetters) throws JavaModelException {
   if (excludedNames == null) {
     excludedNames = EMPTY;
   }
   return getGetterName(
       field.getJavaProject(),
       field.getElementName(),
       field.getFlags(),
       useIsForBoolGetters && JavaModelUtil.isBoolean(field),
       excludedNames);
 }
 public static String getSetterName(IField field, String[] excludedNames)
     throws JavaModelException {
   if (excludedNames == null) {
     excludedNames = EMPTY;
   }
   return getSetterName(
       field.getJavaProject(),
       field.getElementName(),
       field.getFlags(),
       JavaModelUtil.isBoolean(field),
       excludedNames);
 }
  private ICompilationUnit[] getCompilationUnits(IStructuredSelection selection) {
    HashSet result = new HashSet();
    Object[] selected = selection.toArray();
    for (int i = 0; i < selected.length; i++) {
      try {
        if (selected[i] instanceof IJavaElement) {
          IJavaElement elem = (IJavaElement) selected[i];
          if (elem.exists()) {

            switch (elem.getElementType()) {
              case IJavaElement.TYPE:
                if (elem.getParent().getElementType() == IJavaElement.COMPILATION_UNIT) {
                  result.add(elem.getParent());
                }
                break;
              case IJavaElement.COMPILATION_UNIT:
                result.add(elem);
                break;
              case IJavaElement.IMPORT_CONTAINER:
                result.add(elem.getParent());
                break;
              case IJavaElement.PACKAGE_FRAGMENT:
                collectCompilationUnits((IPackageFragment) elem, result);
                break;
              case IJavaElement.PACKAGE_FRAGMENT_ROOT:
                collectCompilationUnits((IPackageFragmentRoot) elem, result);
                break;
              case IJavaElement.JAVA_PROJECT:
                IPackageFragmentRoot[] roots = ((IJavaProject) elem).getPackageFragmentRoots();
                for (int k = 0; k < roots.length; k++) {
                  collectCompilationUnits(roots[k], result);
                }
                break;
            }
          }
        } else if (selected[i] instanceof LogicalPackage) {
          IPackageFragment[] packageFragments = ((LogicalPackage) selected[i]).getFragments();
          for (int k = 0; k < packageFragments.length; k++) {
            IPackageFragment pack = packageFragments[k];
            if (pack.exists()) {
              collectCompilationUnits(pack, result);
            }
          }
        }
      } catch (JavaModelException e) {
        if (JavaModelUtil.isExceptionToBeLogged(e)) JavaPlugin.log(e);
      }
    }
    return (ICompilationUnit[]) result.toArray(new ICompilationUnit[result.size()]);
  }
  @Override
  public void run(IProgressMonitor monitor) throws CoreException {
    if (monitor == null) monitor = new NullProgressMonitor();
    try {
      monitor.beginTask("", 1); // $NON-NLS-1$
      monitor.setTaskName(CodeGenerationMessages.GenerateToStringOperation_description);

      AbstractTypeDeclaration declaration =
          (AbstractTypeDeclaration)
              ASTNodes.findDeclaration(fContext.getTypeBinding(), fRewrite.getRoot());
      ListRewrite rewriter =
          fRewrite
              .getASTRewrite()
              .getListRewrite(declaration, declaration.getBodyDeclarationsProperty());
      if (fContext.getTypeBinding() != null && rewriter != null) {

        MethodDeclaration toStringMethod = fGenerator.generateToStringMethod();

        List<BodyDeclaration> list = declaration.bodyDeclarations();
        BodyDeclaration replace = findMethodToReplace(list, toStringMethod);
        if (replace == null
            || ((Boolean)
                    toStringMethod.getProperty(AbstractToStringGenerator.OVERWRITE_METHOD_PROPERTY))
                .booleanValue()) insertMethod(toStringMethod, rewriter, replace);

        List<MethodDeclaration> helperMethods = fGenerator.generateHelperMethods();
        for (Iterator<MethodDeclaration> iterator = helperMethods.iterator();
            iterator.hasNext(); ) {
          MethodDeclaration method = iterator.next();
          replace = findMethodToReplace(list, method);
          if (replace == null
              || ((Boolean) method.getProperty(AbstractToStringGenerator.OVERWRITE_METHOD_PROPERTY))
                  .booleanValue()) {
            insertMethod(method, rewriter, replace);
          }
        }

        JavaModelUtil.applyEdit(
            (ICompilationUnit) fUnit.getJavaElement(),
            fRewrite.createChange(true).getEdit(),
            false,
            monitor);
      }

    } finally {
      monitor.done();
    }
  }
Exemplo n.º 18
0
  private static Java50Fix createFix(
      CompilationUnit compilationUnit, IProblemLocation problem, String annotation, String label) {
    ICompilationUnit cu = (ICompilationUnit) compilationUnit.getJavaElement();
    if (!JavaModelUtil.is50OrHigher(cu.getJavaProject())) return null;

    ASTNode selectedNode = problem.getCoveringNode(compilationUnit);
    if (selectedNode == null) return null;

    ASTNode declaringNode = getDeclaringNode(selectedNode);
    if (!(declaringNode instanceof BodyDeclaration)) return null;

    BodyDeclaration declaration = (BodyDeclaration) declaringNode;

    AnnotationRewriteOperation operation = new AnnotationRewriteOperation(declaration, annotation);

    return new Java50Fix(label, compilationUnit, new CompilationUnitRewriteOperation[] {operation});
  }
Exemplo n.º 19
0
  public static ICleanUpFix createCleanUp(
      CompilationUnit compilationUnit,
      boolean addOverrideAnnotation,
      boolean addOverrideInterfaceAnnotation,
      boolean addDeprecatedAnnotation,
      boolean rawTypeReference) {

    ICompilationUnit cu = (ICompilationUnit) compilationUnit.getJavaElement();
    if (!JavaModelUtil.is50OrHigher(cu.getJavaProject())) return null;

    if (!addOverrideAnnotation && !addDeprecatedAnnotation && !rawTypeReference) return null;

    List /*<CompilationUnitRewriteOperation>*/ operations = new ArrayList();

    IProblem[] problems = compilationUnit.getProblems();
    IProblemLocation[] locations = new IProblemLocation[problems.length];
    for (int i = 0; i < problems.length; i++) {
      locations[i] = new ProblemLocation(problems[i]);
    }

    if (addOverrideAnnotation)
      createAddOverrideAnnotationOperations(
          compilationUnit, addOverrideInterfaceAnnotation, locations, operations);

    if (addDeprecatedAnnotation)
      createAddDeprecatedAnnotationOperations(compilationUnit, locations, operations);

    if (rawTypeReference) createRawTypeReferenceOperations(compilationUnit, locations, operations);

    if (operations.size() == 0) return null;

    String fixName;
    if (rawTypeReference) {
      fixName = FixMessages.Java50Fix_add_type_parameters_change_name;
    } else {
      fixName = FixMessages.Java50Fix_add_annotations_change_name;
    }

    CompilationUnitRewriteOperation[] operationsArray =
        (CompilationUnitRewriteOperation[])
            operations.toArray(new CompilationUnitRewriteOperation[operations.size()]);
    return new Java50Fix(fixName, compilationUnit, operationsArray);
  }
 /**
  * Finds a method declaration in a type's hierarchy. The search is top down, so this returns the
  * first declaration of the method in the hierarchy. This searches for a method with a name and
  * signature. Parameter types are only compared by the simple name, no resolving for the fully
  * qualified type name is done. Constructors are only compared by parameters, not the name.
  *
  * @param type Searches in this type's supertypes.
  * @param name The name of the method to find
  * @param paramTypes The type signatures of the parameters e.g. <code>{"QString;","I"}</code>
  * @param isConstructor If the method is a constructor
  * @return The first method found or null, if nothing found
  */
 private static IMethod findMethodDeclarationInHierarchy(
     ITypeHierarchy hierarchy, IType type, String name, String[] paramTypes, boolean isConstructor)
     throws JavaModelException {
   IType[] superTypes = hierarchy.getAllSupertypes(type);
   for (int i = superTypes.length - 1; i >= 0; i--) {
     IMethod first = JavaModelUtil.findMethod(name, paramTypes, isConstructor, superTypes[i]);
     if (first != null && !Flags.isPrivate(first.getFlags())) {
       // the order getAllSupertypes does make assumptions of the order of inner elements -> search
       // recursively
       IMethod res =
           findMethodDeclarationInHierarchy(
               hierarchy, first.getDeclaringType(), name, paramTypes, isConstructor);
       if (res != null) {
         return res;
       }
       return first;
     }
   }
   return null;
 }
Exemplo n.º 21
0
  private RefactoringStatus checkNewAccessor(IMethod existingAccessor, String newAccessorName)
      throws CoreException {
    RefactoringStatus result = new RefactoringStatus();
    IMethod accessor =
        JavaModelUtil.findMethod(
            newAccessorName,
            existingAccessor.getParameterTypes(),
            false,
            fField.getDeclaringType());
    if (accessor == null || !accessor.exists()) return null;

    String message =
        Messages.format(
            RefactoringCoreMessages.RenameFieldRefactoring_already_exists,
            new String[] {
              JavaElementUtil.createMethodSignature(accessor),
              BasicElementLabels.getJavaElementName(
                  fField.getDeclaringType().getFullyQualifiedName('.'))
            });
    result.addError(message, JavaStatusContext.create(accessor));
    return result;
  }
  /*
   * Finds a type by the simple name. From AddImportsOperation
   */
  private TypeNameMatch[] findAllTypes(
      String simpleTypeName,
      IJavaSearchScope searchScope,
      SimpleName nameNode,
      IProgressMonitor monitor,
      ICompilationUnit cu)
      throws JavaModelException {
    boolean is50OrHigher = JavaModelUtil.is50OrHigher(cu.getJavaProject());

    int typeKinds = SimilarElementsRequestor.ALL_TYPES;
    if (nameNode != null) {
      typeKinds = ASTResolving.getPossibleTypeKinds(nameNode, is50OrHigher);
    }

    ArrayList<TypeNameMatch> typeInfos = new ArrayList<TypeNameMatch>();
    TypeNameMatchCollector requestor = new TypeNameMatchCollector(typeInfos);
    new SearchEngine()
        .searchAllTypeNames(
            null,
            0,
            simpleTypeName.toCharArray(),
            SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE,
            getSearchForConstant(typeKinds),
            searchScope,
            requestor,
            IJavaSearchConstants.FORCE_IMMEDIATE_SEARCH,
            monitor);

    ArrayList<TypeNameMatch> typeRefsFound = new ArrayList<TypeNameMatch>(typeInfos.size());
    for (int i = 0, len = typeInfos.size(); i < len; i++) {
      TypeNameMatch curr = typeInfos.get(i);
      if (curr.getPackageName().length() > 0) { // do not suggest imports from the default package
        if (isOfKind(curr, typeKinds, is50OrHigher) && isVisible(curr, cu)) {
          typeRefsFound.add(curr);
        }
      }
    }
    return typeRefsFound.toArray(new TypeNameMatch[typeRefsFound.size()]);
  }
 private ImportRewrite createImportRewrite() {
   if (fCompilationUnit != null
       && allowAddingImports()
       && !JavaModelUtil.isPackageInfo(fCompilationUnit)) {
     try {
       CompilationUnit cu = getASTRoot(fCompilationUnit);
       if (cu == null) {
         ImportRewrite rewrite = StubUtility.createImportRewrite(fCompilationUnit, true);
         fImportContext = null;
         return rewrite;
       } else {
         ImportRewrite rewrite = StubUtility.createImportRewrite(cu, true);
         fImportContext =
             new ContextSensitiveImportRewriteContext(
                 cu, fInvocationContext.getInvocationOffset(), rewrite);
         return rewrite;
       }
     } catch (CoreException x) {
       JavaPlugin.log(x);
     }
   }
   return null;
 }
Exemplo n.º 24
0
    /**
     * Resolves a type name in the context of the declaring type.
     *
     * @param refTypeSig the type name in signature notation (for example 'QVector') this can also
     *     be an array type, but dimensions will be ignored.
     * @param declaringType the context for resolving (type where the reference was made in)
     * @return returns the fully qualified type name or build-in-type name. if a unresolved type
     *     couldn't be resolved null is returned
     * @throws JavaModelException thrown when the type can not be accessed
     */
    public IType resolveType(String refTypeSig, IType declaringType) throws JavaModelException {
      IJavaProject javaProject = declaringType.getJavaProject();

      int arrayCount = Signature.getArrayCount(refTypeSig);
      char type = refTypeSig.charAt(arrayCount);
      if (type == Signature.C_UNRESOLVED) {
        String name = ""; // $NON-NLS-1$
        int bracket = refTypeSig.indexOf(Signature.C_GENERIC_START, arrayCount + 1);
        if (bracket > 0) name = refTypeSig.substring(arrayCount + 1, bracket);
        else {
          int semi = refTypeSig.indexOf(Signature.C_SEMICOLON, arrayCount + 1);
          if (semi == -1) {
            throw new IllegalArgumentException();
          }
          name = refTypeSig.substring(arrayCount + 1, semi);
        }

        String dotTypeName = "." + name;
        String dotBaseTypeName = null;
        String dotExtensionTypeName = null;
        int dotIndex = name.indexOf('.');
        if (dotIndex != -1) {
          // We might get a fully qualified type name -- Qcom.apple.jingle.eo.MZProgramNodeType;
          IType resolvedType = javaProject.findType(name);
          if (resolvedType != null) {
            return resolvedType;
          }
          // If not, then this might be a nested type reference on another type, so let's split it
          // to look for that in our imports later
          dotBaseTypeName = "." + name.substring(0, dotIndex);
          dotExtensionTypeName = name.substring(dotIndex);
        }

        IImportDeclaration[] importDeclarations = declaringType.getCompilationUnit().getImports();
        // Loop over the imports and look for the import of our symbol
        for (IImportDeclaration declaration : importDeclarations) {
          String importName = declaration.getElementName();
          // If it's a .* import, then pop off the package name and lookup the type
          if (declaration.isOnDemand()) {
            String packageName = importName.substring(0, importName.lastIndexOf('.'));
            String possibleTypeName = packageName + dotTypeName;
            IType onDemandPackageType = javaProject.findType(possibleTypeName);
            if (onDemandPackageType != null) {
              return onDemandPackageType;
            }
          }
          // If it's not a .* import, then does the import end with our type name?
          else if (importName.endsWith(dotTypeName)) {
            IType importType = javaProject.findType(importName);
            if (importType != null) {
              return importType;
            }
          }
          // If it doesn't, check to see if we were a dotted type ("Outer.Inner") and check to see
          // if Outer is imported
          else if (dotBaseTypeName != null && importName.endsWith(dotBaseTypeName)) {
            // ... then look for Outer.Inner
            IType importNestedType = javaProject.findType(importName + dotExtensionTypeName);
            if (importNestedType != null) {
              return importNestedType;
            }
          }
        }

        // Is this a java.lang.Xxx class that we get for free?
        String javaLangTypeName = "java.lang" + dotTypeName;
        IType javaLangType = javaProject.findType(javaLangTypeName);
        if (javaLangType != null) {
          return javaLangType;
        }

        // What about an inner type of our own class?
        String innerTypeName = declaringType.getFullyQualifiedName('.') + dotTypeName;
        IType innerType = javaProject.findType(innerTypeName);
        if (innerType != null) {
          return innerType;
        }

        // Are we declared in a package?
        IPackageFragment declaringTypePackageFragment = declaringType.getPackageFragment();
        if (declaringTypePackageFragment != null) {
          // ... if so, is this name in our package, so it didn't need an import?
          String samePackageTypeName = declaringTypePackageFragment.getElementName() + dotTypeName;
          IType samePackageType = javaProject.findType(samePackageTypeName);
          if (samePackageType != null) {
            return samePackageType;
          }
        } else {
          // If we were in the default package, is that class in the default package too?
          IType defaultPackageType = javaProject.findType(name);
          if (defaultPackageType != null) {
            return defaultPackageType;
          }
        }

        String slowResolvedTypeName = JavaModelUtil.getResolvedTypeName(refTypeSig, _type);
        if (slowResolvedTypeName != null) {
          IType slowResolvedType = javaProject.findType(slowResolvedTypeName);
          if (slowResolvedType != null) {
            return slowResolvedType;
          }
        }

        return null;
      } else {
        // We were given an Lxxx; signature ... just look it up
        String resolvedTypeName = Signature.toString(refTypeSig.substring(arrayCount));
        IType resolvedType = javaProject.findType(resolvedTypeName);
        return resolvedType;
      }
    }
Exemplo n.º 25
0
  public static URL getJavadocLocation(IJavaElement element, boolean includeMemberReference)
      throws JavaModelException {
    URL baseLocation = getJavadocBaseLocation(element);
    if (baseLocation == null) {
      return null;
    }

    String urlString = baseLocation.toExternalForm();

    StringBuffer urlBuffer = new StringBuffer(urlString);
    if (!urlString.endsWith("/")) { // $NON-NLS-1$
      urlBuffer.append('/');
    }

    StringBuffer pathBuffer = new StringBuffer();
    StringBuffer fragmentBuffer = new StringBuffer();

    switch (element.getElementType()) {
      case IJavaElement.PACKAGE_FRAGMENT:
        appendPackageSummaryPath((IPackageFragment) element, pathBuffer);
        break;
      case IJavaElement.JAVA_PROJECT:
      case IJavaElement.PACKAGE_FRAGMENT_ROOT:
        appendIndexPath(pathBuffer);
        break;
      case IJavaElement.IMPORT_CONTAINER:
        element = element.getParent();
        // $FALL-THROUGH$
      case IJavaElement.COMPILATION_UNIT:
        IType mainType = ((ICompilationUnit) element).findPrimaryType();
        if (mainType == null) {
          return null;
        }
        appendTypePath(mainType, pathBuffer);
        break;
      case IJavaElement.CLASS_FILE:
        appendTypePath(((IClassFile) element).getType(), pathBuffer);
        break;
      case IJavaElement.TYPE:
        appendTypePath((IType) element, pathBuffer);
        break;
      case IJavaElement.FIELD:
        IField field = (IField) element;
        appendTypePath(field.getDeclaringType(), pathBuffer);
        if (includeMemberReference) {
          appendFieldReference(field, fragmentBuffer);
        }
        break;
      case IJavaElement.METHOD:
        IMethod method = (IMethod) element;
        appendTypePath(method.getDeclaringType(), pathBuffer);
        if (includeMemberReference) {
          appendMethodReference(method, fragmentBuffer);
        }
        break;
      case IJavaElement.INITIALIZER:
        appendTypePath(((IMember) element).getDeclaringType(), pathBuffer);
        break;
      case IJavaElement.IMPORT_DECLARATION:
        IImportDeclaration decl = (IImportDeclaration) element;

        if (decl.isOnDemand()) {
          IJavaElement cont =
              JavaModelUtil.findTypeContainer(
                  element.getJavaProject(), Signature.getQualifier(decl.getElementName()));
          if (cont instanceof IType) {
            appendTypePath((IType) cont, pathBuffer);
          } else if (cont instanceof IPackageFragment) {
            appendPackageSummaryPath((IPackageFragment) cont, pathBuffer);
          }
        } else {
          IType imp = element.getJavaProject().findType(decl.getElementName());
          appendTypePath(imp, pathBuffer);
        }
        break;
      case IJavaElement.PACKAGE_DECLARATION:
        IJavaElement pack = element.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
        if (pack != null) {
          appendPackageSummaryPath((IPackageFragment) pack, pathBuffer);
        } else {
          return null;
        }
        break;
      default:
        return null;
    }

    try {
      String fragment = fragmentBuffer.length() == 0 ? null : fragmentBuffer.toString();
      try {
        URI relativeURI = new URI(null, null, pathBuffer.toString(), fragment);
        urlBuffer.append(relativeURI.toString());
        return new URL(urlBuffer.toString());
      } catch (URISyntaxException e) {
        JavaPlugin.log(e);
        return new URL(urlBuffer.append(pathBuffer).toString());
      }
    } catch (MalformedURLException e) {
      JavaPlugin.log(e);
    }
    return null;
  }
 private static void setLatestCompliance(Map<String, String> map) {
   JavaModelUtil.set50ComplianceOptions(map);
 }
  public JavadocHelpContext(IContext context, Object[] elements) throws JavaModelException {
    Assert.isNotNull(elements);
    if (context instanceof IContext2) fTitle = ((IContext2) context).getTitle();

    List helpResources = new ArrayList();

    String javadocSummary = null;
    for (int i = 0; i < elements.length; i++) {
      if (elements[i] instanceof IJavaElement) {
        IJavaElement element = (IJavaElement) elements[i];
        // if element isn't on the build path skip it
        if (!ActionUtil.isOnBuildPath(element)) continue;

        // Create Javadoc summary
        if (BUG_85721_FIXED) {
          if (javadocSummary == null) {
            javadocSummary = retrieveText(element);
            if (javadocSummary != null) {
              String elementLabel =
                  JavaElementLabels.getTextLabel(element, JavaElementLabels.ALL_DEFAULT);

              // FIXME: needs to be NLSed once the code becomes active
              javadocSummary =
                  "<b>Javadoc for "
                      + elementLabel
                      + ":</b><br>"
                      + javadocSummary; //$NON-NLS-1$//$NON-NLS-2$
            }
          } else {
            javadocSummary = ""; // no Javadoc summary for multiple selection //$NON-NLS-1$
          }
        }

        URL url = JavaUI.getJavadocLocation(element, true);
        if (url == null || doesNotExist(url)) {
          IPackageFragmentRoot root = JavaModelUtil.getPackageFragmentRoot(element);
          if (root != null) {
            url = JavaUI.getJavadocBaseLocation(element);
            if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
              element = element.getJavaProject();
            } else {
              element = root;
            }
            url = JavaUI.getJavadocLocation(element, false);
          }
        }
        if (url != null) {
          IHelpResource javaResource = new JavaUIHelpResource(element, getURLString(url));
          helpResources.add(javaResource);
        }
      }
    }

    // Add static help topics
    if (context != null) {
      IHelpResource[] resources = context.getRelatedTopics();
      if (resources != null) {
        for (int j = 0; j < resources.length; j++) {
          helpResources.add(resources[j]);
        }
      }
    }

    fHelpResources =
        (IHelpResource[]) helpResources.toArray(new IHelpResource[helpResources.size()]);

    if (context != null) fText = context.getText();

    if (BUG_85721_FIXED) {
      if (javadocSummary != null && javadocSummary.length() > 0) {
        if (fText != null) fText = context.getText() + "<br><br>" + javadocSummary; // $NON-NLS-1$
        else fText = javadocSummary;
      }
    }

    if (fText == null) fText = ""; // $NON-NLS-1$
  }
 public static IMethod getSetter(IField field) throws JavaModelException {
   String[] args = new String[] {field.getTypeSignature()};
   return JavaModelUtil.findMethod(
       getSetterName(field, EMPTY), args, false, field.getDeclaringType());
 }
 boolean isValidDestination(ASTNode node) {
   boolean isInterface = node instanceof TypeDeclaration && ((TypeDeclaration) node).isInterface();
   return !(node instanceof AnnotationTypeDeclaration)
       && !(isInterface && !JavaModelUtil.is18OrHigher(fCUnit.getJavaProject()));
 }
  private void fillInstalledJREs(ComboDialogField comboField) {
    String selectedItem = getLastSelectedJRE();

    int selectionIndex = -1;

    if (_useProjectRE.isSelected()) {
      selectionIndex = comboField.getSelectionIndex();
      if (selectionIndex != -1) { // paranoia
        selectedItem = comboField.getItems()[selectionIndex];
      }
    }

    List<IVMInstall> standins = VMUtils.getInstalledBBVMs();
    _installedVMs = (standins.toArray(new IVMInstall[standins.size()]));

    Arrays.sort(
        _installedVMs,
        new Comparator<IVMInstall>() {
          public int compare(IVMInstall arg0, IVMInstall arg1) {
            String cc0, cc1;

            if (arg1 instanceof IVMInstall2 && arg0 instanceof IVMInstall2) {
              cc0 = JavaModelUtil.getCompilerCompliance((IVMInstall2) arg0, JavaCore.VERSION_1_4);
              cc1 = JavaModelUtil.getCompilerCompliance((IVMInstall2) arg1, JavaCore.VERSION_1_4);
              int result = cc1.compareTo(cc0);

              if (result != 0) return result;
            }
            return Policy.getComparator().compare(arg0.getName(), arg1.getName());
          }
        });

    selectionIndex = -1; // find new index

    String[] jreLabels = new String[_installedVMs.length];

    _RECompliance = new String[_installedVMs.length];

    for (int i = 0; i < _installedVMs.length; i++) {
      jreLabels[i] = _installedVMs[i].getName();
      if (selectedItem != null && jreLabels[i].equals(selectedItem)) {
        selectionIndex = i;
      }
      if (_installedVMs[i] instanceof IVMInstall2) {
        _RECompliance[i] =
            JavaModelUtil.getCompilerCompliance(
                (IVMInstall2) _installedVMs[i], JavaCore.VERSION_1_4);
      } else {
        _RECompliance[i] = JavaCore.VERSION_1_4;
      }
    }

    // don't fire event when setting combobox items.
    _fireEvent = false;
    comboField.setItems(jreLabels);
    if (selectionIndex == -1) {
      comboField.selectItem(getDefaultBBJRE());
    } else {
      comboField.selectItem(selectedItem);
    }
    _fireEvent = true;
  }