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);
    }
  }
Beispiel #2
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;
  }
 protected EClass getExpectedJvmType(IJavaElement javaElement) {
   try {
     switch (javaElement.getElementType()) {
       case IJavaElement.TYPE:
         return TypesPackage.Literals.JVM_TYPE;
       case IJavaElement.METHOD:
         IMethod method = (IMethod) javaElement;
         if (method.isConstructor()) return TypesPackage.Literals.JVM_CONSTRUCTOR;
         else return TypesPackage.Literals.JVM_OPERATION;
       case IJavaElement.FIELD:
         return TypesPackage.Literals.JVM_FIELD;
       default:
         return null;
     }
   } catch (JavaModelException exc) {
     throw new WrappedException(exc);
   }
 }
  protected void setUp() throws Exception {
    super.setUp();
    fProject = new SWTTestProject();
    IType control = fProject.getProject().findType("org.eclipse.swt.widgets.Control");

    ExtractInterfaceProcessor processor =
        new ExtractInterfaceProcessor(
            control, JavaPreferencesSettings.getCodeGenerationSettings(fProject.getProject()));
    fRefactoring = new ProcessorBasedRefactoring(processor);

    IMethod[] methods = control.getMethods();
    List extractedMembers = new ArrayList();
    for (int i = 0; i < methods.length; i++) {
      IMethod method = methods[i];
      int flags = method.getFlags();
      if (Flags.isPublic(flags) && !Flags.isStatic(flags) && !method.isConstructor()) {
        extractedMembers.add(method);
      }
    }
    processor.setTypeName("IControl");
    processor.setExtractedMembers(
        (IMember[]) extractedMembers.toArray(new IMember[extractedMembers.size()]));
    processor.setReplace(true);
  }
 /**
  * Computes all of the Javadoc completion proposals
  *
  * @param jcontext
  * @param corecontext
  * @return the complete list of Javadoc completion proposals or an empty list, never <code>null
  *     </code>
  * @since 1.0.500
  */
 List<ICompletionProposal> computeJavadocProposals(
     JavaContentAssistInvocationContext jcontext, CompletionContext corecontext) {
   ICompilationUnit cunit = jcontext.getCompilationUnit();
   if (cunit != null) {
     try {
       int offset = jcontext.getInvocationOffset();
       IJavaElement element = cunit.getElementAt(offset);
       if (!isVisible(element)) {
         return Collections.EMPTY_LIST;
       }
       ImageDescriptor imagedesc =
           jcontext
               .getLabelProvider()
               .createImageDescriptor(
                   org.eclipse.jdt.core.CompletionProposal.create(
                       org.eclipse.jdt.core.CompletionProposal.JAVADOC_BLOCK_TAG, offset));
       fImageHandle = (imagedesc == null ? null : imagedesc.createImage());
       int type = getType(element);
       int member = IApiJavadocTag.MEMBER_NONE;
       switch (element.getElementType()) {
         case IJavaElement.METHOD:
           {
             IMethod method = (IMethod) element;
             member = IApiJavadocTag.MEMBER_METHOD;
             if (method.isConstructor()) {
               member = IApiJavadocTag.MEMBER_CONSTRUCTOR;
             }
             break;
           }
         case IJavaElement.FIELD:
           {
             member = IApiJavadocTag.MEMBER_FIELD;
             break;
           }
         default:
           break;
       }
       IApiJavadocTag[] tags = ApiPlugin.getJavadocTagManager().getTagsForType(type, member);
       int tagcount = tags.length;
       if (tagcount > 0) {
         ArrayList<ICompletionProposal> list = null;
         collectExistingTags(element, jcontext);
         String completiontext = null;
         int tokenstart = corecontext.getTokenStart();
         int length = offset - tokenstart;
         for (int i = 0; i < tagcount; i++) {
           if (!acceptTag(tags[i], element)) {
             continue;
           }
           completiontext = tags[i].getCompleteTag(type, member);
           if (appliesToContext(
               jcontext.getDocument(), completiontext, tokenstart, (length > 0 ? length : 1))) {
             if (list == null) {
               list = new ArrayList<ICompletionProposal>(tagcount - i);
             }
             list.add(
                 new APIToolsJavadocCompletionProposal(
                     corecontext, completiontext, tags[i].getTagName(), fImageHandle));
           }
         }
         if (list != null) {
           return list;
         }
       }
     } catch (JavaModelException e) {
       fErrorMessage = e.getMessage();
     }
   }
   return Collections.EMPTY_LIST;
 }
  public JavaRefactoringDescriptor buildEclipseDescriptor() throws Exception {
    System.err.println("[eclipse-rename] Building descriptor...");
    IJavaElement element = location.getIJavaElement();
    String kind = getRenameKind(element);
    // [1] BUGFIX was needed:  The scripting interface didn't allow VariableDeclarationFragments as
    // IJavaElements
    // and thus had to be extended

    // [2] WORKAROUND for scripting interface bug (see below)
    if (kind.equals(IJavaRefactorings.RENAME_METHOD)) {
      IMethod m = (IMethod) element;
      if (m.isConstructor()) {
        // Rename the type instead (as the UI would do-- the scripting interface will only rename
        // the constructor, which is broken)
        kind = IJavaRefactorings.RENAME_TYPE;
        element = m.getDeclaringType();
      }
    }

    System.err.println("[eclipse-rename] Kind = " + kind + ",  element = " + element);

    // [3] Don't test for package fragments now
    if (kind.equals(IJavaRefactorings.RENAME_PACKAGE)) return null; // don't bother with this now

    if (element == null) {
      System.err.println("!!! ABORT: No IJavaElement to represent location");
      throw new RuntimeException("!!! ABORT: No IJavaElement for location");
    }

    if (element instanceof ILocalVariable) {
      System.err.println("element is of type " + element.getClass());
      final ILocalVariable fLocalVariable = (ILocalVariable) element;
      final ISourceRange sourceRange = fLocalVariable.getNameRange();
      final CompilationUnit fCompilationUnitNode = location.getCompilationUnit();
      ASTNode name = NodeFinder.perform(fCompilationUnitNode, sourceRange);
      System.err.println("node is of type " + name.getClass());
      if (name == null) System.err.println("!!! ILV doesn't have associated name!");
      if (name.getParent() instanceof VariableDeclaration)
        System.err.println("ILV has parent : " + (VariableDeclaration) name.getParent());
      else
        System.err.println(
            "!!! ILV doesn't have var declaration parent, instead " + name.getParent().getClass());
    }

    System.err.println("Trying to rename a " + kind + ": " + element);
    if (element instanceof SimpleName)
      System.err.println("  Name = '" + ((SimpleName) element).getIdentifier() + "'");

    if (kind.equals(IJavaRefactorings.RENAME_TYPE)) {
      System.err.println("(Possibly need a new launch configuration)");
      tproject.renameClass((IType) element, new_name);
    }

    final RenameJavaElementDescriptor descriptor =
        (RenameJavaElementDescriptor) getDescriptor(kind);
    descriptor.setJavaElement(element);
    descriptor.setNewName(this.new_name);

    if (element.getElementType() == IJavaElement.TYPE
        || element.getElementType() == IJavaElement.PACKAGE_FRAGMENT)
      descriptor.setUpdateQualifiedNames(true);
    else descriptor.setUpdateQualifiedNames(false);

    descriptor.setUpdateReferences(true);
    descriptor.setDeprecateDelegate(false);
    descriptor.setRenameGetters(false);
    descriptor.setRenameSetters(false);
    descriptor.setKeepOriginal(false);
    descriptor.setUpdateHierarchy(false);
    descriptor.setUpdateSimilarDeclarations(false);

    // [3] Fix:  Eclipse will complain if the transformation is a no-op, but we don't want that:
    if (element.getElementName().equals(this.new_name)) throw new NOPException();

    System.err.println("[eclipse-rename] Computed descriptor.");
    return descriptor;
  }
  private void extractIType(IType type) {
    try {
      String fqn = type.getFullyQualifiedName();

      // Write the entity
      if (type.isClass()) {
        entityWriter.writeClass(fqn, type.getFlags(), path);

        // Write the superclass
        String superSig = type.getSuperclassTypeSignature();
        if (superSig != null) {
          relationWriter.writeExtends(fqn, typeSignatureToFqn(superSig), path);
        }
      } else if (type.isAnnotation()) {
        entityWriter.writeAnnotation(fqn, type.getFlags(), path);
      } else if (type.isInterface()) {
        entityWriter.writeInterface(fqn, type.getFlags(), path);
      } else if (type.isEnum()) {
        entityWriter.writeEnum(fqn, type.getFlags(), path);
      }

      // Write the superinterfaces
      for (String superIntSig : type.getSuperInterfaceTypeSignatures()) {
        relationWriter.writeImplements(fqn, typeSignatureToFqn(superIntSig), path);
      }

      if (!fqnStack.isEmpty()) {
        relationWriter.writeInside(type.getFullyQualifiedName(), fqnStack.peek(), path);
      }

      fqnStack.push(type.getFullyQualifiedName());

      for (IType child : type.getTypes()) {
        extractIType(child);
      }

      for (IField field : type.getFields()) {
        if (!Flags.isSynthetic(field.getFlags())) {
          extractIField(field);
        }
      }

      for (IMethod method : type.getMethods()) {
        if (!Flags.isSynthetic(method.getFlags())
            || (Flags.isSynthetic(method.getFlags())
                && method.isConstructor()
                && method.getParameterTypes().length == 0)) {
          extractIMethod(method, type.isAnnotation());
        }
      }

      int pos = 0;
      for (ITypeParameter param : type.getTypeParameters()) {
        relationWriter.writeParametrizedBy(fqn, getTypeParam(param), pos++, path);
      }

      fqnStack.pop();
    } catch (Exception e) {
      logger.log(Level.SEVERE, "Error in extracting class file", e);
    }
  }
