public void testListenerNotifiedOnExternalChanges() {
    addDefaultLibrary();
    myFixture.configureByFiles("/content/anno/p/annotations.xml");
    myFixture.configureByFiles("lib/p/Test.java");

    ExternalAnnotationsManager.getInstance(myProject)
        .findExternalAnnotation(getOwner(), AnnotationUtil.NOT_NULL); // force creating service

    startListeningForExternalChanges();
    new WriteCommandAction(myProject) {
      @Override
      protected void run(final Result result) throws Throwable {
        VirtualFile file =
            LocalFileSystem.getInstance()
                .findFileByPath(myFixture.getTempDirPath() + "/content/anno/p/annotations.xml");
        assert file != null;
        String newText =
            "  "
                + StreamUtil.readText(file.getInputStream())
                + "      "; // adding newspace to the beginning and end of file
        FileUtil.writeToFile(
            VfsUtil.virtualToIoFile(file),
            newText); // writing using java.io.File to make this change external
        file.refresh(false, false);
      }
    }.execute();
    stopListeningAndCheckEvents();
  }
  private void doDeannotate(@NonNls final String testPath, String hint1, String hint2)
      throws Throwable {
    myFixture.configureByFile(testPath);
    final PsiFile file = myFixture.getFile();
    final Editor editor = myFixture.getEditor();

    assertNotAvailable(hint1);
    assertNotAvailable(hint2);

    final DeannotateIntentionAction deannotateFix = new DeannotateIntentionAction();
    assertTrue(deannotateFix.isAvailable(myProject, editor, file));

    final PsiModifierListOwner container = DeannotateIntentionAction.getContainer(editor, file);
    startListening(container, AnnotationUtil.NOT_NULL, true);
    new WriteCommandAction(myProject) {
      @Override
      protected void run(final Result result) throws Throwable {
        ExternalAnnotationsManager.getInstance(myProject)
            .deannotate(container, AnnotationUtil.NOT_NULL);
      }
    }.execute();
    stopListeningAndCheckEvents();

    FileDocumentManager.getInstance().saveAllDocuments();

    IntentionAction fix = myFixture.findSingleIntention(hint1);
    assertNotNull(fix);

    fix = myFixture.findSingleIntention(hint2);
    assertNotNull(fix);

    assertFalse(deannotateFix.isAvailable(myProject, editor, file));
  }
  public void testListenerNotifiedWhenOperationsFail() {
    addLibrary(); // no annotation roots: all operations should fail
    myFixture.configureByFiles("lib/p/Test.java");
    final PsiMethod method = ((PsiJavaFile) myFixture.getFile()).getClasses()[0].getMethods()[0];

    startListening(method, AnnotationUtil.NOT_NULL, false);
    new WriteCommandAction(myProject) {
      @Override
      protected void run(final Result result) throws Throwable {
        ExternalAnnotationsManager.getInstance(myProject)
            .annotateExternally(method, AnnotationUtil.NOT_NULL, myFixture.getFile(), null);
      }
    }.execute();
    stopListeningAndCheckEvents();

    startListening(method, AnnotationUtil.NOT_NULL, false);
    new WriteCommandAction(myProject) {
      @Override
      protected void run(final Result result) throws Throwable {
        ExternalAnnotationsManager.getInstance(myProject)
            .editExternalAnnotation(method, AnnotationUtil.NOT_NULL, null);
      }
    }.execute();
    stopListeningAndCheckEvents();

    startListening(method, AnnotationUtil.NOT_NULL, false);
    new WriteCommandAction(myProject) {
      @Override
      protected void run(final Result result) throws Throwable {
        ExternalAnnotationsManager.getInstance(myProject)
            .deannotate(method, AnnotationUtil.NOT_NULL);
      }
    }.execute();
    stopListeningAndCheckEvents();
  }
  public void testAnnotated() throws Throwable {
    PsiFile psiFile = myFixture.configureByFile("lib/p/TestAnnotated.java");
    PsiTestUtil.addSourceRoot(myModule, psiFile.getVirtualFile().getParent());
    final PsiFile file = myFixture.getFile();
    final Editor editor = myFixture.getEditor();
    assertNotAvailable("Annotate method 'get' as @NotNull");
    assertNotAvailable("Annotate method 'get' as @Nullable");

    final DeannotateIntentionAction deannotateFix = new DeannotateIntentionAction();
    assertFalse(deannotateFix.isAvailable(myProject, editor, file));
  }
 public void testDeannotation1() throws Throwable {
   addDefaultLibrary();
   myFixture.configureByFiles("lib/p/TestPrimitive.java", "content/anno/p/annotations.xml");
   doDeannotate(
       "lib/p/TestDeannotation1.java",
       "Annotate parameter 'ss' as @NotNull",
       "Annotate parameter 'ss' as @Nullable");
   myFixture.checkResultByFile(
       "content/anno/p/annotations.xml",
       "content/anno/p/annotationsDeannotation1_after.xml",
       false);
 }
  public void testEditingMultiRootAnnotations() {
    addLibrary("/content/annoMultiRoot/root1", "/content/annoMultiRoot/root2");
    myFixture.configureByFiles(
        "/content/annoMultiRoot/root1/multiRoot/annotations.xml",
        "/content/annoMultiRoot/root2/multiRoot/annotations.xml");
    myFixture.configureByFiles("lib/multiRoot/Test.java");

    final ExternalAnnotationsManager manager = ExternalAnnotationsManager.getInstance(myProject);
    final PsiMethod method = ((PsiJavaFile) myFixture.getFile()).getClasses()[0].getMethods()[0];
    final PsiParameter parameter = method.getParameterList().getParameters()[0];

    assertMethodAndParameterAnnotationsValues(manager, method, parameter, "\"foo\"");

    final PsiAnnotation annotationFromText =
        JavaPsiFacade.getElementFactory(myProject)
            .createAnnotationFromText("@Annotation(value=\"bar\")", null);

    startListening(method, AnnotationUtil.NULLABLE, true);
    new WriteCommandAction(myProject) {
      @Override
      protected void run(final Result result) throws Throwable {
        manager.editExternalAnnotation(
            method, AnnotationUtil.NULLABLE, annotationFromText.getParameterList().getAttributes());
      }
    }.execute();
    stopListeningAndCheckEvents();

    startListening(parameter, AnnotationUtil.NOT_NULL, true);
    new WriteCommandAction(myProject) {
      @Override
      protected void run(final Result result) throws Throwable {
        manager.editExternalAnnotation(
            parameter,
            AnnotationUtil.NOT_NULL,
            annotationFromText.getParameterList().getAttributes());
      }
    }.execute();
    stopListeningAndCheckEvents();

    assertMethodAndParameterAnnotationsValues(manager, method, parameter, "\"bar\"");

    myFixture.checkResultByFile(
        "content/annoMultiRoot/root1/multiRoot/annotations.xml",
        "content/annoMultiRoot/root1/multiRoot/annotations_after.xml",
        false);
    myFixture.checkResultByFile(
        "content/annoMultiRoot/root2/multiRoot/annotations.xml",
        "content/annoMultiRoot/root2/multiRoot/annotations_after.xml",
        false);
  }
  @NotNull
  private static String getPresentableElementPosition(
      @NotNull final CodeInsightTestFixture fixture, final @Nullable PsiElement element) {
    if (element == null) return "";

    final StringBuilder buf = new StringBuilder(element.getText());
    DartComponent component = PsiTreeUtil.getParentOfType(element, DartComponent.class);
    while (component != null) {
      final DartComponentName componentName = component.getComponentName();
      if (componentName != null && componentName != element) {
        buf.insert(0, component.getName() + " -> ");
      }
      component = PsiTreeUtil.getParentOfType(component, DartComponent.class);
    }
    String path =
        element instanceof PsiDirectoryImpl
            ? ((PsiDirectoryImpl) element).getVirtualFile().getPath()
            : element.getContainingFile().getVirtualFile().getPath();

    final String contentRoot =
        ModuleRootManager.getInstance(fixture.getModule()).getContentRoots()[0].getPath();
    if (path.equals(contentRoot)) path = "[content root]";

    final String contentRootWithSlash = contentRoot + "/";
    if (path.startsWith(contentRootWithSlash)) path = path.substring(contentRootWithSlash.length());

    final DartSdk sdk = DartSdk.getDartSdk(element.getProject());
    if (sdk != null && path.startsWith(sdk.getHomePath()))
      path = "[Dart SDK]" + path.substring(sdk.getHomePath().length());

    if (buf.length() > 0) buf.insert(0, " -> ");
    buf.insert(0, path);

    return buf.toString();
  }
  @Override
  protected void tearDown() throws Exception {
    myFixture.tearDown();
    myFixture = null;

    super.tearDown();
  }
  public static void doTest(@NotNull final CodeInsightTestFixture fixture) {
    final List<CaretPositionInfo> caretPositions =
        DartTestUtils.extractPositionMarkers(
            fixture.getProject(), fixture.getEditor().getDocument());

    fixture.doHighlighting();

    for (CaretPositionInfo caretPositionInfo : caretPositions) {
      final int line =
          fixture.getEditor().getDocument().getLineNumber(caretPositionInfo.caretOffset);
      final int column =
          caretPositionInfo.caretOffset
              - fixture.getEditor().getDocument().getLineStartOffset(line);
      final String fileNameAndPosition =
          fixture.getFile().getName() + ":" + (line + 1) + ":" + (column + 1);

      final PsiReference reference =
          TargetElementUtil.findReference(fixture.getEditor(), caretPositionInfo.caretOffset);
      assertNotNull("No reference in " + fileNameAndPosition, reference);

      final PsiElement resolve = reference.resolve();
      final String actualElementPosition = getPresentableElementPosition(fixture, resolve);
      assertEquals(
          "Incorrect resolution for reference in " + fileNameAndPosition,
          caretPositionInfo.expected,
          actualElementPosition);
    }
  }
  @Override
  public void setUp() throws Exception {
    super.setUp();
    final TestFixtureBuilder<IdeaProjectTestFixture> projectBuilder =
        IdeaTestFixtureFactory.getFixtureFactory().createFixtureBuilder(getName());

    myFixture =
        JavaTestFixtureFactory.getFixtureFactory()
            .createCodeInsightFixture(projectBuilder.getFixture());
    final String dataPath = PathManagerEx.getTestDataPath() + "/codeInsight/externalAnnotations";
    myFixture.setTestDataPath(dataPath);
    final JavaModuleFixtureBuilder builder =
        projectBuilder.addModule(JavaModuleFixtureBuilder.class);
    builder.setMockJdkLevel(JavaModuleFixtureBuilder.MockJdkLevel.jdk15);

    myFixture.setUp();
    myModule = builder.getFixture().getModule();
    myProject = myFixture.getProject();
  }
  @Override
  protected void setUp() throws Exception {
    super.setUp();
    final IdeaTestFixtureFactory fixtureFactory = IdeaTestFixtureFactory.getFixtureFactory();
    final TestFixtureBuilder<IdeaProjectTestFixture> builder =
        fixtureFactory.createFixtureBuilder(getName());

    myFixture = fixtureFactory.createCodeInsightFixture(builder.getFixture());
    myFixture.setTestDataPath(getTestDataPath());
    myFixture.setUp();

    final Project project = myFixture.getProject();

    new WriteCommandAction(project) {
      @Override
      protected void run(Result result) throws Throwable {
        FileTypeManager.getInstance()
            .registerFileType(RegExpFileType.INSTANCE, new String[] {"regexp"});
      }
    }.execute();
  }
  @Override
  protected void tearDown() throws Exception {
    try {
      myFixture.tearDown();
    } finally {
      myFixture = null;
      myModule = null;
      myProject = null;

      super.tearDown();
      assertNull(myBusConnection);
    }
  }
  public static void doTest(
      @NotNull final CodeInsightTestFixture fixture, @NotNull final String text) {
    PsiFile file = fixture.getFile();
    if (file == null) {
      file = fixture.addFileToProject("file.dart", text);
      fixture.openFileInEditor(file.getVirtualFile());
    } else {
      final Document document =
          FileDocumentManager.getInstance().getDocument(file.getVirtualFile());
      assert document != null;
      ApplicationManager.getApplication()
          .runWriteAction(
              new Runnable() {
                @Override
                public void run() {
                  document.setText(text);
                }
              });
    }

    doTest(fixture);
  }
  @Override
  protected void setUp() throws Exception {
    super.setUp();

    final IdeaTestFixtureFactory factory = IdeaTestFixtureFactory.getFixtureFactory();
    final TestFixtureBuilder<IdeaProjectTestFixture> fixtureBuilder =
        factory.createLightFixtureBuilder(getProjectDescriptor());

    final IdeaProjectTestFixture fixture = fixtureBuilder.getFixture();
    final LightTempDirTestFixtureImpl tempDirTestFixture = new LightTempDirTestFixtureImpl(true);
    myFixture =
        IdeaTestFixtureFactory.getFixtureFactory()
            .createCodeInsightFixture(fixture, tempDirTestFixture);
    myFixture.setUp();

    setupFixtureWhenInitialized();
  }
  public void testAnnotateLibrary() throws Throwable {

    addDefaultLibrary();
    myFixture.configureByFiles("lib/p/TestPrimitive.java", "content/anno/p/annotations.xml");
    myFixture.configureByFiles("lib/p/Test.java");
    final PsiFile file = myFixture.getFile();
    final Editor editor = myFixture.getEditor();

    final IntentionAction fix = myFixture.findSingleIntention("Annotate method 'get' as @NotNull");
    assertTrue(fix.isAvailable(myProject, editor, file));

    // expecting other @Nullable annotations to be removed, and default @NotNull to be added
    List<Trinity<PsiModifierListOwner, String, Boolean>> expectedSequence =
        new ArrayList<Trinity<PsiModifierListOwner, String, Boolean>>();
    for (String notNull : NullableNotNullManager.getInstance(myProject).getNullables()) {
      expectedSequence.add(Trinity.create(getOwner(), notNull, false));
    }
    expectedSequence.add(Trinity.create(getOwner(), AnnotationUtil.NOT_NULL, true));
    startListening(expectedSequence);
    new WriteCommandAction(myProject) {
      @Override
      protected void run(final Result result) throws Throwable {
        fix.invoke(myProject, editor, file);
      }
    }.execute();

    FileDocumentManager.getInstance().saveAllDocuments();

    final PsiElement psiElement = file.findElementAt(editor.getCaretModel().getOffset());
    assertNotNull(psiElement);
    final PsiModifierListOwner listOwner =
        PsiTreeUtil.getParentOfType(psiElement, PsiModifierListOwner.class);
    assertNotNull(listOwner);
    assertNotNull(
        ExternalAnnotationsManager.getInstance(myProject)
            .findExternalAnnotation(listOwner, AnnotationUtil.NOT_NULL));
    stopListeningAndCheckEvents();

    myFixture.checkResultByFile(
        "content/anno/p/annotations.xml",
        "content/anno/p/annotationsAnnotateLibrary_after.xml",
        false);
  }
 @NotNull
 private PsiModifierListOwner getOwner() {
   return ObjectUtils.assertNotNull(
       AddAnnotationPsiFix.getContainer(myFixture.getFile(), myFixture.getCaretOffset()));
 }
  public void testPrimitive() throws Throwable {
    PsiFile psiFile = myFixture.configureByFile("lib/p/TestPrimitive.java");
    PsiTestUtil.addSourceRoot(myModule, psiFile.getVirtualFile().getParent());

    assertNotAvailable("Annotate method 'get' as @NotNull");
  }
 private void assertNotAvailable(String hint) {
   List<IntentionAction> actions = myFixture.filterAvailableIntentions(hint);
   assertEmpty(actions);
 }
 public static PsiMethodCallExpressionExtractor createExpressionExtractor(
     CodeInsightTestFixture fixture) {
   Caret currentCaret = getCaret(fixture);
   return ExtractorFactory.createMethodCallExpressionExtractor(
       fixture.getFile(), currentCaret.getSelectionStart(), currentCaret.getSelectionEnd());
 }
 private static Caret getCaret(CodeInsightTestFixture fixture) {
   Caret currentCaret = fixture.getEditor().getCaretModel().getCurrentCaret();
   if (currentCaret.getSelectionStart() == 0 && currentCaret.getSelectionEnd() == 0)
     TestCase.fail("No valid caret found in test file");
   return currentCaret;
 }
 protected void createAndAddFile(final String relativePath, final String text) throws IOException {
   final PsiFile psiFile = myFixture.addFileToProject(relativePath, text);
   myFixture.configureFromExistingVirtualFile(psiFile.getVirtualFile());
 }
 protected Project getProject() {
   return myFixture.getProject();
 }