Example #1
0
  /** @since 3.2.0 */
  public static IMethod getMethod(
      IType type, String methodName, String[] parameterTypes, boolean includeHierarchy) {
    int index = methodName.indexOf('(');
    if (index >= 0) {
      methodName = methodName.substring(0, index);
    }
    try {
      while (type != null) {
        for (IMethod method : Introspector.getMethods(type)) {
          if (method.getElementName().equals(methodName)
              && method.getParameterTypes().length == parameterTypes.length) {
            String[] methodParameterTypes = getParameterTypesAsStringArray(method);
            if (Arrays.deepEquals(parameterTypes, methodParameterTypes)) {
              return method;
            }
          }
        }
        if (!includeHierarchy) break;
        type = Introspector.getSuperType(type);
      }

      return Introspector.findMethod(
          type, methodName, parameterTypes.length, Public.YES, Static.DONT_CARE);
    } catch (JavaModelException e) {
    }
    return null;
  }
  public void testViewRecursion() throws JavaModelException, PartInitException {
    view = (ActiveSearchView) JavaPlugin.getActivePage().showView(ActiveSearchView.ID);
    ActiveSearchView.getFromActivePerspective().setSyncExecForTesting(false);

    for (AbstractRelationProvider provider :
        ContextCorePlugin.getDefault().getRelationProviders()) {
      assertTrue(provider.isEnabled());
    }
    assertEquals(0, view.getViewer().getTree().getItemCount());

    IWorkbenchPart part =
        PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart();
    IMethod m1 = type1.createMethod("void m1() {\n m1(); \n}", null, true, null);
    StructuredSelection sm1 = new StructuredSelection(m1);
    monitor.selectionChanged(part, sm1);
    IInteractionElement node =
        manager.processInteractionEvent(
            mockInterestContribution(m1.getHandleIdentifier(), scaling.getLandmark()));

    assertEquals(1, ContextCore.getContextManager().getActiveLandmarks().size());

    assertEquals(1, search(2, node).size());

    List<TreeItem> collectedItems = new ArrayList<TreeItem>();
    UiTestUtil.collectTreeItemsInView(view.getViewer().getTree().getItems(), collectedItems);

    // just make sure that the view didn't blow up.
    assertEquals(1, collectedItems.size());
    monitor.selectionChanged(part, sm1);
    manager.processInteractionEvent(
        mockInterestContribution(m1.getHandleIdentifier(), -scaling.getLandmark()));
  }
 @Test
 public void shouldCreateResourceMethodWithBeanParamAnnotatedParameter()
     throws JavaModelException, CoreException {
   // pre-conditions
   final IType carType =
       metamodelMonitor.resolveType("org.jboss.tools.ws.jaxrs.sample.services.CarResource");
   replaceAllOccurrencesOfCode(
       carType,
       "update(final CarParameterAggregator car)",
       "update(@BeanParam final CarParameterAggregator car)",
       false);
   assertThat(carType, notNullValue());
   final IMethod carMethod = JavaElementsUtils.getMethod(carType, "update");
   assertThat(carMethod, notNullValue());
   // operation
   final List<IJaxrsElement> elements =
       JaxrsElementFactory.createElements(
           carType,
           JdtUtils.parse(carType, new NullProgressMonitor()),
           metamodel,
           new NullProgressMonitor());
   // verifications
   assertThat(elements.size(), equalTo(3));
   final JaxrsResource carResource = metamodel.findResource(carType);
   final JaxrsResourceMethod resourceMethod =
       carResource.getMethods().get(carMethod.getHandleIdentifier());
   assertThat(resourceMethod.getJavaMethodParameters().size(), equalTo(1));
   assertThat(
       resourceMethod
           .getJavaMethodParameters()
           .iterator()
           .next()
           .getAnnotation(JaxrsClassnames.BEAN_PARAM),
       notNullValue());
 }
