Exemplo n.º 1
0
  public void testSearchNotRunIfViewDeactivated() throws PartInitException, JavaModelException {
    view = (ActiveSearchView) JavaPlugin.getActivePage().showView(ActiveSearchView.ID);
    for (AbstractRelationProvider provider :
        ContextCorePlugin.getDefault().getRelationProviders()) {
      assertTrue(provider.getCurrentDegreeOfSeparation() > 0);
    }
    IViewPart viewPart = JavaPlugin.getActivePage().showView("org.eclipse.ui.views.ProblemView");

    // XXX e4.0 IPerspectiveDescriptor API has changed
    //		IPerspectiveDescriptor perspective = ((WorkbenchPage)
    // JavaPlugin.getActivePage()).getPerspective();
    IViewReference reference = JavaPlugin.getActivePage().findViewReference(ActiveSearchView.ID);
    assertNotNull(reference);
    //		assertTrue(perspective.canCloseView(view));
    //		assertTrue(perspective.hideView(reference));
    JavaPlugin.getActivePage().hideView(viewPart);

    for (AbstractRelationProvider provider :
        ContextCorePlugin.getDefault().getRelationProviders()) {
      assertFalse(provider.isEnabled());
    }

    JavaPlugin.getActivePage().showView(ActiveSearchView.ID);
    for (AbstractRelationProvider provider :
        ContextCorePlugin.getDefault().getRelationProviders()) {
      assertTrue(provider.isEnabled());
    }
  }
  /**
   * Utility method to inspect a selection to find a Java element.
   *
   * @param selection the selection to be inspected
   * @return a Java element to be used as the initial selection, or <code>null</code>, if no Java
   *     element exists in the given selection
   */
  protected IJavaElement getInitialJavaElement(IStructuredSelection selection) {
    IJavaElement jelem = null;
    if (selection != null && !selection.isEmpty()) {
      Object selectedElement = selection.getFirstElement();
      if (selectedElement instanceof IAdaptable) {
        IAdaptable adaptable = (IAdaptable) selectedElement;

        jelem = adaptable.getAdapter(IJavaElement.class);
        if (jelem == null || !jelem.exists()) {
          jelem = null;
          IResource resource = adaptable.getAdapter(IResource.class);
          if (resource != null && resource.getType() != IResource.ROOT) {
            while (jelem == null && resource.getType() != IResource.PROJECT) {
              resource = resource.getParent();
              jelem = resource.getAdapter(IJavaElement.class);
            }
            if (jelem == null) {
              jelem = JavaCore.create(resource); // java project
            }
          }
        }
      }
    }
    if (jelem == null) {
      IWorkbenchPart part = JavaPlugin.getActivePage().getActivePart();
      if (part instanceof ContentOutline) {
        part = JavaPlugin.getActivePage().getActiveEditor();
      }

      if (part instanceof IViewPartInputProvider) {
        Object elem = ((IViewPartInputProvider) part).getViewPartInput();
        if (elem instanceof IJavaElement) {
          jelem = (IJavaElement) elem;
        }
      }
    }

    if (jelem == null || jelem.getElementType() == IJavaElement.JAVA_MODEL) {
      try {
        IJavaProject[] projects = JavaCore.create(getWorkspaceRoot()).getJavaProjects();
        if (projects.length == 1) {
          IClasspathEntry[] rawClasspath = projects[0].getRawClasspath();
          for (int i = 0; i < rawClasspath.length; i++) {
            if (rawClasspath[i].getEntryKind()
                == IClasspathEntry.CPE_SOURCE) { // add only if the project contains a source folder
              jelem = projects[0];
              break;
            }
          }
        }
      } catch (JavaModelException e) {
        JavaPlugin.log(e);
      }
    }
    return jelem;
  }
  /**
   * Assert NO proposals on the primitive leaf type of an array type.
   *
   * @throws Exception
   */
  public void testAnnotateParameter_ArrayOfPrimitive() throws Exception {

    String X_PATH = "pack/age/X";
    String[] pathAndContents =
        new String[] {
          X_PATH + ".java",
          "package pack.age;\n"
              + "import java.util.List;\n"
              + "public interface X {\n"
              + "    public String test(int[] ints, List<String> list);\n"
              + "}\n"
        };
    addLibrary(
        fJProject1,
        "lib.jar",
        "lib.zip",
        pathAndContents,
        ANNOTATION_PATH,
        JavaCore.VERSION_1_8,
        null);
    IType type = fJProject1.findType(X_PATH.replace('/', '.'));
    JavaEditor javaEditor = (JavaEditor) JavaUI.openInEditor(type);

    try {
      int offset = pathAndContents[1].indexOf("int[]");

      List<ICompletionProposal> list = collectAnnotateProposals(javaEditor, offset);

      assertNumberOfProposals(list, 0);
    } finally {
      JavaPlugin.getActivePage().closeAllEditors(false);
    }
  }
