/**
  * Collects the existing tags on the {@link IJavaElement} we have been activated on
  *
  * @param element
  * @param jcontext
  * @throws JavaModelException
  * @throws BadLocationException
  */
 private void collectExistingTags(
     IJavaElement element, JavaContentAssistInvocationContext jcontext) throws JavaModelException {
   if (element instanceof IMember) {
     IMember member = (IMember) element;
     ICompilationUnit cunit = jcontext.getCompilationUnit();
     if (cunit != null) {
       if (cunit.isWorkingCopy()) {
         cunit.reconcile(ICompilationUnit.NO_AST, false, false, null, null);
       }
       fParser.setSource(member.getSource().toCharArray());
       fParser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS);
       Map<String, String> options = element.getJavaProject().getOptions(true);
       options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
       fParser.setCompilerOptions(options);
       fParser.setStatementsRecovery(false);
       fParser.setResolveBindings(false);
       fParser.setBindingsRecovery(false);
       ASTNode ast = fParser.createAST(null);
       TagCollector collector = new TagCollector();
       if (ast.getNodeType() == ASTNode.TYPE_DECLARATION) {
         TypeDeclaration typeDeclaration = (TypeDeclaration) ast;
         List<BodyDeclaration> bodyDeclarations = typeDeclaration.bodyDeclarations();
         if (bodyDeclarations.size() == 1) {
           // only one element should be there as we are parsing a
           // specific member
           BodyDeclaration bodyDeclaration = bodyDeclarations.iterator().next();
           Javadoc javadoc = bodyDeclaration.getJavadoc();
           if (javadoc != null) {
             javadoc.accept(collector);
           }
         }
       }
     }
   }
 }
 public void run(IStructuredSelection selection) {
   IMember member = getMember(selection);
   if (!ActionUtil.isProcessable(getShell(), member)) return;
   FindOccurrencesEngine engine = FindOccurrencesEngine.create(new OccurrencesFinder());
   try {
     ISourceRange range = member.getNameRange();
     String result = engine.run(member.getTypeRoot(), range.getOffset(), range.getLength());
     if (result != null) showMessage(getShell(), fActionBars, result);
   } catch (JavaModelException e) {
     JavaPlugin.log(e);
   }
 }
Exemplo n.º 3
0
 private IJavaElement findSibling(IJavaElement curr, IJavaElement[] members)
     throws JavaModelException {
   IJavaElement res = null;
   int methodStart = ((IMember) curr).getSourceRange().getOffset();
   for (int i = members.length - 1; i >= 0; i--) {
     IMember member = (IMember) members[i];
     if (methodStart >= member.getSourceRange().getOffset()) {
       return res;
     }
     res = member;
   }
   return null;
 }
Exemplo n.º 4
0
  private Reader getContentReader(IMember member, IProgressMonitor monitor)
      throws JavaModelException {
    Reader contentReader = JavadocContentAccess.getContentReader(member, true);
    if (contentReader != null) {
      return contentReader;
    }

    if (member.getOpenable().getBuffer() == null) { // only if no source available
      String s = member.getAttachedJavadoc(monitor);
      if (s != null) {
        return new StringReader(s);
      }
    }
    return null;
  }
Exemplo n.º 5
0
 @Override
 public void run(IStructuredSelection selection) {
   try {
     IMember member = getMember(selection);
     if (member == null || !ActionUtil.isEditable(getShell(), member)) return;
     ISourceRange range = member.getNameRange();
     RefactoringExecutionStarter.startChangeTypeRefactoring(
         member.getCompilationUnit(), getShell(), range.getOffset(), range.getLength());
   } catch (CoreException e) {
     ExceptionHandler.handle(
         e,
         RefactoringMessages.ChangeTypeAction_dialog_title,
         RefactoringMessages.ChangeTypeAction_exception);
   }
 }
 /**
  * Returns if the given {@link IJavaElement} is externally visible <br>
  * <br>
  * Changes to the logic here must also be made in the {@link TagValidator} to ensure the
  * visibility is computed equally.
  *
  * @see TagValidator
  * @param element
  * @return <code>true</code> if the given element is visible <code>false</code> otherwise
  * @throws JavaModelException if a model lookup fails
  */
 boolean isVisible(IJavaElement element) throws JavaModelException {
   if (element != null) {
     switch (element.getElementType()) {
       case IJavaElement.FIELD:
       case IJavaElement.METHOD:
         {
           IMember member = (IMember) element;
           int flags = member.getFlags();
           IType type = member.getDeclaringType();
           if (Flags.isPublic(flags)
               || Flags.isProtected(flags)
               || (type != null && type.isInterface())) {
             return isVisible(type);
           }
           break;
         }
       case IJavaElement.TYPE:
         {
           IType type = (IType) element;
           int flags = type.getFlags();
           if (type.isLocal() && !type.isAnonymous() || Flags.isPrivate(flags)) {
             return false;
           }
           if (type.isMember()) {
             if ((Flags.isPublic(flags) && Flags.isStatic(flags))
                 || Flags.isPublic(flags)
                 || Flags.isProtected(flags)
                 || type.isInterface()) {
               return isVisible(type.getDeclaringType());
             }
           } else {
             return Flags.isPublic(flags) || type.isInterface();
           }
           break;
         }
       default:
         {
           break;
         }
     }
   }
   return false;
 }
