Ejemplo n.º 1
0
 public ITypeModel getBodyType() {
   IMethod iMethod = (IMethod) tm;
   try {
     String[] parameterTypes = iMethod.getParameterTypes();
     for (String s : parameterTypes) {
       if (s.contains("java")) // $NON-NLS-1$
       {
         continue;
       }
       String returnType = s;
       if (returnType.startsWith("Q") && returnType.endsWith(";")) { // $NON-NLS-1$ //$NON-NLS-2$
         IType ownerType = (IType) iMethod.getAncestor(IJavaElement.TYPE);
         String[][] resolveType =
             ownerType.resolveType(returnType.substring(1, returnType.length() - 1));
         if (resolveType.length == 1) {
           IType findType =
               ownerType.getJavaProject().findType(resolveType[0][0] + '.' + resolveType[0][1]);
           if (findType != null && findType instanceof SourceType) {
             return new JDTType(findType);
           }
         }
       }
     }
   } catch (Exception e) {
     throw new IllegalStateException(e);
   }
   return null;
 }
Ejemplo n.º 2
0
    /** Create & return a new configuration based on the specified <code>IType</code>. */
    protected ILaunchConfiguration createConfiguration(IType type) {
      String launcherName = MainLauncher.this.getLauncherName();
      ILaunchConfigurationType configType = MainLauncher.this.getLaunchConfigurationType();

      ILaunchConfigurationWorkingCopy wc = null;
      try {
        wc = configType.newInstance(null, launcherName);
      } catch (CoreException exception) {
        JDIDebugUIPlugin.log(exception);
        return null;
      }
      wc.setAttribute(
          IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, type.getFullyQualifiedName());
      wc.setAttribute(
          IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME,
          type.getJavaProject().getElementName());

      MainLauncher.this.setAdditionalAttributes(wc);

      ILaunchConfiguration config = null;
      try {
        config = wc.doSave();
      } catch (CoreException exception) {
        JDIDebugUIPlugin.log(exception);
      }
      return config;
    }
 private StringBuffer composeTypeReference(IType type) {
   StringBuffer buffer = new StringBuffer();
   buffer.append(type.getJavaProject().getElementName());
   buffer.append(PROJECT_END_CHAR);
   buffer.append(type.getFullyQualifiedName());
   return buffer;
 }
 /* (non-Javadoc)
  * @see org.eclipse.jdt.debug.ui.launchConfigurations.JavaLaunchShortcut#createConfiguration(org.eclipse.jdt.core.IType)
  */
 @Override
 protected ILaunchConfiguration createConfiguration(IType type) {
   ILaunchConfiguration config = null;
   ILaunchConfigurationWorkingCopy wc = null;
   try {
     ILaunchConfigurationType configType = getConfigurationType();
     wc =
         configType.newInstance(
             null,
             getLaunchManager().generateLaunchConfigurationName(type.getTypeQualifiedName('.')));
     //			wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME,
     // type.getFullyQualifiedName());
     wc.setAttribute(
         IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME,
         type.getJavaProject().getElementName());
     wc.setMappedResources(new IResource[] {type.getUnderlyingResource()});
     config = wc.doSave();
   } catch (CoreException exception) {
     MessageDialog.openError(
         JDIDebugUIPlugin.getActiveWorkbenchShell(),
         LauncherMessages.JavaLaunchShortcut_3,
         exception.getStatus().getMessage());
   }
   return config;
 }
Ejemplo n.º 5
0
  public static boolean isTestCase(ICompilationUnit compilationUnit) {
    IType primaryType = compilationUnit.findPrimaryType();
    if (primaryType == null) {
      return false;
    }

    ProjectPreferences prefs = Preferences.forProject(primaryType.getJavaProject());
    return prefs.getTestClassNamePattern().evaluate(primaryType).isTestCase();
  }