Exemplo n.º 4
0
  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()));
  }
Exemplo n.º 5
0
  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());
    }
  }
Exemplo n.º 6
0
  public JavaEditor openJavaEditor(IJavaElement javaElement) {
    IEditorPart part = EditorUtility.isOpenInEditor(javaElement);
    if (part == null) {
      try {
        part = JavaUI.openInEditor(javaElement);
      } catch (PartInitException e) {
        // ignore
      } catch (JavaModelException e) {
        // ignore
      }
    }

    IWorkbenchPage page = JavaPlugin.getActivePage();
    if (page != null && part != null) {
      page.bringToTop(part);
    }
    if (part != null) {
      part.setFocus();
    }
    if (part instanceof JavaEditor) {
      return (JavaEditor) part;
    }

    return null;
  }
  private IProgressMonitor getProgressMonitor() {
    IWorkbenchPage wbPage = JavaPlugin.getActivePage();
    if (wbPage == null) return null;

    IEditorPart editor = wbPage.getActiveEditor();
    if (editor == null) return null;

    return editor.getEditorSite().getActionBars().getStatusLineManager().getProgressMonitor();
  }
 /**
  * Returns the text selection of the current editor. <code>null</code> is returned when the
  * current editor does not have focus or does not return a text selection.
  *
  * @return Returns the text selection of the current editor or <code>null</code>.
  * @since 3.0
  */
 protected ITextSelection getCurrentTextSelection() {
   IWorkbenchPart part = JavaPlugin.getActivePage().getActivePart();
   if (part instanceof IEditorPart) {
     ISelectionProvider selectionProvider = part.getSite().getSelectionProvider();
     if (selectionProvider != null) {
       ISelection selection = selectionProvider.getSelection();
       if (selection instanceof ITextSelection) {
         return (ITextSelection) selection;
       }
     }
   }
   return null;
 }