Exemplo n.º 7
0
  public void testExact() throws CoreException, IOException {
    ICDIProject cdi = CDICorePlugin.getCDIProject(getTestProject(), true);

    Collection<IBean> bs =
        cdi.getBeans(new Path("/CDISolderTest/src/org/jboss/exact/FishFactory.java"));
    assertEquals(2, bs.size());
    IClassBean cls = null;
    IProducerMethod mtd = null;
    for (IBean b : bs) {
      if (b instanceof IClassBean) {
        cls = (IClassBean) b;
      } else if (b instanceof IProducerMethod) {
        mtd = (IProducerMethod) b;
      }
    }
    assertNotNull(cls);
    assertNotNull(mtd);
    Collection<IInjectionPoint> points = cls.getInjectionPoints();
    int count = 0;
    for (IInjectionPoint p : points) {
      Collection<IBean> injected = cdi.getBeans(false, p);
      IMember member = p.getSourceMember();
      if (member.getElementName().equals("peacefulFish")) {
        assertEquals(1, injected.size());
        IBean ib = injected.iterator().next();
        assertEquals("org.jboss.exact.Salmon", ib.getBeanClass().getFullyQualifiedName());
        count++;
      } else if (member.getElementName().equals("dangerousFish")) {
        assertEquals(1, injected.size());
        IBean ib = injected.iterator().next();
        assertEquals("org.jboss.exact.Shark", ib.getBeanClass().getFullyQualifiedName());
        count++;
      } else if (member.getElementName().equals("getTastyFish")) {
        assertEquals(1, injected.size());
        IBean ib = injected.iterator().next();
        assertEquals("org.jboss.exact.Salmon", ib.getBeanClass().getFullyQualifiedName());
        count++;
      } else {
      }
    }
    assertEquals(3, count);
  }
  /**
   * 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);
  }
  /* (non-JavaDoc)
   * Method declared in SelectionDispatchAction.
   */
  private IMember getMember(IStructuredSelection selection) {
    if (selection.size() != 1) return null;
    Object o = selection.getFirstElement();
    if (o instanceof IMember) {
      IMember member = (IMember) o;
      try {
        if (member.getNameRange() == null) return null;
      } catch (JavaModelException ex) {
        return null;
      }

      IClassFile file = member.getClassFile();
      if (file != null) {
        try {
          if (file.getSourceRange() != null) return member;
        } catch (JavaModelException e) {
          return null;
        }
      }
      return member;
    }
    return null;
  }
  @Override
  public void acceptSearchMatch(SearchMatch match) {
    if (fRequireExactMatch && (match.getAccuracy() != SearchMatch.A_ACCURATE)) {
      return;
    }

    if (match.isInsideDocComment()) {
      return;
    }

    if (match.getElement() != null && match.getElement() instanceof IMember) {
      IMember member = (IMember) match.getElement();
      switch (member.getElementType()) {
        case IJavaElement.METHOD:
        case IJavaElement.TYPE:
        case IJavaElement.FIELD:
        case IJavaElement.INITIALIZER:
          fSearchResults.addMember(
              member, member, match.getOffset(), match.getOffset() + match.getLength());
          break;
      }
    }
  }
  CalleeAnalyzerVisitor(
      IMember member, CompilationUnit compilationUnit, IProgressMonitor progressMonitor) {
    fSearchResults = new CallSearchResultCollector();
    this.fMember = member;
    this.fCompilationUnit = compilationUnit;
    this.fProgressMonitor = progressMonitor;

    try {
      ISourceRange sourceRange = member.getSourceRange();
      this.fMethodStartPosition = sourceRange.getOffset();
      this.fMethodEndPosition = fMethodStartPosition + sourceRange.getLength();
    } catch (JavaModelException jme) {
      JavaPlugin.log(jme);
    }
  }
  public void run(ISelection selection) {

    String errorTitle = CompareMessages.AddFromHistory_title;
    String errorMessage = CompareMessages.AddFromHistory_internalErrorMessage;
    Shell shell = getShell();

    ICompilationUnit cu = null;
    IParent parent = null;
    IMember input = null;

    // analyze selection
    if (selection.isEmpty()) {
      // no selection: we try to use the editor's input
      JavaEditor editor = getEditor();
      if (editor != null) {
        IEditorInput editorInput = editor.getEditorInput();
        IWorkingCopyManager manager = JavaPlugin.getDefault().getWorkingCopyManager();
        if (manager != null) {
          cu = manager.getWorkingCopy(editorInput);
          parent = cu;
        }
      }
    } else {
      input = getEditionElement(selection);
      if (input != null) {
        cu = input.getCompilationUnit();
        parent = input;
        input = null;

      } else {
        if (selection instanceof IStructuredSelection) {
          Object o = ((IStructuredSelection) selection).getFirstElement();
          if (o instanceof ICompilationUnit) {
            cu = (ICompilationUnit) o;
            parent = cu;
          }
        }
      }
    }

    if (parent == null || cu == null) {
      String invalidSelectionMessage = CompareMessages.AddFromHistory_invalidSelectionMessage;
      MessageDialog.openInformation(shell, errorTitle, invalidSelectionMessage);
      return;
    }

    IFile file = getFile(parent);
    if (file == null) {
      MessageDialog.openError(shell, errorTitle, errorMessage);
      return;
    }

    boolean inEditor = beingEdited(file);

    IStatus status = Resources.makeCommittable(file, shell);
    if (!status.isOK()) {
      return;
    }

    // get the document where to insert the text
    IPath path = file.getFullPath();
    ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
    ITextFileBuffer textFileBuffer = null;
    try {
      bufferManager.connect(path, LocationKind.IFILE, null);
      textFileBuffer = bufferManager.getTextFileBuffer(path, LocationKind.IFILE);
      IDocument document = textFileBuffer.getDocument();

      // configure EditionSelectionDialog and let user select an edition
      ITypedElement target = new JavaTextBufferNode(file, document, inEditor);
      ITypedElement[] editions = buildEditions(target, file);

      ResourceBundle bundle = ResourceBundle.getBundle(BUNDLE_NAME);
      EditionSelectionDialog d = new EditionSelectionDialog(shell, bundle);
      d.setAddMode(true);
      d.setHelpContextId(IJavaHelpContextIds.ADD_ELEMENT_FROM_HISTORY_DIALOG);
      ITypedElement selected = d.selectEdition(target, editions, parent);
      if (selected == null) return; // user cancel

      ICompilationUnit cu2 = cu;
      if (parent instanceof IMember) cu2 = ((IMember) parent).getCompilationUnit();

      CompilationUnit root = parsePartialCompilationUnit(cu2);
      ASTRewrite rewriter = ASTRewrite.create(root.getAST());

      ITypedElement[] results = d.getSelection();
      for (int i = 0; i < results.length; i++) {

        // create an AST node
        ASTNode newNode =
            createASTNode(
                rewriter,
                results[i],
                TextUtilities.getDefaultLineDelimiter(document),
                cu.getJavaProject());
        if (newNode == null) {
          MessageDialog.openError(shell, errorTitle, errorMessage);
          return;
        }

        // now determine where to put the new node
        if (newNode instanceof PackageDeclaration) {
          rewriter.set(root, CompilationUnit.PACKAGE_PROPERTY, newNode, null);

        } else if (newNode instanceof ImportDeclaration) {
          ListRewrite lw = rewriter.getListRewrite(root, CompilationUnit.IMPORTS_PROPERTY);
          lw.insertFirst(newNode, null);

        } else { // class, interface, enum, annotation, method, field

          if (parent instanceof ICompilationUnit) { // top level
            ListRewrite lw = rewriter.getListRewrite(root, CompilationUnit.TYPES_PROPERTY);
            int index = ASTNodes.getInsertionIndex((BodyDeclaration) newNode, root.types());
            lw.insertAt(newNode, index, null);

          } else if (parent instanceof IType) {
            ASTNode declaration = getBodyContainer(root, (IType) parent);
            if (declaration instanceof TypeDeclaration
                || declaration instanceof AnnotationTypeDeclaration) {
              List container = ASTNodes.getBodyDeclarations(declaration);
              int index = ASTNodes.getInsertionIndex((BodyDeclaration) newNode, container);
              ListRewrite lw =
                  rewriter.getListRewrite(
                      declaration, ASTNodes.getBodyDeclarationsProperty(declaration));
              lw.insertAt(newNode, index, null);
            } else if (declaration instanceof EnumDeclaration) {
              List container = ((EnumDeclaration) declaration).enumConstants();
              int index = ASTNodes.getInsertionIndex((FieldDeclaration) newNode, container);
              ListRewrite lw =
                  rewriter.getListRewrite(declaration, EnumDeclaration.ENUM_CONSTANTS_PROPERTY);
              lw.insertAt(newNode, index, null);
            }
          } else {
            JavaPlugin.logErrorMessage(
                "JavaAddElementFromHistoryImpl: unknown container " + parent); // $NON-NLS-1$
          }
        }
      }

      Map options = null;
      IJavaProject javaProject = cu2.getJavaProject();
      if (javaProject != null) options = javaProject.getOptions(true);
      applyChanges(rewriter, document, textFileBuffer, shell, inEditor, options);

    } catch (InvocationTargetException ex) {
      ExceptionHandler.handle(ex, shell, errorTitle, errorMessage);

    } catch (InterruptedException ex) {
      // shouldn't be called because is not cancelable
      Assert.isTrue(false);

    } catch (CoreException ex) {
      ExceptionHandler.handle(ex, shell, errorTitle, errorMessage);

    } finally {
      try {
        if (textFileBuffer != null) bufferManager.disconnect(path, LocationKind.IFILE, null);
      } catch (CoreException e) {
        JavaPlugin.log(e);
      }
    }
  }
 protected static final boolean isStatic(IMember member) throws JavaModelException {
   return Flags.isStatic(member.getFlags());
 }