public static String getMatchedPackage(String className, ICompilationUnit cUnit)
      throws JavaModelException {
    int higherAccuracy = 0;
    String matchedPackage = cUnit.getPackageDeclarations()[0].getElementName();
    IImportDeclaration[] imports = cUnit.getImports();
    for (IImportDeclaration impDec : imports) {
      String fullName = impDec.getElementName();
      int dotIndex = fullName.lastIndexOf('.');

      String lastNameOfImport = fullName.substring(dotIndex + 1);
      if (lastNameOfImport.equals(className) && higherAccuracy < 2) {
        matchedPackage = fullName.substring(0, dotIndex);
        higherAccuracy = 2;
      } else if (lastNameOfImport.equals("*") && higherAccuracy < 1) {
        matchedPackage = fullName.substring(0, dotIndex);
        higherAccuracy = 1;
      }
    }

    if (higherAccuracy > 0) return matchedPackage;

    if (cUnit.getType(className) != null) return cUnit.getPackageDeclarations()[0].getElementName();

    return "java.lang";
  }
  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;
  }
Exemple #3
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;
      }
    }
Exemple #4
0
  public static String resolveClassName(String className, IType type) {
    if (className == null || type == null) {
      return className;
    }
    // replace binary $ inner class name syntax with . for source level
    className = className.replace('$', '.');
    String dotClassName = new StringBuilder().append('.').append(className).toString();

    IProject project = type.getJavaProject().getProject();

    try {
      // Special handling for some well-know classes
      if (className.startsWith("java.lang") && getJavaType(project, className) != null) {
        return className;
      }

      // Check if the class is imported
      if (!type.isBinary()) {

        // Strip className to first segment to support ReflectionUtils.MethodCallback
        int ix = className.lastIndexOf('.');
        String firstClassNameSegment = className;
        if (ix > 0) {
          firstClassNameSegment = className.substring(0, ix);
        }

        // Iterate the imports
        for (IImportDeclaration importDeclaration : type.getCompilationUnit().getImports()) {
          String importName = importDeclaration.getElementName();
          // Wildcard imports -> check if the package + className is a valid type
          if (importDeclaration.isOnDemand()) {
            String newClassName =
                new StringBuilder(importName.substring(0, importName.length() - 1))
                    .append(className)
                    .toString();
            if (getJavaType(project, newClassName) != null) {
              return newClassName;
            }
          }
          // Concrete import matching .className at the end -> check if type exists
          else if (importName.endsWith(dotClassName) && getJavaType(project, importName) != null) {
            return importName;
          }
          // Check if className is multi segmented (ReflectionUtils.MethodCallback)
          // -> check if the first segment
          else if (!className.equals(firstClassNameSegment)) {
            if (importName.endsWith(firstClassNameSegment)) {
              String newClassName =
                  new StringBuilder(importName.substring(0, importName.lastIndexOf('.') + 1))
                      .append(className)
                      .toString();
              if (getJavaType(project, newClassName) != null) {
                return newClassName;
              }
            }
          }
        }
      }

      // Check if the class is in the same package as the type
      String packageName = type.getPackageFragment().getElementName();
      String newClassName = new StringBuilder(packageName).append(dotClassName).toString();
      if (getJavaType(project, newClassName) != null) {
        return newClassName;
      }

      // Check if the className is sufficient (already fully-qualified)
      if (getJavaType(project, className) != null) {
        return className;
      }

      // Check if the class is coming from the java.lang
      newClassName = new StringBuilder("java.lang").append(dotClassName).toString();
      if (getJavaType(project, newClassName) != null) {
        return newClassName;
      }

      // Fall back to full blown resolution
      String[][] fullInter = type.resolveType(className);
      if (fullInter != null && fullInter.length > 0) {
        return fullInter[0][0] + "." + fullInter[0][1];
      }
    } catch (JavaModelException e) {
      SpringCore.log(e);
    }

    return className;
  }