Exemplo n.º 9
0
  /**
   * 將所要變更的內容寫回Edit中 (New)
   *
   * @param msg
   */
  protected void applyChange(ASTRewrite rewrite) {
    try {
      // 參考org.eclipse.jdt.internal.ui.text.correction.CorrectionMarkerResolutionGenerator run
      // org.eclipse.jdt.internal.ui.text.correction.ChangeCorrectionProposal apply與performChange
      ICompilationUnit cu = (ICompilationUnit) actOpenable;
      IEditorPart part = EditorUtility.isOpenInEditor(cu);
      IEditorInput input = part.getEditorInput();
      IDocument doc =
          JavaPlugin.getDefault().getCompilationUnitDocumentProvider().getDocument(input);

      performChange(JavaPlugin.getActivePage().getActiveEditor(), doc, rewrite);
    } catch (CoreException e) {
      logger.error("[Core Exception] EXCEPTION ", e);
    }
  }
  // similar to
  // org.eclipse.jdt.internal.ui.text.correction.ModifierCorrectionSubProcessor.removeOverrideAnnotationProposal(..)
  public void removeDeprecatedAnnotation(
      IDocument document, ICompilationUnit cu, BodyDeclaration decl) {
    Annotation annot = findAnnotation(decl.modifiers());
    if (annot != null) {
      ASTRewrite rewrite = ASTRewrite.create(annot.getAST());
      rewrite.remove(annot, null);

      callASTRewriteCorrectionProposal(getDisplayString(), cu, rewrite, 6, getImage(), document);

      ITextViewer viewer = getViewer(JavaPlugin.getActivePage().getActiveEditor());
      ITrackedNodePosition trackPos = rewrite.track(decl);
      if (trackPos != null && viewer != null) {
        viewer.setSelectedRange(trackPos.getStartPosition(), 0);
      }
    }
  }
 /**
  * Returns whether the Smart Insert Mode is selected.
  *
  * @return <code>true</code> if the Smart Insert Mode is selected
  * @since 3.7
  */
 private boolean isSmartInsertMode() {
   IWorkbenchPage page = JavaPlugin.getActivePage();
   if (page != null) {
     IEditorPart part = page.getActiveEditor();
     if (part instanceof ITextEditorExtension3) {
       ITextEditorExtension3 extension = (ITextEditorExtension3) part;
       return extension.getInsertMode() == ITextEditorExtension3.SMART_INSERT;
     } else if (part != null && EditorUtility.isCompareEditorInput(part.getEditorInput())) {
       ITextEditorExtension3 extension =
           (ITextEditorExtension3) part.getAdapter(ITextEditorExtension3.class);
       if (extension != null)
         return extension.getInsertMode() == ITextEditorExtension3.SMART_INSERT;
     }
   }
   return false;
 }
 protected void openResource(final IFile resource) {
   final IWorkbenchPage activePage = JavaPlugin.getActivePage();
   if (activePage != null) {
     final Display display = getShell().getDisplay();
     if (display != null) {
       display.asyncExec(
           new Runnable() {
             public void run() {
               try {
                 IDE.openEditor(activePage, resource, true);
               } catch (PartInitException e) {
                 JavaPlugin.log(e);
               }
             }
           });
     }
   }
 }
Exemplo n.º 13
0
  /**
   * Assert two proposals ("@NonNull" and "@Nullable") on a complex field type (list of array) Apply
   * the second proposal and check the effect.
   *
   * @throws Exception
   */
  public void testAnnotateField1() throws Exception {

    String NODE_PATH = "pack/age/Node";
    String[] pathAndContents =
        new String[] {
          NODE_PATH + ".java",
          "package pack.age;\n"
              + "import java.util.List;\n"
              + "public class Node {\n"
              + "    List<Object[]> value;\n"
              + "}\n"
        };
    addLibrary(
        fJProject1,
        "lib.jar",
        "lib.zip",
        pathAndContents,
        ANNOTATION_PATH,
        JavaCore.VERSION_1_5,
        null);
    IType type = fJProject1.findType(NODE_PATH.replace('/', '.'));
    JavaEditor javaEditor = (JavaEditor) JavaUI.openInEditor(type);

    try {
      int offset = pathAndContents[1].indexOf("[]> value");

      List<ICompletionProposal> list = collectAnnotateProposals(javaEditor, offset);

      assertCorrectLabels(list);
      assertNumberOfProposals(list, 2);

      ICompletionProposal proposal = findProposalByName("Annotate as 'Object @NonNull []'", list);
      String expectedInfo =
          "<dl><dt>value</dt>"
              + "<dd>Ljava/util/List&lt;[Ljava/lang/Object;&gt;;</dd>"
              + "<dd>Ljava/util/List&lt;[<b>1</b>Ljava/lang/Object;&gt;;</dd>"
              + // <= 1
              "</dl>";
      assertEquals("expect detail", expectedInfo, proposal.getAdditionalProposalInfo());

      proposal = findProposalByName("Annotate as 'Object @Nullable []'", list);
      expectedInfo =
          "<dl><dt>value</dt>"
              + "<dd>Ljava/util/List&lt;[Ljava/lang/Object;&gt;;</dd>"
              + "<dd>Ljava/util/List&lt;[<b>0</b>Ljava/lang/Object;&gt;;</dd>"
              + // <= 0
              "</dl>";
      assertEquals("expect detail", expectedInfo, proposal.getAdditionalProposalInfo());

      IDocument document =
          javaEditor.getDocumentProvider().getDocument(javaEditor.getEditorInput());
      proposal.apply(document);

      IFile annotationFile =
          fJProject1.getProject().getFile(new Path(ANNOTATION_PATH).append(NODE_PATH + ".eea"));
      assertTrue("Annotation file should have been created", annotationFile.exists());

      String expectedContent =
          "class pack/age/Node\n"
              + "value\n"
              + " Ljava/util/List<[Ljava/lang/Object;>;\n"
              + " Ljava/util/List<[0Ljava/lang/Object;>;\n";
      checkContentOfFile("annotation file content", annotationFile, expectedContent);
    } finally {
      JavaPlugin.getActivePage().closeAllEditors(false);
    }
  }