Example #4
0
  /**
   * Gets the fully qualified name of the supplied java element.
   *
   * <p>NOTE: For easy of determining fields and method segments, they are appended with a javadoc
   * style '#' instead of the normal '.'.
   *
   * @param element The IJavaElement.
   * @return The fully qualified name.
   */
  public static String getFullyQualifiedName(IJavaElement element) {
    IJavaElement parent = element;
    while (parent.getElementType() != IJavaElement.COMPILATION_UNIT
        && parent.getElementType() != IJavaElement.CLASS_FILE) {
      parent = parent.getParent();
    }

    StringBuffer elementName =
        new StringBuffer()
            .append(parent.getParent().getElementName())
            .append('.')
            .append(FileUtils.getFileName(parent.getElementName()));

    switch (element.getElementType()) {
      case IJavaElement.FIELD:
        IField field = (IField) element;
        elementName.append('#').append(field.getElementName());
        break;
      case IJavaElement.METHOD:
        IMethod method = (IMethod) element;
        elementName.append('#').append(method.getElementName()).append('(');
        String[] parameters = method.getParameterTypes();
        for (int ii = 0; ii < parameters.length; ii++) {
          if (ii != 0) {
            elementName.append(", ");
          }
          elementName.append(Signature.toString(parameters[ii]).replace('/', '.'));
        }
        elementName.append(')');
        break;
    }

    return elementName.toString();
  }
