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;
  }
  // -------
  private static IMethod[] classesDeclareMethodName(
      ITypeHierarchy hier, List<IType> classes, IMethod method, String newName)
      throws CoreException {
    Set<IMethod> result = new HashSet<>();
    IType type = method.getDeclaringType();
    List<IType> subtypes = Arrays.asList(hier.getAllSubtypes(type));

    int parameterCount = method.getParameterTypes().length;
    boolean isMethodPrivate = JdtFlags.isPrivate(method);

    for (Iterator<IType> iter = classes.iterator(); iter.hasNext(); ) {
      IType clazz = iter.next();
      IMethod[] methods = clazz.getMethods();
      boolean isSubclass = subtypes.contains(clazz);
      for (int j = 0; j < methods.length; j++) {
        IMethod foundMethod =
            Checks.findMethod(newName, parameterCount, false, new IMethod[] {methods[j]});
        if (foundMethod == null) continue;
        if (isSubclass || type.equals(clazz)) result.add(foundMethod);
        else if ((!isMethodPrivate) && (!JdtFlags.isPrivate(methods[j]))) result.add(foundMethod);
      }
    }
    return result.toArray(new IMethod[result.size()]);
  }
  private static IMember getMember(IStructuredSelection selection) throws JavaModelException {
    if (selection.size() != 1) return null;

    Object element = selection.getFirstElement();
    if (!(element instanceof IMember)) return null;

    if (element instanceof IMethod) {
      IMethod method = (IMethod) element;
      String returnType = method.getReturnType();
      if (PrimitiveType.toCode(Signature.toString(returnType)) != null) return null;
      return method;
    } else if (element instanceof IField && !JdtFlags.isEnum((IMember) element)) {
      return (IField) element;
    }
    return null;
  }
  @Override
  public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
    if (!fMethod.exists()) {
      String message =
          Messages.format(
              RefactoringCoreMessages.RenameMethodRefactoring_deleted,
              BasicElementLabels.getFileName(fMethod.getCompilationUnit()));
      return RefactoringStatus.createFatalErrorStatus(message);
    }

    RefactoringStatus result = Checks.checkAvailability(fMethod);
    if (result.hasFatalError()) return result;
    result.merge(Checks.checkIfCuBroken(fMethod));
    if (JdtFlags.isNative(fMethod))
      result.addError(RefactoringCoreMessages.RenameMethodRefactoring_no_native);
    return result;
  }
  /**
   * Creates a new search scope with all compilation units possibly referencing <code>javaElement
   * </code>.
   *
   * @param javaElement the java element
   * @param considerVisibility consider visibility of javaElement iff <code>true</code>
   * @param sourceReferencesOnly consider references in source only (no references in binary)
   * @return the search scope
   * @throws JavaModelException if an error occurs
   */
  public static IJavaSearchScope create(
      IJavaElement javaElement, boolean considerVisibility, boolean sourceReferencesOnly)
      throws JavaModelException {
    if (considerVisibility & javaElement instanceof IMember) {
      IMember member = (IMember) javaElement;
      if (JdtFlags.isPrivate(member)) {
        if (member.getCompilationUnit() != null)
          return SearchEngine.createJavaSearchScope(
              new IJavaElement[] {member.getCompilationUnit()});
        else return SearchEngine.createJavaSearchScope(new IJavaElement[] {member});
      }
      // Removed code that does some optimizations regarding package visible members. The problem is
      // that
      // there can be a package fragment with the same name in a different source folder or project.
      // So we
      // have to treat package visible members like public or protected members.
    }

    IJavaProject javaProject = javaElement.getJavaProject();
    return SearchEngine.createJavaSearchScope(
        getAllScopeElements(javaProject, sourceReferencesOnly), false);
  }
 private static int getVisibility(IMember member) throws JavaModelException {
   if (JdtFlags.isPrivate(member)) return 0;
   if (JdtFlags.isPackageVisible(member)) return 1;
   if (JdtFlags.isProtected(member)) return 2;
   return 4;
 }
 private RefactoringStatus initialize(JavaRefactoringArguments arguments) {
   final String selection =
       arguments.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION);
   if (selection != null) {
     int offset = -1;
     int length = -1;
     final StringTokenizer tokenizer = new StringTokenizer(selection);
     if (tokenizer.hasMoreTokens()) offset = Integer.valueOf(tokenizer.nextToken()).intValue();
     if (tokenizer.hasMoreTokens()) length = Integer.valueOf(tokenizer.nextToken()).intValue();
     if (offset >= 0 && length >= 0) {
       fSelectionStart = offset;
       fSelectionLength = length;
     } else
       return RefactoringStatus.createFatalErrorStatus(
           Messages.format(
               RefactoringCoreMessages.InitializableRefactoring_illegal_argument,
               new Object[] {selection, JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION}));
   } else
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
             JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION));
   final String handle = arguments.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT);
   if (handle != null) {
     final IJavaElement element =
         JavaRefactoringDescriptorUtil.handleToElement(arguments.getProject(), handle, false);
     if (element == null
         || !element.exists()
         || element.getElementType() != IJavaElement.COMPILATION_UNIT)
       return JavaRefactoringDescriptorUtil.createInputFatalStatus(
           element, getName(), IJavaRefactorings.EXTRACT_CONSTANT);
     else fCu = (ICompilationUnit) element;
   } else
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
             JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT));
   final String visibility = arguments.getAttribute(ATTRIBUTE_VISIBILITY);
   if (visibility != null && !"".equals(visibility)) { // $NON-NLS-1$
     int flag = 0;
     try {
       flag = Integer.parseInt(visibility);
     } catch (NumberFormatException exception) {
       return RefactoringStatus.createFatalErrorStatus(
           Messages.format(
               RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
               ATTRIBUTE_VISIBILITY));
     }
     fVisibility = JdtFlags.getVisibilityString(flag);
   }
   final String name = arguments.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME);
   if (name != null && !"".equals(name)) // $NON-NLS-1$
   fConstantName = name;
   else
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
             JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME));
   final String replace = arguments.getAttribute(ATTRIBUTE_REPLACE);
   if (replace != null) {
     fReplaceAllOccurrences = Boolean.valueOf(replace).booleanValue();
   } else
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
             ATTRIBUTE_REPLACE));
   final String declareFinal = arguments.getAttribute(ATTRIBUTE_QUALIFY);
   if (declareFinal != null) {
     fQualifyReferencesWithDeclaringClassName = Boolean.valueOf(declareFinal).booleanValue();
   } else
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
             ATTRIBUTE_QUALIFY));
   return new RefactoringStatus();
 }
  private ExtractConstantDescriptor createRefactoringDescriptor() {
    final Map<String, String> arguments = new HashMap<>();
    String project = null;
    IJavaProject javaProject = fCu.getJavaProject();
    if (javaProject != null) project = javaProject.getElementName();
    int flags =
        JavaRefactoringDescriptor.JAR_REFACTORING | JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
    if (JdtFlags.getVisibilityCode(fVisibility) != Modifier.PRIVATE)
      flags |= RefactoringDescriptor.STRUCTURAL_CHANGE;

    final String expression = ASTNodes.asString(fSelectedExpression.getAssociatedExpression());
    final String description =
        Messages.format(
            RefactoringCoreMessages.ExtractConstantRefactoring_descriptor_description_short,
            BasicElementLabels.getJavaElementName(fConstantName));
    final String header =
        Messages.format(
            RefactoringCoreMessages.ExtractConstantRefactoring_descriptor_description,
            new String[] {
              BasicElementLabels.getJavaElementName(fConstantName),
              BasicElementLabels.getJavaCodeString(expression)
            });
    final JDTRefactoringDescriptorComment comment =
        new JDTRefactoringDescriptorComment(project, this, header);
    comment.addSetting(
        Messages.format(
            RefactoringCoreMessages.ExtractConstantRefactoring_constant_name_pattern,
            BasicElementLabels.getJavaElementName(fConstantName)));
    comment.addSetting(
        Messages.format(
            RefactoringCoreMessages.ExtractConstantRefactoring_constant_expression_pattern,
            BasicElementLabels.getJavaCodeString(expression)));
    String visibility = fVisibility;
    if ("".equals(visibility)) // $NON-NLS-1$
    visibility = RefactoringCoreMessages.ExtractConstantRefactoring_default_visibility;
    comment.addSetting(
        Messages.format(
            RefactoringCoreMessages.ExtractConstantRefactoring_visibility_pattern, visibility));
    if (fReplaceAllOccurrences)
      comment.addSetting(RefactoringCoreMessages.ExtractConstantRefactoring_replace_occurrences);
    if (fQualifyReferencesWithDeclaringClassName)
      comment.addSetting(RefactoringCoreMessages.ExtractConstantRefactoring_qualify_references);
    arguments.put(
        JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT,
        JavaRefactoringDescriptorUtil.elementToHandle(project, fCu));
    arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME, fConstantName);
    arguments.put(
        JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION,
        new Integer(fSelectionStart).toString()
            + " "
            + new Integer(fSelectionLength).toString()); // $NON-NLS-1$
    arguments.put(ATTRIBUTE_REPLACE, Boolean.valueOf(fReplaceAllOccurrences).toString());
    arguments.put(
        ATTRIBUTE_QUALIFY, Boolean.valueOf(fQualifyReferencesWithDeclaringClassName).toString());
    arguments.put(
        ATTRIBUTE_VISIBILITY, new Integer(JdtFlags.getVisibilityCode(fVisibility)).toString());

    ExtractConstantDescriptor descriptor =
        RefactoringSignatureDescriptorFactory.createExtractConstantDescriptor(
            project, description, comment.asString(), arguments, flags);
    return descriptor;
  }
  /**
   * Create a stub for a getter of the given field using getter/setter templates. The resulting code
   * has to be formatted and indented.
   *
   * @param field The field to create a getter for
   * @param getterName The chosen name for the getter
   * @param addComments If <code>true</code>, comments will be added.
   * @param flags The flags signaling visibility, if static, synchronized or final
   * @return Returns the generated stub.
   * @throws CoreException when stub creation failed
   */
  public static String getGetterStub(
      IField field, String getterName, boolean addComments, int flags) throws CoreException {
    String fieldName = field.getElementName();
    IType parentType = field.getDeclaringType();

    boolean isStatic = Flags.isStatic(flags);
    boolean isSync = Flags.isSynchronized(flags);
    boolean isFinal = Flags.isFinal(flags);

    String typeName = Signature.toString(field.getTypeSignature());
    String accessorName = StubUtility.getBaseName(field);

    String lineDelim =
        "\n"; // Use default line delimiter, as generated stub has to be formatted anyway
              // //$NON-NLS-1$
    StringBuffer buf = new StringBuffer();
    if (addComments) {
      String comment =
          CodeGeneration.getGetterComment(
              field.getCompilationUnit(),
              parentType.getTypeQualifiedName('.'),
              getterName,
              field.getElementName(),
              typeName,
              accessorName,
              lineDelim);
      if (comment != null) {
        buf.append(comment);
        buf.append(lineDelim);
      }
    }

    buf.append(JdtFlags.getVisibilityString(flags));
    buf.append(' ');
    if (isStatic) buf.append("static "); // $NON-NLS-1$
    if (isSync) buf.append("synchronized "); // $NON-NLS-1$
    if (isFinal) buf.append("final "); // $NON-NLS-1$

    buf.append(typeName);
    buf.append(' ');
    buf.append(getterName);
    buf.append("() {"); // $NON-NLS-1$
    buf.append(lineDelim);

    boolean useThis = StubUtility.useThisForFieldAccess(field.getJavaProject());
    if (useThis && !isStatic) {
      fieldName = "this." + fieldName; // $NON-NLS-1$
    }

    String body =
        CodeGeneration.getGetterMethodBodyContent(
            field.getCompilationUnit(),
            parentType.getTypeQualifiedName('.'),
            getterName,
            fieldName,
            lineDelim);
    if (body != null) {
      buf.append(body);
    }
    buf.append("}"); // $NON-NLS-1$
    buf.append(lineDelim);
    return buf.toString();
  }
Esempio n. 10
0
 private static boolean isInstanceField(IField field) throws CoreException {
   if (JavaModelUtil.isInterfaceOrAnnotation(field.getDeclaringType())) return false;
   else return !JdtFlags.isStatic(field);
 }