public void testExtractInterfaceFromInterface2() throws Exception {
    String className = "A";
    String extendingInterfaceName = "I1";
    String newInterfaceName = "B";

    IType clas =
        getType(createCUfromTestFile(getPackageP(), getTopLevelTypeName(className)), className);
    ICompilationUnit cu = clas.getCompilationUnit();
    IPackageFragment pack = (IPackageFragment) cu.getParent();

    getType(
        createCUfromTestFile(getPackageP(), getTopLevelTypeName(extendingInterfaceName)),
        extendingInterfaceName);

    IPackageFragmentRoot root = RefactoringTestSetup.getDefaultSourceFolder();
    assertNotNull(root);
    IPackageFragment p2 = root.createPackageFragment("p2", true, null);
    getType(createCUfromTestFile(p2, getTopLevelTypeName("I2")), "I2");

    ExtractInterfaceProcessor processor =
        new ExtractInterfaceProcessor(
            clas, JavaPreferencesSettings.getCodeGenerationSettings(clas.getJavaProject()));
    Refactoring ref = new ProcessorBasedRefactoring(processor);

    processor.setTypeName(newInterfaceName);
    assertEquals(
        "interface name should be accepted",
        RefactoringStatus.OK,
        processor.checkTypeName(newInterfaceName).getSeverity());

    IMember[] extractableMembers = processor.getExtractableMembers();
    final IMember[] members = new IMember[extractableMembers.length - 1];
    List<IMember> list = new ArrayList<>();
    for (IMember iMember : extractableMembers) {
      if (!(iMember instanceof IField)) {
        list.add(iMember);
      }
    }
    processor.setExtractedMembers(list.toArray(members));
    processor.setReplace(true);
    processor.setAnnotations(false);
    RefactoringStatus performRefactoring = performRefactoring(ref);
    assertEquals("was supposed to pass", null, performRefactoring);
    assertEqualLines(
        "incorrect changes in " + className,
        getFileContents(getOutputTestFileName(className)),
        cu.getSource());

    ICompilationUnit interfaceCu = pack.getCompilationUnit(newInterfaceName + ".java");
    assertEqualLines(
        "incorrect interface created",
        getFileContents(getOutputTestFileName(newInterfaceName)),
        interfaceCu.getSource());
  }
 @Override
 public void run(RefactoringRequest request) throws Exception {
   CodeGenerationSettings settings =
       JavaPreferencesSettings.getCodeGenerationSettings(
           request.getCompilationUnit().getJavaProject());
   settings.createComments = false;
   // TODO: Add functionality: which classes to extract, etc
   ExtractClassContribution contribution = new ExtractClassContribution();
   ExtractClassDescriptor descriptor = (ExtractClassDescriptor) contribution.createDescriptor();
   ExtractClassRefactoring refactor = new ExtractClassRefactoring(descriptor);
   RefactoringUtils.performRefactoring(refactor);
 }
 private static ExtractSupertypeProcessor createRefactoringProcessor(IMember[] members)
     throws JavaModelException {
   IJavaProject project = null;
   if (members != null && members.length > 0) project = members[0].getJavaProject();
   if (RefactoringAvailabilityTester.isExtractSupertypeAvailable(members)) {
     final CodeGenerationSettings settings =
         JavaPreferencesSettings.getCodeGenerationSettings(project);
     settings.createComments = false;
     ExtractSupertypeProcessor processor = new ExtractSupertypeProcessor(members, settings);
     new ProcessorBasedRefactoring(processor);
     return processor;
   }
   return null;
 }
  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);
  }
  private void createConstantDeclaration() throws CoreException {
    Type type = getConstantType();

    IExpressionFragment fragment = getSelectedExpression();
    Expression initializer =
        getSelectedExpression().createCopyTarget(fCuRewrite.getASTRewrite(), true);

    AST ast = fCuRewrite.getAST();
    VariableDeclarationFragment variableDeclarationFragment = ast.newVariableDeclarationFragment();
    variableDeclarationFragment.setName(ast.newSimpleName(fConstantName));
    variableDeclarationFragment.setInitializer(initializer);

    FieldDeclaration fieldDeclaration = ast.newFieldDeclaration(variableDeclarationFragment);
    fieldDeclaration.setType(type);
    Modifier.ModifierKeyword accessModifier = Modifier.ModifierKeyword.toKeyword(fVisibility);
    if (accessModifier != null) fieldDeclaration.modifiers().add(ast.newModifier(accessModifier));
    fieldDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD));
    fieldDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.FINAL_KEYWORD));

    boolean createComments =
        JavaPreferencesSettings.getCodeGenerationSettings(fCu.getJavaProject()).createComments;
    if (createComments) {
      String comment =
          CodeGeneration.getFieldComment(
              fCu, getConstantTypeName(), fConstantName, StubUtility.getLineDelimiterUsed(fCu));
      if (comment != null && comment.length() > 0) {
        Javadoc doc =
            (Javadoc) fCuRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC);
        fieldDeclaration.setJavadoc(doc);
      }
    }

    AbstractTypeDeclaration parent = getContainingTypeDeclarationNode();
    ListRewrite listRewrite =
        fCuRewrite.getASTRewrite().getListRewrite(parent, parent.getBodyDeclarationsProperty());
    TextEditGroup msg =
        fCuRewrite.createGroupDescription(
            RefactoringCoreMessages.ExtractConstantRefactoring_declare_constant);
    if (insertFirst()) {
      listRewrite.insertFirst(fieldDeclaration, msg);
    } else {
      listRewrite.insertAfter(fieldDeclaration, getNodeToInsertConstantDeclarationAfter(), msg);
    }

    if (fLinkedProposalModel != null) {
      ASTRewrite rewrite = fCuRewrite.getASTRewrite();
      LinkedProposalPositionGroup nameGroup = fLinkedProposalModel.getPositionGroup(KEY_NAME, true);
      nameGroup.addPosition(rewrite.track(variableDeclarationFragment.getName()), true);

      String[] nameSuggestions = guessConstantNames();
      if (nameSuggestions.length > 0 && !nameSuggestions[0].equals(fConstantName)) {
        nameGroup.addProposal(fConstantName, null, nameSuggestions.length + 1);
      }
      for (int i = 0; i < nameSuggestions.length; i++) {
        nameGroup.addProposal(nameSuggestions[i], null, nameSuggestions.length - i);
      }

      LinkedProposalPositionGroup typeGroup = fLinkedProposalModel.getPositionGroup(KEY_TYPE, true);
      typeGroup.addPosition(rewrite.track(type), true);

      ITypeBinding typeBinding = guessBindingForReference(fragment.getAssociatedExpression());
      if (typeBinding != null) {
        ITypeBinding[] relaxingTypes = ASTResolving.getNarrowingTypes(ast, typeBinding);
        for (int i = 0; i < relaxingTypes.length; i++) {
          typeGroup.addProposal(relaxingTypes[i], fCuRewrite.getCu(), relaxingTypes.length - i);
        }
      }
      boolean isInterface =
          parent.resolveBinding() != null && parent.resolveBinding().isInterface();
      ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(
          fLinkedProposalModel, rewrite, fieldDeclaration.modifiers(), isInterface);
    }
  }
  /**
   * Note: This method is for internal use only. Clients should not call this method.
   *
   * @param cu The compilation unit to process
   */
  public void run(ICompilationUnit cu) {
    if (!ElementValidator.check(
        cu, getShell(), ActionMessages.OrganizeImportsAction_error_title, fEditor != null)) return;
    if (!ActionUtil.isProcessable(getShell(), cu)) return;

    IEditingSupport helper = createViewerHelper();
    try {
      CodeGenerationSettings settings =
          JavaPreferencesSettings.getCodeGenerationSettings(cu.getJavaProject());

      if (fEditor == null && EditorUtility.isOpenInEditor(cu) == null) {
        IEditorPart editor = EditorUtility.openInEditor(cu);
        if (editor instanceof JavaEditor) {
          fEditor = (JavaEditor) editor;
        }
      }

      CompilationUnit astRoot =
          JavaPlugin.getDefault().getASTProvider().getAST(cu, ASTProvider.WAIT_ACTIVE_ONLY, null);

      AJOrganizeImportsOperation op =
          new AJOrganizeImportsOperation(
              cu,
              astRoot,
              settings.importIgnoreLowercase,
              !cu.isWorkingCopy(),
              true,
              createChooseImportQuery());

      IRewriteTarget target = null;
      if (fEditor != null) {
        target = (IRewriteTarget) fEditor.getAdapter(IRewriteTarget.class);
        if (target != null) {
          target.beginCompoundChange();
        }
      }

      IProgressService progressService = PlatformUI.getWorkbench().getProgressService();
      IRunnableContext context = getSite().getWorkbenchWindow();
      if (context == null) {
        context = progressService;
      }
      try {
        registerHelper(helper);
        progressService.runInUI(
            context, new WorkbenchRunnableAdapter(op, op.getScheduleRule()), op.getScheduleRule());
        IProblem parseError = op.getParseError();
        if (parseError != null) {
          String message =
              Messages.format(
                  ActionMessages.OrganizeImportsAction_single_error_parse, parseError.getMessage());
          MessageDialog.openInformation(
              getShell(), ActionMessages.OrganizeImportsAction_error_title, message);
          if (fEditor != null && parseError.getSourceStart() != -1) {
            fEditor.selectAndReveal(
                parseError.getSourceStart(),
                parseError.getSourceEnd() - parseError.getSourceStart() + 1);
          }
        } else {
          if (fEditor != null) {
            setStatusBarMessage(getOrganizeInfo(op));
          }
        }
      } catch (InvocationTargetException e) {
        ExceptionHandler.handle(
            e,
            getShell(),
            ActionMessages.OrganizeImportsAction_error_title,
            ActionMessages.OrganizeImportsAction_error_message);
      } catch (InterruptedException e) {
      } finally {
        deregisterHelper(helper);
        if (target != null) {
          target.endCompoundChange();
        }
      }
    } catch (CoreException e) {
      ExceptionHandler.handle(
          e,
          getShell(),
          ActionMessages.OrganizeImportsAction_error_title,
          ActionMessages.OrganizeImportsAction_error_message);
    }
  }
  private void doRunOnMultiple(ICompilationUnit[] cus, MultiStatus status, IProgressMonitor monitor)
      throws OperationCanceledException {
    if (monitor == null) {
      monitor = new NullProgressMonitor();
    }
    monitor.setTaskName("Organizing imports...");

    monitor.beginTask("", cus.length); // $NON-NLS-1$
    try {
      IChooseImportQuery query =
          new IChooseImportQuery() {
            public TypeNameMatch[] chooseImports(
                TypeNameMatch[][] openChoices, ISourceRange[] ranges) {
              throw new OrganizeImportError();
            }
          };
      IJavaProject lastProject = null;

      for (int i = 0; i < cus.length; i++) {
        ICompilationUnit cu = cus[i];
        if (testOnBuildPath(cu, status)) {
          if (lastProject == null || !lastProject.equals(cu.getJavaProject())) {
            lastProject = cu.getJavaProject();
          }
          CodeGenerationSettings settings =
              JavaPreferencesSettings.getCodeGenerationSettings(lastProject);

          String cuLocation = cu.getPath().makeRelative().toString();

          monitor.subTask(cuLocation);

          try {
            boolean save = !cu.isWorkingCopy();
            if (!save) {
              ITextFileBuffer textFileBuffer =
                  FileBuffers.getTextFileBufferManager().getTextFileBuffer(cu.getPath());
              save = textFileBuffer != null && !textFileBuffer.isDirty(); // save when not dirty
            }

            AJOrganizeImportsOperation op =
                new AJOrganizeImportsOperation(
                    cu, null, settings.importIgnoreLowercase, save, true, query);
            runInSync(op, cuLocation, status, monitor);

            IProblem parseError = op.getParseError();
            if (parseError != null) {
              String message =
                  Messages.format(
                      ActionMessages.OrganizeImportsAction_multi_error_parse, cuLocation);
              status.add(new Status(IStatus.INFO, JavaUI.ID_PLUGIN, IStatus.ERROR, message, null));
            }
          } catch (CoreException e) {
            JavaPlugin.log(e);
            String message =
                Messages.format(
                    "{0}: Unexpected error. See log for details.", e.getStatus().getMessage());
            status.add(new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IStatus.ERROR, message, null));
          }

          if (monitor.isCanceled()) {
            throw new OperationCanceledException();
          }
        }
      }
    } finally {
      monitor.done();
    }
  }