Example #5
0
 public static IMethod[] removeGeneratedMethods(IMethod[] methods) throws Exception {
   List<IMethod> result = new ArrayList<IMethod>();
   for (IMethod m : methods) {
     if (m.getNameRange().getLength() > 0) result.add(m);
   }
   return result.size() == methods.length ? methods : result.toArray(new IMethod[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;
 }
Example #7
0
 /**
  * Tries to find the given {@link IApiMethod} in the given {@link IType}. If a matching method is
  * not found <code>null</code> is returned
  *
  * @param type the type top look in for the given {@link IApiMethod}
  * @param method the {@link IApiMethod} to look for
  * @return the {@link IMethod} from the given {@link IType} that matches the given {@link
  *     IApiMethod} or <code>null</code> if no matching method is found
  * @throws JavaModelException
  * @throws CoreException
  */
 protected IMethod findMethodInType(IType type, IApiMethod method)
     throws JavaModelException, CoreException {
   String[] parameterTypes = Signature.getParameterTypes(method.getSignature());
   for (int i = 0; i < parameterTypes.length; i++) {
     parameterTypes[i] = parameterTypes[i].replace('/', '.');
   }
   String methodname = method.getName();
   if (method.isConstructor()) {
     IApiType enclosingType = method.getEnclosingType();
     if (enclosingType.isMemberType() && !Flags.isStatic(enclosingType.getModifiers())) {
       // remove the synthetic argument that corresponds to the enclosing type
       int length = parameterTypes.length - 1;
       System.arraycopy(parameterTypes, 1, (parameterTypes = new String[length]), 0, length);
     }
     methodname = enclosingType.getSimpleName();
   }
   IMethod Qmethod = type.getMethod(methodname, parameterTypes);
   IMethod[] methods = type.getMethods();
   IMethod match = null;
   for (int i = 0; i < methods.length; i++) {
     IMethod m = methods[i];
     if (m.isSimilar(Qmethod)) {
       match = m;
       break;
     }
   }
   return match;
 }
Example #8
0
  private void addAccessorOccurrences(
      IProgressMonitor pm,
      IMethod accessor,
      String editName,
      String newAccessorName,
      RefactoringStatus status)
      throws CoreException {
    Assert.isTrue(accessor.exists());

    IJavaSearchScope scope = RefactoringScopeFactory.create(accessor);
    SearchPattern pattern =
        SearchPattern.createPattern(
            accessor,
            IJavaSearchConstants.ALL_OCCURRENCES,
            SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
    SearchResultGroup[] groupedResults =
        RefactoringSearchEngine.search(
            pattern, scope, new MethodOccurenceCollector(accessor.getElementName()), pm, status);

    for (int i = 0; i < groupedResults.length; i++) {
      ICompilationUnit cu = groupedResults[i].getCompilationUnit();
      if (cu == null) continue;
      SearchMatch[] results = groupedResults[i].getSearchResults();
      for (int j = 0; j < results.length; j++) {
        SearchMatch searchResult = results[j];
        TextEdit edit =
            new ReplaceEdit(searchResult.getOffset(), searchResult.getLength(), newAccessorName);
        addTextEdit(fChangeManager.get(cu), editName, edit);
      }
    }
  }
 static final IMethod[] hierarchyDeclaresMethodName(
     IProgressMonitor pm, ITypeHierarchy hierarchy, IMethod method, String newName)
     throws CoreException {
   try {
     Set<IMethod> result = new HashSet<>();
     IType type = method.getDeclaringType();
     IMethod foundMethod =
         Checks.findMethod(newName, method.getParameterTypes().length, false, type);
     if (foundMethod != null) result.add(foundMethod);
     IMethod[] foundInHierarchyClasses =
         classesDeclareMethodName(
             hierarchy, Arrays.asList(hierarchy.getAllClasses()), method, newName);
     if (foundInHierarchyClasses != null) result.addAll(Arrays.asList(foundInHierarchyClasses));
     IType[] implementingClasses = hierarchy.getImplementingClasses(type);
     IMethod[] foundInImplementingClasses =
         classesDeclareMethodName(hierarchy, Arrays.asList(implementingClasses), method, newName);
     if (foundInImplementingClasses != null)
       result.addAll(Arrays.asList(foundInImplementingClasses));
     return result.toArray(new IMethod[result.size()]);
   } finally {
     if (pm != null) {
       pm.done();
     }
   }
 }
  @Override
  public void generate(Shell parentShell, IType objectClass, CommandIdentifier commandIdentifier) {
    LinkedHashSet<MethodSkeleton<U>> methodSkeletons =
        methodSkeletonManager.getMethodSkeletons(commandIdentifier);
    LinkedHashSet<StrategyIdentifier> strategyIdentifiers =
        methodContentManager.getStrategiesIntersection(methodSkeletons);

    try {
      Set<IMethod> excludedMethods = getExcludedMethods(objectClass, methodSkeletons);
      FieldDialog<U> dialog =
          dialogFactory.createDialog(
              parentShell, objectClass, excludedMethods, strategyIdentifiers);
      int returnCode = dialog.getDialog().open();
      if (returnCode == Window.OK) {

        for (IMethod excludedMethod : excludedMethods) {
          excludedMethod.delete(true, null);
        }

        U data = dialog.getData();
        StrategyIdentifier selectedContentStrategy = data.getSelectedStrategyIdentifier();
        LinkedHashSet<Method<T, U>> methods =
            methodContentManager.getAllMethods(methodSkeletons, selectedContentStrategy);
        generateCode(parentShell, objectClass, data, methods);
      }

    } catch (Exception exception) {
      MessageDialog.openError(parentShell, "Method Generation Failed", exception.getMessage());
    }
  }
  public void testSearchAfterDeletion()
      throws JavaModelException, PartInitException, IOException, CoreException {
    view = (ActiveSearchView) JavaPlugin.getActivePage().showView(ActiveSearchView.ID);
    if (view != null) {
      assertEquals(0, view.getViewer().getTree().getItemCount());

      IWorkbenchPart part =
          PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart();
      IMethod m1 = type1.createMethod("void m1() {\n m2() \n}", null, true, null);
      IMethod m2 = type1.createMethod("void m2() { }", null, true, null);
      StructuredSelection sm2 = new StructuredSelection(m2);
      monitor.selectionChanged(part, sm2);
      IInteractionElement node =
          manager.processInteractionEvent(
              mockInterestContribution(m2.getHandleIdentifier(), scaling.getLandmark()));
      assertEquals(1, ContextCore.getContextManager().getActiveLandmarks().size());

      assertEquals(1, search(2, node).size());

      m1.delete(true, null);
      assertFalse(m1.exists());

      assertEquals(0, search(2, node).size());
    }
  }
 private void printMethods(IType type, StringBuilder sb) throws JavaModelException {
   IMethod[] methods = type.getMethods();
   if (methods.length > 0) {
     sb.append("<METHODS>");
     for (IMethod method : methods) {
       sb.append("<METHOD NAME=\"" + method.getElementName() + "\">");
       ILocalVariable[] vars = method.getParameters();
       sb.append("<PARAMETERS>");
       if (vars.length > 0) {
         for (int i = 0; i < vars.length; i += 1) {
           System.out.println(vars[i].toString());
           System.out.println(vars[i].getSource());
           sb.append("<PARAMETER>" + vars[i].getSource() + "</PARAMETER>");
         }
       } else {
         sb.append("<PARAMETER>void</PARAMETER>");
       }
       sb.append("</PARAMETERS>");
       // method.gets
       sb.append("<SIGNATURE>" + method.getSignature() + "</SIGNATURE>");
       sb.append("<RETURNTYPE>" + method.getReturnType() + "</RETURNTYPE>");
       sb.append("</METHOD>");
     }
     sb.append("</METHODS>");
   }
 }
 @SuppressWarnings("deprecation")
 private boolean isParameterNamesAvailable() throws Exception {
   ASTParser parser = ASTParser.newParser(AST.JLS3);
   parser.setIgnoreMethodBodies(true);
   IJavaProject javaProject = projectProvider.getJavaProject(resourceSet);
   parser.setProject(javaProject);
   IType type = javaProject.findType("org.eclipse.xtext.common.types.testSetups.TestEnum");
   IBinding[] bindings = parser.createBindings(new IJavaElement[] {type}, null);
   ITypeBinding typeBinding = (ITypeBinding) bindings[0];
   IMethodBinding[] methods = typeBinding.getDeclaredMethods();
   for (IMethodBinding method : methods) {
     if (method.isConstructor()) {
       IMethod element = (IMethod) method.getJavaElement();
       if (element.exists()) {
         String[] parameterNames = element.getParameterNames();
         if (parameterNames.length == 1 && parameterNames[0].equals("string")) {
           return true;
         }
       } else {
         return false;
       }
     }
   }
   return false;
 }
 private boolean canSwitchNames(IMethod nukeTarget, IMethod nameSwitchTarget) {
   String nukeName = nukeTarget.getElementName();
   String nameSwitchName = nameSwitchTarget.getElementName();
   boolean result = !nukeName.equals(nameSwitchName);
   result &= !hasMember(nukeTarget.getDeclaringType(), nameSwitchName);
   result &= !hasMember(nameSwitchTarget.getDeclaringType(), nukeName);
   return result;
 }
 public boolean visit(MethodDeclaration node) {
   if (null != m_methodFilter) {
     return node.getName().getIdentifier().equals(m_methodFilter.getElementName())
         && node.parameters().size() == m_methodFilter.getNumberOfParameters();
   } else {
     return true;
   }
 }
 private ICompilationUnit[] getDeclarationCUs() {
   Set<ICompilationUnit> cus = new HashSet<>();
   for (Iterator<IMethod> iter = fMethodsToRename.iterator(); iter.hasNext(); ) {
     IMethod method = iter.next();
     cus.add(method.getCompilationUnit());
   }
   return cus.toArray(new ICompilationUnit[cus.size()]);
 }
Example #17
0
 public String getReturnType() {
   try {
     IType type = method.getDeclaringType();
     String name = getClassNameFromSignature(method.getReturnType());
     return getQualifiedClassName(type, name);
   } catch (JavaModelException e) {
     return null;
   }
 }
 @Override
 public Change createChange(IProgressMonitor monitor) throws CoreException {
   try {
     final TextChange[] changes = fChangeManager.getAllChanges();
     final List<TextChange> list = new ArrayList<>(changes.length);
     list.addAll(Arrays.asList(changes));
     String project = null;
     IJavaProject javaProject = fMethod.getJavaProject();
     if (javaProject != null) project = javaProject.getElementName();
     int flags =
         JavaRefactoringDescriptor.JAR_MIGRATION
             | JavaRefactoringDescriptor.JAR_REFACTORING
             | RefactoringDescriptor.STRUCTURAL_CHANGE;
     try {
       if (!Flags.isPrivate(fMethod.getFlags())) flags |= RefactoringDescriptor.MULTI_CHANGE;
     } catch (JavaModelException exception) {
       JavaPlugin.log(exception);
     }
     final IType declaring = fMethod.getDeclaringType();
     try {
       if (declaring.isAnonymous() || declaring.isLocal())
         flags |= JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
     } catch (JavaModelException exception) {
       JavaPlugin.log(exception);
     }
     final String description =
         Messages.format(
             RefactoringCoreMessages.RenameMethodProcessor_descriptor_description_short,
             BasicElementLabels.getJavaElementName(fMethod.getElementName()));
     final String header =
         Messages.format(
             RefactoringCoreMessages.RenameMethodProcessor_descriptor_description,
             new String[] {
               JavaElementLabels.getTextLabel(fMethod, JavaElementLabels.ALL_FULLY_QUALIFIED),
               BasicElementLabels.getJavaElementName(getNewElementName())
             });
     final String comment = new JDTRefactoringDescriptorComment(project, this, header).asString();
     final RenameJavaElementDescriptor descriptor =
         RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(
             IJavaRefactorings.RENAME_METHOD);
     descriptor.setProject(project);
     descriptor.setDescription(description);
     descriptor.setComment(comment);
     descriptor.setFlags(flags);
     descriptor.setJavaElement(fMethod);
     descriptor.setNewName(getNewElementName());
     descriptor.setUpdateReferences(fUpdateReferences);
     descriptor.setKeepOriginal(fDelegateUpdating);
     descriptor.setDeprecateDelegate(fDelegateDeprecation);
     return new DynamicValidationRefactoringChange(
         descriptor,
         RefactoringCoreMessages.RenameMethodProcessor_change_name,
         list.toArray(new Change[list.size()]));
   } finally {
     monitor.done();
   }
 }
  /** {@inheritDoc} */
  public IHyperlink createHyperlink(
      String name,
      String target,
      Node node,
      Node parentNode,
      IDocument document,
      ITextViewer textViewer,
      IRegion hyperlinkRegion,
      IRegion cursor) {
    String parentName = null;
    if (parentNode != null) {
      parentName = parentNode.getNodeName();
    }

    List<String> propertyPaths = new ArrayList<String>();
    hyperlinkRegion =
        BeansEditorUtils.extractPropertyPathFromCursorPosition(
            hyperlinkRegion, cursor, target, propertyPaths);
    if ("bean".equals(parentName) && StringUtils.hasText(target)) {
      IFile file = BeansEditorUtils.getFile(document);
      String className =
          BeansEditorUtils.getClassNameForBean(file, node.getOwnerDocument(), parentNode);
      IType type = JdtUtils.getJavaType(file.getProject(), className);

      if (type != null) {
        IBeansConfig config = BeansCorePlugin.getModel().getConfig(file);
        if (config != null && parentNode instanceof Element) {
          IModelElement element = BeansModelUtils.getModelElement((Element) parentNode, config);
          int argIndex = getArgumentIndex(node);
          if (argIndex >= 0) {
            if (element instanceof IBean) {
              IBean bean = (IBean) element;
              int count = bean.getConstructorArguments().size();
              if (count > 0) {
                try {
                  Set<IMethod> methods = Introspector.getConstructors(type, count, false);
                  Iterator<IMethod> iter = methods.iterator();
                  while (iter.hasNext()) {
                    IMethod candidate = iter.next();
                    if (target.equalsIgnoreCase(candidate.getParameterNames()[argIndex])) {
                      // return new JavaElementHyperlink(hyperlinkRegion,
                      // candidate.getParameters()[argIndex]);
                      // TODO: just a temporary workaround for making this Eclipse 3.6 compatible
                      return new JavaElementHyperlink(hyperlinkRegion, candidate);
                    }
                  }
                } catch (JavaModelException e) {
                  // do nothing
                }
              }
            }
          }
        }
      }
    }
    return null;
  }
Example #20
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 static IMethod[] getMethods(IType type, String[] names, String[][] signatures) {
   if (names == null || signatures == null) return new IMethod[0];
   List methods = new ArrayList(names.length);
   for (int i = 0; i < names.length; i++) {
     IMethod method = type.getMethod(names[i], signatures[i]);
     assertTrue("method " + method.getElementName() + " does not exist", method.exists());
     if (!methods.contains(method)) methods.add(method);
   }
   return (IMethod[]) methods.toArray(new IMethod[methods.size()]);
 }
Example #22
0
 public static String getParentName(IMethod method) {
   // Special support Ajdt intertype declarations
   String methodName = method.getElementName();
   int index = methodName.lastIndexOf('.');
   if (index > 0) {
     return methodName.substring(0, index);
   } else {
     return method.getParent().getElementName();
   }
 }
  private void extractIMethod(IMethod method, boolean annotationElement) {
    try {
      StringBuilder fqnBuilder = new StringBuilder(fqnStack.peek());
      if (method.isConstructor()) {
        fqnBuilder.append('.').append("<init>");
      } else {
        fqnBuilder.append('.').append(method.getElementName());
      }
      fqnBuilder.append('(');
      boolean first = true;
      for (String param : method.getParameterTypes()) {
        if (first) {
          first = false;
        } else {
          fqnBuilder.append(',');
        }
        String sig = typeSignatureToFqn(param);
        fqnBuilder.append(sig);
      }
      fqnBuilder.append(')');

      String fqn = fqnBuilder.toString();

      // Write the entity
      if (annotationElement) {
        entityWriter.writeAnnotationElement(fqn, method.getFlags(), path);
      } else if (method.isConstructor()) {
        entityWriter.writeConstructor(fqn, method.getFlags(), path);
      } else {
        entityWriter.writeMethod(fqn, method.getFlags(), path);
      }

      // Write the inside relation
      relationWriter.writeInside(fqn, fqnStack.peek(), path);

      // Write the returns relation
      relationWriter.writeReturns(fqn, typeSignatureToFqn(method.getReturnType()), path);

      // Write the receives relation
      String[] paramTypes = method.getParameterTypes();
      for (int i = 0; i < paramTypes.length; i++) {
        localVariableWriter.writeClassParameter(
            "arg" + i, typeSignatureToFqn(paramTypes[i]), fqn, i, path);
        //        relationWriter.writeReceives(fqn, typeSignatureToFqn(paramTypes[i]), "arg" + i,
        // i);
      }

      int pos = 0;
      for (ITypeParameter param : method.getTypeParameters()) {
        relationWriter.writeParametrizedBy(fqn, getTypeParam(param), pos++, path);
      }
    } catch (JavaModelException e) {
      logger.log(Level.SEVERE, "Error in extracting class file", e);
    }
  }
Example #24
0
  public void testOutputParameterOfMethod() throws JavaModelException {
    assertNotNull(getTestSetting().getRoleJavaElement());
    assertTrue(getTestSetting().getRoleJavaElement().exists());

    IMethod method = getTestSetting().getRoleJavaElement().getMethod(METHOD_NAME, new String[0]);
    assertNotNull(method);
    assertTrue(method.exists());

    String returnType = method.getReturnType();
    assertEquals(returnType, RETURN_TYPE);
  }
Example #25
0
  /**
   * Finds a method in a list of methods. Compares methods by signature (only SimpleNames of types),
   * and not by the declaring type.
   *
   * @param method the method to find
   * @param allMethods the methods to look at
   * @return The found method or <code>null</code>, if nothing found
   * @throws JavaModelException
   */
  public static IMethod findMethod(IMethod method, IMethod[] allMethods) throws JavaModelException {
    String name = method.getElementName();
    String[] paramTypes = method.getParameterTypes();
    boolean isConstructor = method.isConstructor();

    for (int i = 0; i < allMethods.length; i++) {
      if (JavaModelUtil.isSameMethodSignature(name, paramTypes, isConstructor, allMethods[i]))
        return allMethods[i];
    }
    return null;
  }
 /**
  * Calculate proposals. This implementation calls {@link #calculateType} to get the root for the
  * search and passes the returned {@link IType} and the instance's {@link IMethodFilter} to {@link
  * Introspector#findAllMethods(IType, String, IMethodFilter)}.
  *
  * <p>If a match is found the {@link #createMethodProposal} is called to report the match as a
  * proposal in the content assist request.
  */
 public void computeProposals(
     IContentAssistContext context, IContentAssistProposalRecorder recorder) {
   Set<String> proposedMethods = new HashSet<String>();
   for (IMethod method :
       Introspector.findAllMethods(calculateType(context), context.getMatchString(), filter)) {
     if (!proposedMethods.contains(method.getElementName())) {
       proposedMethods.add(method.getElementName());
       createMethodProposal(recorder, method);
     }
   }
 }
 @Override
 protected JvmOperation getMethodFromType(EObject context, Class<?> type, String method) {
   JvmOperation result = super.getMethodFromType(context, type, method);
   if (result != null) {
     IJavaElement found = elementFinder.findElementFor(result);
     assertEquals(IJavaElement.METHOD, found.getElementType());
     assertEquals(result.getSimpleName(), found.getElementName());
     IMethod foundMethod = (IMethod) found;
     assertEquals(result.getParameters().size(), foundMethod.getNumberOfParameters());
   }
   return result;
 }
  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 boolean hasMainMethod(IType t) {
   try {
     for (IMethod m : t.getMethods()) {
       if (m.isMainMethod()) {
         return true;
       }
     }
   } catch (Exception e) {
     BootActivator.log(e);
   }
   return false;
 }
 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());
 }