Exemplo n.º 14
0
  // FIXME(stephan): enable once implemented
  public void _testAnnotateParameter_TypeParameter() throws Exception {

    String X_PATH = "pack/age/X";
    String[] pathAndContents =
        new String[] {
          X_PATH + ".java",
          "package pack.age;\n"
              + "import java.util.List;\n"
              + "public interface X {\n"
              + "    public <X, T extends List<X>> X test(T list);\n"
              + "}\n"
        };
    addLibrary(
        fJProject1,
        "lib.jar",
        "lib.zip",
        pathAndContents,
        ANNOTATION_PATH,
        JavaCore.VERSION_1_8,
        null);

    IType type = fJProject1.findType(X_PATH.replace('/', '.'));
    JavaEditor javaEditor = (JavaEditor) JavaUI.openInEditor(type);

    try {
      int offset = pathAndContents[1].indexOf("T extends");

      List<ICompletionProposal> list = collectAnnotateProposals(javaEditor, offset);

      assertCorrectLabels(list);
      assertNumberOfProposals(list, 2);

      ICompletionProposal proposal = findProposalByName("Annotate as '@NonNull T'", list);
      String expectedInfo =
          "<dl><dt>test</dt>"
              + "<dd>&lt;X:Ljava/lang/Object;T:Ljava/util/List&lt;TX;&gt;&gt;(TT;)TX;</dd>"
              + "<dd>&lt;X:Ljava/lang/Object;1T:Ljava/util/List&lt;TX;&gt;&gt;(TT;)TX;</dd>"
              + // <= 1
              "</dl>";
      assertEquals("expect detail", expectedInfo, proposal.getAdditionalProposalInfo());

      proposal = findProposalByName("Annotate as '@Nullable Number'", list);
      expectedInfo =
          "<dl><dt>test</dt>"
              + "<dd>&lt;X:Ljava/lang/Object;T:Ljava/util/List&lt;TX;&gt;&gt;(TT;)TX;</dd>"
              + "<dd>&lt;X:Ljava/lang/Object;0T:Ljava/util/List&lt;TX;&gt;&gt;(TT;)TX;</dd>"
              + // <= 0
              "</dl>";
      assertEquals("expect detail", expectedInfo, proposal.getAdditionalProposalInfo());

      IDocument document =
          javaEditor.getDocumentProvider().getDocument(javaEditor.getEditorInput());
      proposal.apply(document);

      IFile annotationFile =
          fJProject1.getProject().getFile(new Path(ANNOTATION_PATH).append(X_PATH + ".eea"));
      assertTrue("Annotation file should have been created", annotationFile.exists());

      String expectedContent =
          "class pack/age/X\n"
              + "test\n"
              + " <X:Ljava/lang/Object;T:Ljava/util/List<;TX;>>(TT;)TX;\n"
              + " <X:Ljava/lang/Object;0T:Ljava/util/List<;TX;>>(TT;)TX;\n";
      checkContentOfFile("annotation file content", annotationFile, expectedContent);
    } finally {
      JavaPlugin.getActivePage().closeAllEditors(false);
    }
  }