Ejemplo n.º 6
0
 public IMethod findMethod(IType type, String name) throws JavaModelException {
   for (IMethod m : type.getMethods()) if (m.getElementName().equals(name)) return m;
   String superType = type.getSuperclassName();
   if (superType != null)
     for (String[] resolved : type.resolveType(superType)) {
       IType type2 = TypeUtil.findType(type.getJavaProject(), resolved[0] + "." + resolved[1]);
       if (type2 != null) return findMethod(type2, name);
     }
   return null;
 }
  public void testExtractInterfaceFromInterface2() throws Exception {
    String className = "A";
    String extendingInterfaceName = "I1";
    String newInterfaceName = "B";

    IType clas =
        getType(createCUfromTestFile(getPackageP(), getTopLevelTypeName(className)), className);
    ICompilationUnit cu = clas.getCompilationUnit();
    IPackageFragment pack = (IPackageFragment) cu.getParent();

    getType(
        createCUfromTestFile(getPackageP(), getTopLevelTypeName(extendingInterfaceName)),
        extendingInterfaceName);

    IPackageFragmentRoot root = RefactoringTestSetup.getDefaultSourceFolder();
    assertNotNull(root);
    IPackageFragment p2 = root.createPackageFragment("p2", true, null);
    getType(createCUfromTestFile(p2, getTopLevelTypeName("I2")), "I2");

    ExtractInterfaceProcessor processor =
        new ExtractInterfaceProcessor(
            clas, JavaPreferencesSettings.getCodeGenerationSettings(clas.getJavaProject()));
    Refactoring ref = new ProcessorBasedRefactoring(processor);

    processor.setTypeName(newInterfaceName);
    assertEquals(
        "interface name should be accepted",
        RefactoringStatus.OK,
        processor.checkTypeName(newInterfaceName).getSeverity());

    IMember[] extractableMembers = processor.getExtractableMembers();
    final IMember[] members = new IMember[extractableMembers.length - 1];
    List<IMember> list = new ArrayList<>();
    for (IMember iMember : extractableMembers) {
      if (!(iMember instanceof IField)) {
        list.add(iMember);
      }
    }
    processor.setExtractedMembers(list.toArray(members));
    processor.setReplace(true);
    processor.setAnnotations(false);
    RefactoringStatus performRefactoring = performRefactoring(ref);
    assertEquals("was supposed to pass", null, performRefactoring);
    assertEqualLines(
        "incorrect changes in " + className,
        getFileContents(getOutputTestFileName(className)),
        cu.getSource());

    ICompilationUnit interfaceCu = pack.getCompilationUnit(newInterfaceName + ".java");
    assertEqualLines(
        "incorrect interface created",
        getFileContents(getOutputTestFileName(newInterfaceName)),
        interfaceCu.getSource());
  }
  @Override
  public IHyperlink[] createHyperlinksByOffset(
      XtextResource resource, int offset, boolean createMultipleHyperlinks) {
    IHyperlink[] links = super.createHyperlinksByOffset(resource, offset, createMultipleHyperlinks);

    EObject eo = eObjectAtOffsetHelper.resolveElementAt(resource, offset);
    if (eo instanceof ControllerHandledValueProperty) {
      INode n = NodeModelUtils.getNode(eo);

      if (n != null) {
        INode currentNode = NodeModelUtils.findLeafNodeAtOffset(n, offset);
        List<INode> l =
            NodeModelUtils.findNodesForFeature(
                eo, FXGraphPackage.Literals.CONTROLLER_HANDLED_VALUE_PROPERTY__METHODNAME);
        if (l.contains(currentNode)) {
          Region region = new Region(currentNode.getOffset(), currentNode.getLength());

          Model m = (Model) eo.eResource().getContents().get(0);

          if (m != null) {
            ComponentDefinition def = m.getComponentDef();
            if (def != null) {
              if (def.getController() != null && def.getController().getType() != null) {
                IType t = getJDTType(def.getController().getType());
                if (t != null) {
                  IFXCtrlClass fxClass =
                      FXPlugin.getClassmodel().findCtrlClass(t.getJavaProject(), t);
                  if (fxClass != null) {
                    IFXCtrlEventMethod fxp =
                        fxClass.getAllEventMethods().get(currentNode.getText());
                    if (fxp != null) {
                      HyperlinkImpl h = new HyperlinkImpl(region, fxp.getJavaElement());
                      if (links == null || links.length == 0) {
                        return new IHyperlink[] {h};
                      } else {
                        IHyperlink[] rv = new IHyperlink[links.length + 1];
                        System.arraycopy(links, 0, rv, 0, rv.length);
                        rv[rv.length - 1] = h;
                        return rv;
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }

    return links;
  }
Ejemplo n.º 9
0
 public static IType getJavaTypeFromSignatureClassName(String className, IType contextType) {
   if (contextType == null || className == null) {
     return null;
   }
   try {
     return JdtUtils.getJavaType(
         contextType.getJavaProject().getProject(),
         JdtUtils.resolveClassNameBySignature(className, contextType));
   } catch (IllegalArgumentException e) {
     // do Nothing
   }
   return null;
 }
  @Test
  public void should_retrieve_template_from_preferences_for_test_case_project() throws Exception {
    // given
    when(classUnderTest.getJavaProject()).thenReturn(project);

    when(preferences.getMockingTemplate(project)).thenReturn("test-template-id");

    // when
    dependencyMocker.mockDependencies(dependencies, classUnderTest, testCase, SOME_TEST_TYPE);

    // then
    verify(templateStore).get("test-template-id");
  }
 /** Invoked when the search button for the agent agent was clocked. */
 protected void handleAgentNameSearchButtonSelected() {
   final IType[] types = searchAgentNames();
   // Ask to the user
   final DebugTypeSelectionDialog mmsd =
       new DebugTypeSelectionDialog(getShell(), types, ""); // $NON-NLS-1$
   if (mmsd.open() == Window.CANCEL) {
     return;
   }
   final IType type = (IType) mmsd.getFirstResult();
   if (type != null) {
     this.agentNameTextField.setText(type.getFullyQualifiedName());
     this.fProjText.setText(type.getJavaProject().getElementName());
   }
 }
Ejemplo n.º 12
0
 public static byte[] getClassContent(IJavaProject javaProject, String className) {
   if (javaProject == null || !javaProject.exists()) return null;
   String resourceName = className.replace('.', '/') + ".class";
   try {
     IPath outPath =
         javaProject
             .getProject()
             .getLocation()
             .removeLastSegments(1)
             .append(javaProject.getOutputLocation());
     outPath = outPath.addTrailingSeparator();
     {
       URL url = toURL(outPath.append(resourceName));
       if (url != null) {
         InputStream inputStream = url.openStream();
         byte[] content = new byte[inputStream.available()];
         inputStream.read(content);
         return content;
       }
       for (IProject project : javaProject.getProject().getReferencedProjects()) {
         if (!project.isOpen()) {
           continue;
         }
         IJavaProject javaReferencedProject = JavaCore.create(project);
         if (javaReferencedProject.exists()) {
           byte[] content = getClassContent(javaReferencedProject, className);
           if (content != null) {
             return content;
           }
         }
       }
     }
     IType type = javaProject.findType(className);
     if (type != null && type.exists()) {
       if (type.isBinary()) {
         return type.getClassFile().getBytes();
       } else {
         IJavaProject typeProject = type.getJavaProject();
         if (!javaProject.equals(typeProject)) {
           return getClassContent(typeProject, className);
         }
       }
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   return null;
 }
 protected ILaunchConfiguration createConfiguration(IType type) {
   ILaunchConfiguration config = null;
   ILaunchConfigurationWorkingCopy wc = null;
   try {
     ILaunchConfigurationType configType = getAJConfigurationType();
     wc =
         configType.newInstance(
             null, getLaunchManager().generateLaunchConfigurationName(type.getElementName()));
     wc.setAttribute(
         IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME,
         type.getJavaProject().getElementName());
     wc.setAttribute(
         IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, type.getFullyQualifiedName());
     config = wc.doSave();
   } catch (CoreException exception) {
     reportErorr(exception);
   }
   return config;
 }
  /** @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
    }
  }
  @Override
  public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException {
    String project = null;
    IJavaProject javaProject = targetClass.getJavaProject();
    if (javaProject != null) project = javaProject.getElementName();
    int flags =
        JavaRefactoringDescriptor.JAR_MIGRATION
            | JavaRefactoringDescriptor.JAR_REFACTORING
            | RefactoringDescriptor.STRUCTURAL_CHANGE
            | RefactoringDescriptor.MULTI_CHANGE;
    try {
      if (targetClass.isAnonymous() || targetClass.isLocal())
        flags |= JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
    } catch (JavaModelException exception) {
      JavaPlugin.log(exception);
    }

    // TODO need to properly initialize the arguments so that this refactoring becomes recordable
    final Map arguments = new HashMap();
    String description = "Convert Mutable into Immutable Class";
    String comment = "Convert Mutable into Immutable Class";

    final JavaRefactoringDescriptor descriptor =
        new JavaRefactoringDescriptor("fixme", project, description, comment, arguments, flags) {};

    // JDTRefactoringDescriptor(IJavaRefactorings.ENCAPSULATE_FIELD, project, description, comment,
    // arguments, flags);

    final DynamicValidationRefactoringChange result =
        new DynamicValidationRefactoringChange(descriptor, getName());
    TextChange[] changes = fChangeManager.getAllChanges();
    pm.beginTask("ConvertToParallelArray create changes", changes.length);
    for (int i = 0; i < changes.length; i++) {
      result.add(changes[i]);
      pm.worked(1);
    }
    pm.done();
    return result;
  }
  /** Configure this type hierarchy based on the given potential subtypes. */
  private void buildFromPotentialSubtypes(
      String[] allPotentialSubTypes, HashSet localTypes, IProgressMonitor monitor) {
    IType focusType = getType();

    // substitute compilation units with working copies
    HashMap wcPaths = new HashMap(); // a map from path to working copies
    int wcLength;
    org.eclipse.jdt.core.ICompilationUnit[] workingCopies = this.hierarchy.workingCopies;
    if (workingCopies != null && (wcLength = workingCopies.length) > 0) {
      String[] newPaths = new String[wcLength];
      for (int i = 0; i < wcLength; i++) {
        org.eclipse.jdt.core.ICompilationUnit workingCopy = workingCopies[i];
        String path = workingCopy.getPath().toString();
        wcPaths.put(path, workingCopy);
        newPaths[i] = path;
      }
      int potentialSubtypesLength = allPotentialSubTypes.length;
      System.arraycopy(
          allPotentialSubTypes,
          0,
          allPotentialSubTypes = new String[potentialSubtypesLength + wcLength],
          0,
          potentialSubtypesLength);
      System.arraycopy(newPaths, 0, allPotentialSubTypes, potentialSubtypesLength, wcLength);
    }

    int length = allPotentialSubTypes.length;

    // inject the compilation unit of the focus type (so that types in
    // this cu have special visibility permission (this is also usefull
    // when the cu is a working copy)
    Openable focusCU = (Openable) focusType.getCompilationUnit();
    String focusPath = null;
    if (focusCU != null) {
      focusPath = focusCU.getPath().toString();
      if (length > 0) {
        System.arraycopy(
            allPotentialSubTypes, 0, allPotentialSubTypes = new String[length + 1], 0, length);
        allPotentialSubTypes[length] = focusPath;
      } else {
        allPotentialSubTypes = new String[] {focusPath};
      }
      length++;
    }

    /*
     * Sort in alphabetical order so that potential subtypes are grouped per project
     */
    Arrays.sort(allPotentialSubTypes);

    ArrayList potentialSubtypes = new ArrayList();
    try {
      // create element infos for subtypes
      HandleFactory factory = new HandleFactory();
      IJavaProject currentProject = null;
      if (monitor != null)
        monitor.beginTask(
            "", length * 2 /* 1 for build binding, 1 for connect hierarchy*/); // $NON-NLS-1$
      for (int i = 0; i < length; i++) {
        try {
          String resourcePath = allPotentialSubTypes[i];

          // skip duplicate paths (e.g. if focus path was injected when it was already a potential
          // subtype)
          if (i > 0 && resourcePath.equals(allPotentialSubTypes[i - 1])) continue;

          Openable handle;
          org.eclipse.jdt.core.ICompilationUnit workingCopy =
              (org.eclipse.jdt.core.ICompilationUnit) wcPaths.get(resourcePath);
          if (workingCopy != null) {
            handle = (Openable) workingCopy;
          } else {
            handle =
                resourcePath.equals(focusPath)
                    ? focusCU
                    : factory.createOpenable(resourcePath, this.scope);
            if (handle == null) continue; // match is outside classpath
          }

          IJavaProject project = handle.getJavaProject();
          if (currentProject == null) {
            currentProject = project;
            potentialSubtypes = new ArrayList(5);
          } else if (!currentProject.equals(project)) {
            // build current project
            buildForProject(
                (JavaProject) currentProject,
                potentialSubtypes,
                workingCopies,
                localTypes,
                monitor);
            currentProject = project;
            potentialSubtypes = new ArrayList(5);
          }

          potentialSubtypes.add(handle);
        } catch (JavaModelException e) {
          continue;
        }
      }

      // build last project
      try {
        if (currentProject == null) {
          // case of no potential subtypes
          currentProject = focusType.getJavaProject();
          if (focusType.isBinary()) {
            potentialSubtypes.add(focusType.getClassFile());
          } else {
            potentialSubtypes.add(focusType.getCompilationUnit());
          }
        }
        buildForProject(
            (JavaProject) currentProject, potentialSubtypes, workingCopies, localTypes, monitor);
      } catch (JavaModelException e) {
        // ignore
      }

      // Compute hierarchy of focus type if not already done (case of a type with potential subtypes
      // that are not real subtypes)
      if (!this.hierarchy.contains(focusType)) {
        try {
          currentProject = focusType.getJavaProject();
          potentialSubtypes = new ArrayList();
          if (focusType.isBinary()) {
            potentialSubtypes.add(focusType.getClassFile());
          } else {
            potentialSubtypes.add(focusType.getCompilationUnit());
          }
          buildForProject(
              (JavaProject) currentProject, potentialSubtypes, workingCopies, localTypes, monitor);
        } catch (JavaModelException e) {
          // ignore
        }
      }

      // Add focus if not already in (case of a type with no explicit super type)
      if (!this.hierarchy.contains(focusType)) {
        this.hierarchy.addRootClass(focusType);
      }
    } finally {
      if (monitor != null) monitor.done();
    }
  }
  private void buildForProject(
      JavaProject project,
      ArrayList potentialSubtypes,
      org.eclipse.jdt.core.ICompilationUnit[] workingCopies,
      HashSet localTypes,
      IProgressMonitor monitor)
      throws JavaModelException {
    // resolve
    int openablesLength = potentialSubtypes.size();
    if (openablesLength > 0) {
      // copy vectors into arrays
      Openable[] openables = new Openable[openablesLength];
      potentialSubtypes.toArray(openables);

      // sort in the order of roots and in reverse alphabetical order for .class file
      // since requesting top level types in the process of caching an enclosing type is
      // not supported by the lookup environment
      IPackageFragmentRoot[] roots = project.getPackageFragmentRoots();
      int rootsLength = roots.length;
      final HashtableOfObjectToInt indexes = new HashtableOfObjectToInt(openablesLength);
      for (int i = 0; i < openablesLength; i++) {
        IJavaElement root = openables[i].getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
        int index;
        for (index = 0; index < rootsLength; index++) {
          if (roots[index].equals(root)) break;
        }
        indexes.put(openables[i], index);
      }
      Arrays.sort(
          openables,
          new Comparator() {
            public int compare(Object a, Object b) {
              int aIndex = indexes.get(a);
              int bIndex = indexes.get(b);
              if (aIndex != bIndex) return aIndex - bIndex;
              return ((Openable) b).getElementName().compareTo(((Openable) a).getElementName());
            }
          });

      IType focusType = getType();
      boolean inProjectOfFocusType =
          focusType != null && focusType.getJavaProject().equals(project);
      org.eclipse.jdt.core.ICompilationUnit[] unitsToLookInside = null;
      if (inProjectOfFocusType) {
        org.eclipse.jdt.core.ICompilationUnit unitToLookInside = focusType.getCompilationUnit();
        if (unitToLookInside != null) {
          int wcLength = workingCopies == null ? 0 : workingCopies.length;
          if (wcLength == 0) {
            unitsToLookInside = new org.eclipse.jdt.core.ICompilationUnit[] {unitToLookInside};
          } else {
            unitsToLookInside = new org.eclipse.jdt.core.ICompilationUnit[wcLength + 1];
            unitsToLookInside[0] = unitToLookInside;
            System.arraycopy(workingCopies, 0, unitsToLookInside, 1, wcLength);
          }
        } else {
          unitsToLookInside = workingCopies;
        }
      }

      SearchableEnvironment searchableEnvironment =
          project.newSearchableNameEnvironment(unitsToLookInside);
      this.nameLookup = searchableEnvironment.nameLookup;
      Map options = project.getOptions(true);
      // disable task tags to speed up parsing
      options.put(JavaCore.COMPILER_TASK_TAGS, ""); // $NON-NLS-1$
      this.hierarchyResolver =
          new HierarchyResolver(searchableEnvironment, options, this, new DefaultProblemFactory());
      if (focusType != null) {
        Member declaringMember = ((Member) focusType).getOuterMostLocalContext();
        if (declaringMember == null) {
          // top level or member type
          if (!inProjectOfFocusType) {
            char[] typeQualifiedName = focusType.getTypeQualifiedName('.').toCharArray();
            String[] packageName = ((PackageFragment) focusType.getPackageFragment()).names;
            if (searchableEnvironment.findType(typeQualifiedName, Util.toCharArrays(packageName))
                == null) {
              // focus type is not visible in this project: no need to go further
              return;
            }
          }
        } else {
          // local or anonymous type
          Openable openable;
          if (declaringMember.isBinary()) {
            openable = (Openable) declaringMember.getClassFile();
          } else {
            openable = (Openable) declaringMember.getCompilationUnit();
          }
          localTypes = new HashSet();
          localTypes.add(openable.getPath().toString());
          this.hierarchyResolver.resolve(new Openable[] {openable}, localTypes, monitor);
          return;
        }
      }
      this.hierarchyResolver.resolve(openables, localTypes, monitor);
    }
  }
  protected void reportDeclaration(
      MethodBinding methodBinding, MatchLocator locator, SimpleSet knownMethods)
      throws CoreException {
    ReferenceBinding declaringClass = methodBinding.declaringClass;
    IType type = locator.lookupType(declaringClass);
    if (type == null) return; // case of a secondary type

    // Report match for binary
    if (type.isBinary()) {
      IMethod method = null;
      TypeBinding[] parameters = methodBinding.original().parameters;
      int parameterLength = parameters.length;
      char[][] parameterTypes = new char[parameterLength][];
      for (int i = 0; i < parameterLength; i++) {
        char[] typeName = parameters[i].qualifiedSourceName();
        for (int j = 0, dim = parameters[i].dimensions(); j < dim; j++) {
          typeName = CharOperation.concat(typeName, new char[] {'[', ']'});
        }
        parameterTypes[i] = typeName;
      }
      method = locator.createBinaryMethodHandle(type, methodBinding.selector, parameterTypes);
      if (method == null || knownMethods.addIfNotIncluded(method) == null) return;

      IResource resource = type.getResource();
      if (resource == null) resource = type.getJavaProject().getProject();
      IBinaryType info =
          locator.getBinaryInfo(
              (org.eclipse.jdt.internal.core.ClassFile) type.getClassFile(), resource);
      locator.reportBinaryMemberDeclaration(
          resource, method, methodBinding, info, SearchMatch.A_ACCURATE);
      return;
    }

    // When source is available, report match if method is found in the declaring type
    IResource resource = type.getResource();
    if (declaringClass instanceof ParameterizedTypeBinding)
      declaringClass = ((ParameterizedTypeBinding) declaringClass).genericType();
    ClassScope scope = ((SourceTypeBinding) declaringClass).scope;
    if (scope != null) {
      TypeDeclaration typeDecl = scope.referenceContext;
      AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(methodBinding.original());
      if (methodDecl != null) {
        // Create method handle from method declaration
        String methodName = new String(methodBinding.selector);
        Argument[] arguments = methodDecl.arguments;
        int length = arguments == null ? 0 : arguments.length;
        String[] parameterTypes = new String[length];
        for (int i = 0; i < length; i++) {
          char[][] typeName = arguments[i].type.getParameterizedTypeName();
          parameterTypes[i] =
              Signature.createTypeSignature(CharOperation.concatWith(typeName, '.'), false);
        }
        IMethod method = type.getMethod(methodName, parameterTypes);
        if (method == null || knownMethods.addIfNotIncluded(method) == null) return;

        // Create and report corresponding match
        int offset = methodDecl.sourceStart;
        this.match =
            new MethodDeclarationMatch(
                method,
                SearchMatch.A_ACCURATE,
                offset,
                methodDecl.sourceEnd - offset + 1,
                locator.getParticipant(),
                resource);
        locator.report(this.match);
      }
    }
  }
Ejemplo n.º 19
0
 /** @since 2.4 */
 protected boolean isDerived(IType type) {
   return isDerived(type.getFullyQualifiedName(), type.getJavaProject());
 }
Ejemplo n.º 20
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;
      }
    }
Ejemplo n.º 21
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;
  }
  /**
   * Creates a qualified class name from a class name which doesn't contain package name.
   *
   * @param parent a full qualified class name of the class which uses this variable
   * @param type a class name which doesn't contain package name
   * @return full a created qualified class name
   */
  public static String getFullQName(IType parent, String type) {
    if (type.indexOf('.') >= 0) {
      return type;
    }
    if (isPrimitive(type)) {
      return type;
    }
    IJavaProject project = parent.getJavaProject();
    try {
      IType javaType = project.findType("java.lang." + type);
      if (javaType != null && javaType.exists()) {
        return javaType.getFullyQualifiedName();
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    while (true) {
      try {
        IType javaType = project.findType(parent.getFullyQualifiedName() + "." + type);
        if (javaType != null && javaType.exists()) {
          return parent.getFullyQualifiedName() + "." + type;
        }
      } catch (Exception ex) {
        ex.printStackTrace();
      }
      try {
        IType javaType =
            project.findType(parent.getPackageFragment().getElementName() + "." + type);
        if (javaType != null && javaType.exists()) {
          return javaType.getFullyQualifiedName();
        }
      } catch (Exception ex) {
        ex.printStackTrace();
      }
      try {
        IImportDeclaration[] imports = parent.getCompilationUnit().getImports();
        for (int i = 0; i < imports.length; i++) {
          String importName = imports[i].getElementName();
          if (importName.endsWith("." + type)) {
            return importName;
          }
          if (importName.endsWith(".*")) {
            try {
              IType javaType = project.findType(importName.replaceFirst("\\*$", type));
              if (javaType != null && javaType.exists()) {
                return javaType.getFullyQualifiedName();
              }
            } catch (Exception ex) {
            }
          }
        }
      } catch (Exception ex) {
        ex.printStackTrace();
      }

      try {
        // スーパークラス
        if (parent.getSuperclassTypeSignature() == null) {
          break;
        }
        String superClass =
            JavaUtil.getFullQName(parent, Signature.toString(parent.getSuperclassTypeSignature()));

        if (superClass.startsWith("java.lang.")) {
          break;
        }

        parent = parent.getJavaProject().findType(superClass);
      } catch (JavaModelException ex) {
      }
    }
    return type;
  }