Beispiel #8
0
  /**
   * Determines is the java element contains a method with a specific annotation.
   *
   * <p>The syntax for the property tester is of the form: qualified or unqualified annotation name,
   * modifiers
   * <li>qualified or unqualified annotation name, required. For example, <code>org.junit.JUnit
   *     </code>.
   * <li>modifiers - optional space separated list of modifiers, for example, <code>public static
   *     </code>.
   * </ol>
   *
   * @param element the element to check for the method
   * @param annotationName the qualified or unqualified name of the annotation to look for
   * @return true if the method is found in the element, false otherwise
   */
  private boolean hasMethodWithAnnotation(IJavaElement element, Object[] args) {
    try {
      String annotationType = (String) args[0];
      int flags = 0;
      if (args.length > 1) {
        String[] modifiers = ((String) args[1]).split(" "); // $NON-NLS-1$
        for (int j = 0; j < modifiers.length; j++) {
          String modifier = modifiers[j];
          Integer flag = (Integer) fgModifiers.get(modifier);
          if (flag != null) {
            flags = flags | flag.intValue();
          }
        }
      } else {
        flags = -1;
      }

      IType type = getType(element);
      if (type == null || !type.exists()) {
        return false;
      }
      IMethod[] methods = type.getMethods();
      if (methods.length == 0) {
        return false;
      }

      IBuffer buffer = null;
      IOpenable openable = type.getOpenable();
      if (openable instanceof ICompilationUnit) {
        buffer = ((ICompilationUnit) openable).getBuffer();
      } else if (openable instanceof IClassFile) {
        buffer = ((IClassFile) openable).getBuffer();
      }
      if (buffer == null) {
        return false;
      }
      IScanner scanner = null; // delay initialization

      for (int i = 0; i < methods.length; i++) {
        IMethod curr = methods[i];
        if (curr.isConstructor() || (flags != -1 && flags != (curr.getFlags() & FLAGS_MASK))) {
          continue;
        }

        ISourceRange sourceRange = curr.getSourceRange();
        ISourceRange nameRange = curr.getNameRange();
        if (sourceRange != null && nameRange != null) {
          if (scanner == null) {
            scanner = ToolFactory.createScanner(false, false, true, false);
            scanner.setSource(buffer.getCharacters());
          }
          scanner.resetTo(sourceRange.getOffset(), nameRange.getOffset());
          if (findAnnotation(scanner, annotationType)) {
            return true;
          }
        }
      }
    } catch (JavaModelException e) {
    } catch (InvalidInputException e) {
    }
    return false;
  }
 private boolean isNuclearStrikeTargetable(IMethod method) throws JavaModelException {
   return !method.isBinary()
       && !method.isReadOnly()
       && !method.isConstructor()
       && isPrivate(method);
 }