Exemplo n.º 15
0
  /**
   * Assert two proposals ("@NonNull" and "@Nullable") on the array representing the varargs
   * ellipsis An entry with annotation on the inner array already exists and will be amended. Apply
   * the second proposal and check the effect.
   *
   * <p>Cf. {@link AnnotateAssistTest18#testAnnotateParameter_Varargs1()}
   *
   * @throws Exception
   */
  public void testAnnotateParameter_Varargs2() throws Exception {

    String X_PATH = "pack/age/X";
    String[] pathAndContents =
        new String[] {
          X_PATH + ".java",
          "package pack.age;\n"
              + "import java.util.List;\n"
              + "public interface X {\n"
              + "    public String test(List<String> list, int[] ... ints);\n"
              + "}\n"
        };
    addLibrary(
        fJProject1,
        "lib.jar",
        "lib.zip",
        pathAndContents,
        ANNOTATION_PATH,
        JavaCore.VERSION_1_8,
        null);

    IFile annotationFile =
        fJProject1.getProject().getFile(new Path(ANNOTATION_PATH).append(X_PATH + ".eea"));
    String initialContent =
        "class pack/age/X\n"
            + "test\n"
            + " (Ljava/util/List<Ljava/lang/String;>;[[I)Ljava/lang/String;\n"
            + " (Ljava/util/List<Ljava/lang/String;>;[[1I)Ljava/lang/String;\n";
    ensureExists(annotationFile.getParent());
    annotationFile.create(new ByteArrayInputStream(initialContent.getBytes("UTF-8")), 0, null);

    IType type = fJProject1.findType(X_PATH.replace('/', '.'));
    JavaEditor javaEditor = (JavaEditor) JavaUI.openInEditor(type);

    try {
      int offset = pathAndContents[1].indexOf("...");

      List<ICompletionProposal> list = collectAnnotateProposals(javaEditor, offset);

      assertCorrectLabels(list);
      assertNumberOfProposals(list, 2);

      ICompletionProposal proposal = findProposalByName("Annotate as 'int[] @NonNull ...'", list);
      String expectedInfo =
          "<dl><dt>test</dt>"
              + "<dd>(Ljava/util/List&lt;Ljava/lang/String;&gt;;[[I)Ljava/lang/String;</dd>"
              + "<dd>(Ljava/util/List&lt;Ljava/lang/String;&gt;;[<b>1</b>[1I)Ljava/lang/String;</dd>"
              + // <= 1
              "</dl>";
      assertEquals("expect detail", expectedInfo, proposal.getAdditionalProposalInfo());

      proposal = findProposalByName("Annotate as 'int[] @Nullable ...'", list);
      expectedInfo =
          "<dl><dt>test</dt>"
              + "<dd>(Ljava/util/List&lt;Ljava/lang/String;&gt;;[[I)Ljava/lang/String;</dd>"
              + "<dd>(Ljava/util/List&lt;Ljava/lang/String;&gt;;[<b>0</b>[1I)Ljava/lang/String;</dd>"
              + // <= 0
              "</dl>";
      assertEquals("expect detail", expectedInfo, proposal.getAdditionalProposalInfo());

      IDocument document =
          javaEditor.getDocumentProvider().getDocument(javaEditor.getEditorInput());
      proposal.apply(document);

      annotationFile =
          fJProject1.getProject().getFile(new Path(ANNOTATION_PATH).append(X_PATH + ".eea"));
      assertTrue("Annotation file should have been created", annotationFile.exists());

      String expectedContent =
          "class pack/age/X\n"
              + "test\n"
              + " (Ljava/util/List<Ljava/lang/String;>;[[I)Ljava/lang/String;\n"
              + " (Ljava/util/List<Ljava/lang/String;>;[0[1I)Ljava/lang/String;\n";
      checkContentOfFile("annotation file content", annotationFile, expectedContent);
    } finally {
      JavaPlugin.getActivePage().closeAllEditors(false);
    }
  }
Exemplo n.º 16
0
 /**
  * Returns the currently active java editor, or <code>null</code> if it cannot be determined.
  *
  * @return the currently active java editor, or <code>null</code>
  */
 private JavaEditor getJavaEditor() {
   IEditorPart part = JavaPlugin.getActivePage().getActiveEditor();
   if (part instanceof JavaEditor) return (JavaEditor) part;
   else return null;
 }