Example #1
0
 private static void checkMethodInType(
     IType destinationType, RefactoringStatus result, IMethod method) throws JavaModelException {
   IMethod[] destinationTypeMethods = destinationType.getMethods();
   IMethod found = findMethod(method, destinationTypeMethods);
   if (found != null) {
     RefactoringStatusContext context =
         JavaStatusContext.create(destinationType.getCompilationUnit(), found.getSourceRange());
     String message =
         Messages.format(
             RefactoringCoreMessages.MemberCheckUtil_signature_exists,
             new String[] {
               BasicElementLabels.getJavaElementName(method.getElementName()),
               getQualifiedLabel(destinationType)
             });
     result.addError(message, context);
   } else {
     IMethod similar = Checks.findMethod(method, destinationType);
     if (similar != null) {
       String message =
           Messages.format(
               RefactoringCoreMessages.MemberCheckUtil_same_param_count,
               new String[] {
                 BasicElementLabels.getJavaElementName(method.getElementName()),
                 getQualifiedLabel(destinationType)
               });
       RefactoringStatusContext context =
           JavaStatusContext.create(
               destinationType.getCompilationUnit(), similar.getSourceRange());
       result.addWarning(message, context);
     }
   }
 }
 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;
 }
 /**
  * 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);
     }
   }
 }
 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>");
   }
 }
Example #5
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);
      }
    }
  }
Example #6
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();
  }
  private RefactoringStatus checkRelatedMethods() throws CoreException {
    RefactoringStatus result = new RefactoringStatus();
    for (Iterator<IMethod> iter = fMethodsToRename.iterator(); iter.hasNext(); ) {
      IMethod method = iter.next();

      result.merge(
          Checks.checkIfConstructorName(
              method, getNewElementName(), method.getDeclaringType().getElementName()));

      String[] msgData =
          new String[] {
            BasicElementLabels.getJavaElementName(method.getElementName()),
            BasicElementLabels.getJavaElementName(
                method.getDeclaringType().getFullyQualifiedName('.'))
          };
      if (!method.exists()) {
        result.addFatalError(
            Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_not_in_model, msgData));
        continue;
      }
      if (method.isBinary())
        result.addFatalError(
            Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_no_binary, msgData));
      if (method.isReadOnly())
        result.addFatalError(
            Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_no_read_only, msgData));
      if (JdtFlags.isNative(method))
        result.addError(
            Messages.format(RefactoringCoreMessages.RenameMethodRefactoring_no_native_1, msgData));
    }
    return result;
  }
Example #8
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 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;
   }
 }
 protected void initialize(IMethod method) {
   fMethod = method;
   if (!fInitialized) {
     if (method != null) setNewElementName(method.getElementName());
     fUpdateReferences = true;
     initializeWorkingCopyOwner();
   }
 }
 @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();
   }
 }
Example #12
0
 public static String getMethodName(IMethod method) {
   // Special support Ajdt intertype declarations
   String methodName = method.getElementName();
   int index = methodName.lastIndexOf('.');
   if (index > 0) {
     methodName = methodName.substring(index + 1);
   }
   return methodName;
 }
Example #13
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 #15
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 #17
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;
  }
Example #18
0
 public static String getPropertyNameFromMethodName(IMethod method) {
   // Special support Ajdt intertype declarations
   String methodName = method.getElementName();
   int index = methodName.lastIndexOf('.');
   if (index > 0) {
     methodName = methodName.substring(index + 1);
   }
   String replaceText = methodName.substring("set".length());
   if (replaceText != null) {
     replaceText = java.beans.Introspector.decapitalize(replaceText);
   }
   return replaceText;
 }
 private boolean hasMember(IType type, String name) {
   boolean result = false;
   try {
     for (IMethod method : type.getMethods()) {
       result |= name.equals(method.getElementName());
     }
   } catch (JavaModelException jamox) {
     // defensive: assume the method is there, try another combination
     result = true;
     trace(jamox, type.getElementName());
   }
   return result;
 }
 @Override
 public boolean visit(MethodDeclaration node) {
   if (nestLevel != 1) return false;
   if (targetMethod.getElementName().equals(node.getName().getFullyQualifiedName())) {
     IMethod method = (IMethod) node.resolveBinding().getJavaElement();
     if (targetMethod.isSimilar(method)) {
       mapperMethod = new MapperMethod();
       mapperMethod.setMethodDeclaration(node);
       return true;
     }
   }
   return false;
 }
 public static IMethod[] findMethods(
     IMethod[] selectedMethods, String[] namesOfMethods, String[][] signaturesOfMethods) {
   List found = new ArrayList(selectedMethods.length);
   for (int i = 0; i < selectedMethods.length; i++) {
     IMethod method = selectedMethods[i];
     String[] paramTypes = method.getParameterTypes();
     for (int j = 0; j < namesOfMethods.length; j++) {
       String methodName = namesOfMethods[j];
       if (!methodName.equals(method.getElementName())) continue;
       String[] methodSig = signaturesOfMethods[j];
       if (!areSameSignatures(paramTypes, methodSig)) continue;
       found.add(method);
     }
   }
   return (IMethod[]) found.toArray(new IMethod[found.size()]);
 }
  private String toSignature(IMethod method) {
    StringBuilder result = new StringBuilder(method.getElementName());
    String[] types = method.getParameterTypes();
    try {
      String[] names = method.getParameterNames();
      result.append("(");
      for (int i = 0; i < types.length; i++) {
        if (i > 0) result.append(", ");
        result.append(Signature.toString(types[i]) + " " + names[i]);
      }
      result.append(")");
    } catch (JavaModelException ex) {
      // ignore
    }

    return result.toString();
  }
  public String convertToString(Object parameterValue) throws ParameterValueConversionException {

    if (!(parameterValue instanceof IJavaElement)) {
      throw new ParameterValueConversionException(
          "parameterValue must be an IJavaElement"); //$NON-NLS-1$
    }

    IJavaElement javaElement = (IJavaElement) parameterValue;

    IJavaProject javaProject = javaElement.getJavaProject();
    if (javaProject == null) {
      throw new ParameterValueConversionException(
          "Could not get IJavaProject for element"); //$NON-NLS-1$
    }

    StringBuffer buffer;

    if (javaElement instanceof IType) {
      IType type = (IType) javaElement;
      buffer = composeTypeReference(type);
    } else if (javaElement instanceof IMethod) {
      IMethod method = (IMethod) javaElement;
      buffer = composeTypeReference(method.getDeclaringType());
      buffer.append(TYPE_END_CHAR);
      buffer.append(method.getElementName());
      String[] parameterTypes = method.getParameterTypes();
      buffer.append(PARAM_START_CHAR);
      for (int i = 0; i < parameterTypes.length; i++) {
        buffer.append(parameterTypes[i]);
      }
      buffer.append(PARAM_END_CHAR);
    } else if (javaElement instanceof IField) {
      IField field = (IField) javaElement;
      buffer = composeTypeReference(field.getDeclaringType());
      buffer.append(TYPE_END_CHAR);
      buffer.append(field.getElementName());
    } else {
      throw new ParameterValueConversionException("Unsupported IJavaElement type"); // $NON-NLS-1$
    }

    return buffer.toString();
  }
  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 ? '-' : ')');
  }
Example #25
0
 /**
  * We don't include nested types because structural changes of nested types should not affect
  * Xtend classes which use top level types.
  *
  * @deprecated This method is not used anymore.
  */
 @Deprecated
 protected void traverseType(IType type, NameBasedEObjectDescriptionBuilder acceptor) {
   try {
     if (type.exists()) {
       for (IField field : type.getFields()) {
         if (!Flags.isSynthetic(field.getFlags())) {
           String fieldName = field.getElementName();
           acceptor.accept(fieldName);
         }
       }
       for (IMethod method : type.getMethods()) {
         if (!Flags.isSynthetic(method.getFlags())) {
           String methodName = method.getElementName();
           acceptor.accept(methodName);
         }
       }
     }
   } catch (JavaModelException e) {
     if (LOGGER.isDebugEnabled()) LOGGER.debug(e, e);
   }
 }
Example #26
0
  public static void launchMethodConfiguration(
      IJavaProject javaProject,
      IMethod imethod,
      String complianceLevel,
      String runMode,
      RunInfo runInfo) {

    Set /*<String>*/ groups = new HashSet();
    List allmethods = solveDependsOn(imethod);
    IMethod[] methods = new IMethod[allmethods.size()];
    for (int i = 0; i < allmethods.size(); i++) {
      MethodDefinition md = (MethodDefinition) allmethods.get(i);
      methods[i] = md.getMethod();
      groups.addAll(md.getGroups());
    }

    if (!groups.isEmpty()) {
      groupDependencyWarning(imethod.getElementName(), groups);
    }

    launchMethodBasedConfiguration(javaProject, methods, complianceLevel, runMode, runInfo);
  }
  @Override
  /**
   * Checks the final conditions in order to perform the refactoring. Specifically, we check if the
   * variable is used in only a single lower scope than it is declared in, and if this check fails
   * for any reason, the appropriate error status is set.
   */
  public RefactoringStatus checkFinalConditions(IProgressMonitor pm)
      throws CoreException, OperationCanceledException {

    RefactoringStatus status = new RefactoringStatus();

    ICompilationUnit Unit = method.getCompilationUnit();
    compilationUnit = parse(Unit, pm);

    try {
      pm.beginTask("Checking validity...", 1);

      // Do the work to check the final conditions
      variableVisitor = new LocalVarVisitor(this);
      variableVisitor.visit(compilationUnit);
      compilationUnit.accept(variableVisitor);

      // Now check for any errors that may be present
      ASTNode sp = variableVisitor.getScopeParent();
      ASTNode lsp = variableVisitor.getLowerScopeParent();

      if (sp == null) {
        // the variable was never found
        setRefactoringStatus(VARIABLE_NOT_FOUND);
      } else if (lsp == null) {
        setRefactoringStatus(NO_SCOPE_TO_REDUCE_TO);
      }

      if (refactoringStatus == VARIABLE_USED_IN_DECLARING_SCOPE) {
        status.merge(
            RefactoringStatus.createErrorStatus(
                varName
                    + " in method "
                    + method.getElementName()
                    + " is used in the same scope it is declared in."));
      } else if (refactoringStatus == VARIABLE_IS_FIELD) {
        status.merge(
            RefactoringStatus.createErrorStatus(
                varName + " is a field variable and" + " its scope cannot be reduced."));
      } else if (refactoringStatus == NO_SCOPE_TO_REDUCE_TO) {
        status.merge(
            RefactoringStatus.createErrorStatus(
                "No scope to possibly reduce "
                    + varName
                    + " in method "
                    + method.getElementName()
                    + " to."));
      } else if (refactoringStatus == VARIABLE_USED_IN_MULTIPLE_LOWER_SCOPES) {
        status.merge(
            RefactoringStatus.createErrorStatus(
                varName
                    + " is used in multiple lower scopes"
                    + " and cannot be reduced in method "
                    + method.getElementName()));
      } else if (refactoringStatus == VARIABLE_FIRST_INITIALIZED_IN_FOR_DECLARATION) {
        status.merge(
            RefactoringStatus.createErrorStatus(
                varName
                    + " is first initialized in a for loop"
                    + " and cannot be reduced in method "
                    + method.getElementName()));
      } else if (refactoringStatus == VARIABLE_NOT_FOUND) {
        status.merge(
            RefactoringStatus.createErrorStatus(varName + " not found in method " + method));
      }

    } finally {
      pm.done();
    }

    return status;
  }
 /**
  * Get the name of the method to refactor on
  *
  * @return the name of the method to refactor
  */
 public String getMethodName() {
   return method.getElementName();
 }
  private IJavaElement visit(IType javaType) {
    IBindingProvider mirror = null;
    if (ceylonDeclaration instanceof LazyClass) {
      LazyClass lazyClass = (LazyClass) ceylonDeclaration;
      if (!lazyClass.isAbstraction() && lazyClass.isOverloaded()) {
        IBindingProvider constructor = (IBindingProvider) lazyClass.getConstructor();
        if (constructor != null) {
          mirror = constructor;
        }
      }
      if (mirror == null) {
        mirror = (IBindingProvider) lazyClass.classMirror;
      }
    }
    if (ceylonDeclaration instanceof LazyInterface) {
      mirror = (IBindingProvider) ((LazyInterface) ceylonDeclaration).classMirror;
    }
    if (ceylonDeclaration instanceof LazyValue) {
      mirror = (IBindingProvider) ((LazyValue) ceylonDeclaration).classMirror;
    }
    if (ceylonDeclaration instanceof JavaBeanValue) {
      JavaBeanValue javaBeanValue = ((JavaBeanValue) ceylonDeclaration);
      Scope container = javaBeanValue.getContainer();
      if (container instanceof LazyClass) {
        mirror = (IBindingProvider) ((LazyClass) container).classMirror;
      }
      if (container instanceof LazyInterface) {
        mirror = (IBindingProvider) ((LazyInterface) container).classMirror;
      }
      if (container instanceof LazyValue) {
        mirror = (IBindingProvider) ((LazyValue) container).classMirror;
      }
      if (declarationMatched(javaType, mirror) != null) {
        try {
          for (IMethod javaMethod : javaType.getMethods()) {
            if (javaMethod.getElementName().equals(javaBeanValue.getGetterName())) {
              return javaMethod;
            }
          }
        } catch (JavaModelException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      return visit((IParent) javaType);
    }
    if (ceylonDeclaration instanceof FieldValue) {
      FieldValue fieldValue = ((FieldValue) ceylonDeclaration);
      Scope container = fieldValue.getContainer();
      if (container instanceof LazyClass) {
        mirror = (IBindingProvider) ((LazyClass) container).classMirror;
      }
      if (container instanceof LazyInterface) {
        mirror = (IBindingProvider) ((LazyInterface) container).classMirror;
      }
      if (container instanceof LazyValue) {
        mirror = (IBindingProvider) ((LazyValue) container).classMirror;
      }
      if (declarationMatched(javaType, mirror) != null) {
        try {
          for (IField javaField : javaType.getFields()) {
            if (javaField.getElementName().equals(fieldValue.getRealName())) {
              return javaField;
            }
          }
        } catch (JavaModelException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      return visit((IParent) javaType);
    }

    IJavaElement result = declarationMatched(javaType, mirror);
    if (result != null) {
      return result;
    }
    return visit((IParent) javaType);
  }
  @Override
  public List<ICompletionProposal> computeCompletionProposals(
      final ContentAssistInvocationContext context, final IProgressMonitor monitor) {
    final List<ICompletionProposal> list = new ArrayList<ICompletionProposal>();
    boolean extendContext = false;
    try {
      if (context instanceof JavaContentAssistInvocationContext) {
        final ITextViewer viewer = context.getViewer();
        final List<ScriptVariable> scriptVariables = getScriptVariables(viewer);
        if (scriptVariables.isEmpty()) {
          return list;
        }
        final CompletionContext coreContext =
            ((JavaContentAssistInvocationContext) context).getCoreContext();
        if (coreContext != null && !coreContext.isExtended()) {
          // must use reflection to set the fields
          ReflectionUtils.setPrivateField(
              InternalCompletionContext.class, "isExtended", coreContext, true);
          extendContext = true;
        }
        final ICompilationUnit unit =
            ((JavaContentAssistInvocationContext) context).getCompilationUnit();
        if (unit instanceof GroovyCompilationUnit) {
          if (((GroovyCompilationUnit) unit).getModuleNode() == null) {
            return Collections.emptyList();
          }
          final ContentAssistContext assistContext =
              new GroovyCompletionProposalComputer()
                  .createContentAssistContext(
                      (GroovyCompilationUnit) unit,
                      context.getInvocationOffset(),
                      context.getDocument());
          CharSequence prefix = null;
          try {
            prefix = context.computeIdentifierPrefix();
          } catch (final BadLocationException e) {
            BonitaStudioLog.error(e);
          }

          if (assistContext != null && assistContext.completionNode instanceof VariableExpression) {
            try {
              final VariableExpression expr = (VariableExpression) assistContext.completionNode;
              if (scriptVariables != null) {
                for (final ScriptVariable f : scriptVariables) {
                  if (expr.getName().equals(f.getName())) {
                    final IType type = javaProject.findType(f.getType());
                    if (type == null) {
                      return list;
                    }
                    for (final IMethod m : type.getMethods()) {
                      if (m.getElementName().startsWith(prefix.toString())) {
                        final GroovyCompletionProposal proposal =
                            new GroovyCompletionProposal(
                                CompletionProposal.METHOD_REF, context.getInvocationOffset());
                        proposal.setName(m.getElementName().toCharArray());
                        proposal.setCompletion(
                            m.getElementName().substring(prefix.length()).toCharArray());
                        proposal.setFlags(m.getFlags());

                        if (prefix.length() == m.getElementName().length()) {
                          proposal.setReplaceRange(
                              context.getInvocationOffset(), context.getInvocationOffset());
                          proposal.setReceiverRange(0, 0);
                        } else {
                          proposal.setReplaceRange(
                              context.getInvocationOffset() - prefix.length(),
                              context.getInvocationOffset());
                          proposal.setReceiverRange(prefix.length(), prefix.length());
                        }

                        final char[][] parametersArray =
                            new char[m.getParameterNames().length][256];
                        final List<Parameter> parameters = new ArrayList<Parameter>();
                        for (int i = 0; i < m.getParameterNames().length; i++) {
                          parametersArray[i] = m.getParameterNames()[i].toCharArray();
                          parameters.add(
                              new Parameter(
                                  ClassHelper.make(
                                      Signature.getSignatureSimpleName(m.getParameterTypes()[i])),
                                  m.getParameterNames()[i]));
                        }

                        final ClassNode classNode =
                            ClassHelper.make(m.getDeclaringType().getFullyQualifiedName());
                        proposal.setDeclarationSignature(
                            ProposalUtils.createTypeSignature(classNode));
                        proposal.setParameterNames(parametersArray);
                        if (m.getDeclaringType().getFullyQualifiedName().equals(f.getType())) {
                          proposal.setRelevance(100);
                        }

                        final MethodNode methodNode =
                            new MethodNode(
                                m.getElementName(),
                                m.getFlags(),
                                ClassHelper.make(
                                    Signature.getSignatureSimpleName(m.getReturnType())),
                                parameters.toArray(new Parameter[parameters.size()]),
                                new ClassNode[0],
                                null);
                        final char[] methodSignature =
                            ProposalUtils.createMethodSignature(methodNode);
                        proposal.setSignature(methodSignature);

                        final GroovyJavaGuessingCompletionProposal groovyProposal =
                            GroovyJavaGuessingCompletionProposal.createProposal(
                                proposal,
                                (JavaContentAssistInvocationContext) context,
                                true,
                                "Groovy",
                                ProposalFormattingOptions.newFromOptions());
                        if (groovyProposal != null) {
                          list.add(groovyProposal);
                        }
                      }
                    }
                  }
                }
              }
            } catch (final JavaModelException e) {
              BonitaStudioLog.error(e);
            }
          }
        }

        return list;
      }
    } finally {
      final CompletionContext coreContext =
          ((JavaContentAssistInvocationContext) context).getCoreContext();
      if (extendContext && coreContext != null && coreContext.isExtended()) {
        // must use reflection to set the fields
        ReflectionUtils.setPrivateField(
            InternalCompletionContext.class, "isExtended", coreContext, false);
      }
    }

    return Collections.emptyList();
  }