示例#1
0
 protected void assertConditionsError(RefactoringStatus status, int number) {
   if (number > 0) {
     assertTrue("Error in Condition expected", status.hasError()); // $NON-NLS-1$
   }
   RefactoringStatusEntry[] entries = status.getEntries();
   int count = 0;
   for (RefactoringStatusEntry entry : entries) {
     if (entry.isError()) {
       ++count;
     }
   }
   assertEquals(number + " Errors expected found " + count, number, count); // $NON-NLS-1$
 }
  @Override
  public RefactoringStatus checkInitialConditions(IProgressMonitor pm)
      throws CoreException, OperationCanceledException {
    SubMonitor sm = SubMonitor.convert(pm, 10);

    RefactoringStatus status = super.checkInitialConditions(sm.newChild(6));
    if (status.hasError()) {
      return status;
    }

    if (!initStatus.hasFatalError()) {
      initRefactoring(pm);
      if (context.existingFields.isEmpty()) {
        initStatus.addFatalError(Messages.GenerateGettersAndSettersRefactoring_NoFields);
      }
    }
    return initStatus;
  }
  private void helper1(
      String[] methodNames,
      String[][] signatures,
      boolean deleteAllInSourceType,
      boolean deleteAllMatchingMethods,
      boolean replaceOccurences)
      throws Exception {
    ICompilationUnit cu = createCUfromTestFile(getPackageP(), "A");
    IType type = getType(cu, "B");
    IMethod[] methods = getMethods(type, methodNames, signatures);

    ExtractSupertypeProcessor processor = createRefactoringProcessor(methods);
    Refactoring refactoring = processor.getRefactoring();
    processor.setMembersToMove(methods);

    assertTrue("activation", refactoring.checkInitialConditions(new NullProgressMonitor()).isOK());

    processor.setTypesToExtract(new IType[] {type});
    processor.setTypeName("Z");
    processor.setCreateMethodStubs(true);
    processor.setInstanceOf(false);
    processor.setReplace(replaceOccurences);
    if (deleteAllInSourceType) processor.setDeletedMethods(methods);
    if (deleteAllMatchingMethods)
      processor.setDeletedMethods(
          getMethods(processor.getMatchingElements(new NullProgressMonitor(), false)));

    RefactoringStatus status = refactoring.checkFinalConditions(new NullProgressMonitor());
    assertTrue("precondition was supposed to pass", !status.hasError());
    performChange(refactoring, false);

    String expected = getFileContents(getOutputTestFileName("A"));
    String actual = cu.getSource();
    assertEqualLines(expected, actual);

    expected = getFileContents(getOutputTestFileName("Z"));
    ICompilationUnit unit = getPackageP().getCompilationUnit("Z.java");
    if (!unit.exists()) assertTrue("extracted compilation unit does not exist", false);
    actual = unit.getBuffer().getContents();
    assertEqualLines(expected, actual);
  }
  /**
   * This method analyzes a set of local variable renames inside one cu. It checks whether any new
   * compile errors have been introduced by the rename(s) and whether the correct node(s) has/have
   * been renamed.
   *
   * @param analyzePackages the LocalAnalyzePackages containing the information about the local
   *     renames
   * @param cuChange the TextChange containing all local variable changes to be applied.
   * @param oldCUNode the fully (incl. bindings) resolved AST node of the original compilation unit
   * @param recovery whether statements and bindings recovery should be performed when parsing the
   *     changed CU
   * @return a RefactoringStatus containing errors if compile errors or wrongly renamed nodes are
   *     found
   * @throws CoreException thrown if there was an error greating the preview content of the change
   */
  public static RefactoringStatus analyzeLocalRenames(
      LocalAnalyzePackage[] analyzePackages,
      TextChange cuChange,
      CompilationUnit oldCUNode,
      boolean recovery)
      throws CoreException {

    RefactoringStatus result = new RefactoringStatus();
    ICompilationUnit compilationUnit = (ICompilationUnit) oldCUNode.getJavaElement();

    String newCuSource = cuChange.getPreviewContent(new NullProgressMonitor());
    CompilationUnit newCUNode =
        new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL)
            .parse(newCuSource, compilationUnit, true, recovery, null);

    result.merge(analyzeCompileErrors(newCuSource, newCUNode, oldCUNode));
    if (result.hasError()) return result;

    for (int i = 0; i < analyzePackages.length; i++) {
      ASTNode enclosing =
          getEnclosingBlockOrMethodOrLambda(
              analyzePackages[i].fDeclarationEdit, cuChange, newCUNode);

      // get new declaration
      IRegion newRegion =
          RefactoringAnalyzeUtil.getNewTextRange(analyzePackages[i].fDeclarationEdit, cuChange);
      ASTNode newDeclaration =
          NodeFinder.perform(newCUNode, newRegion.getOffset(), newRegion.getLength());
      Assert.isTrue(newDeclaration instanceof Name);

      VariableDeclaration declaration = getVariableDeclaration((Name) newDeclaration);
      Assert.isNotNull(declaration);

      SimpleName[] problemNodes =
          ProblemNodeFinder.getProblemNodes(
              enclosing, declaration, analyzePackages[i].fOccurenceEdits, cuChange);
      result.merge(RefactoringAnalyzeUtil.reportProblemNodes(newCuSource, problemNodes));
    }
    return result;
  }
  /** Creates a refactoring (or returns a previously created refactoring). */
  public Refactoring createRefactoring() throws RefactoringException {
    if (refactoring != null) {
      return refactoring;
    }

    RefactoringStatus status = new RefactoringStatus();
    D descriptor = createDescriptor();
    try {
      refactoring = descriptor.createRefactoring(status);
    } catch (CoreException e) {
      throw new RefactoringException(e);
    }
    if (refactoring == null) {
      throw new RefactoringException(
          String.format(
              "The refactoring descriptor (%s) was unable to create a refactoring.",
              descriptor.getClass().getSimpleName()));
    }
    if (status.hasError()) {
      throw new RefactoringException(status.getMessageMatchingSeverity(RefactoringStatus.ERROR));
    }

    return refactoring;
  }
  /**
   * Invokes the introduce indirection ref. Some pointers:
   *
   * @param topLevelName This is an array of fully qualified top level(!) type names with exactly
   *     one package prefix (e.g. "p.Foo"). Simple names must correspond to .java files. The first
   *     cu will be used for the invocation of the refactoring (see positioning)
   * @param newName name of indirection method
   * @param qTypeName qualified type name of the type for the indirection method. Should be one of
   *     the cus in topLevelName.
   * @param startLine starting line of selection in topLevelName[0]
   * @param startColumn starting column of selection in topLevelName[0]
   * @param endLine ending line of selection in topLevelName[0]
   * @param endColumn ending column of selection in topLevelName[0]
   * @param updateReferences true if references should be updated
   * @param shouldWarn if true, warnings will be expected in the result
   * @param shouldError if true, errors will be expected in the result
   * @param shouldFail if true, fatal errors will be expected in the result
   * @throws Exception
   * @throws JavaModelException
   * @throws CoreException
   * @throws IOException
   */
  private void helper(
      String[] topLevelName,
      String newName,
      String qTypeName,
      int startLine,
      int startColumn,
      int endLine,
      int endColumn,
      boolean updateReferences,
      boolean shouldWarn,
      boolean shouldError,
      boolean shouldFail)
      throws Exception, JavaModelException, CoreException, IOException {
    ICompilationUnit[] cu = new ICompilationUnit[topLevelName.length];
    for (int i = 0; i < topLevelName.length; i++) {
      String packName = topLevelName[i].substring(0, topLevelName[i].indexOf('.'));
      String className = topLevelName[i].substring(topLevelName[i].indexOf('.') + 1);
      IPackageFragment cPackage = getRoot().createPackageFragment(packName, true, null);
      cu[i] = createCUfromTestFile(cPackage, className);
    }

    ISourceRange selection =
        TextRangeUtil.getSelection(cu[0], startLine, startColumn, endLine, endColumn);
    try {
      IntroduceIndirectionRefactoring ref =
          new IntroduceIndirectionRefactoring(cu[0], selection.getOffset(), selection.getLength());
      ref.setEnableUpdateReferences(updateReferences);
      if (qTypeName != null) ref.setIntermediaryClassName(qTypeName);
      if (newName != null) ref.setIntermediaryMethodName(newName);

      boolean failed = false;
      RefactoringStatus status = performRefactoringWithStatus(ref);
      if (status.hasFatalError()) {
        assertTrue(
            "Failed but shouldn't: " + status.getMessageMatchingSeverity(RefactoringStatus.FATAL),
            shouldFail);
        failed = true;
      } else assertFalse("Didn't fail although expected", shouldFail);

      if (!failed) {

        if (status.hasError())
          assertTrue(
              "Had errors but shouldn't: "
                  + status.getMessageMatchingSeverity(RefactoringStatus.ERROR),
              shouldError);
        else assertFalse("No error although expected", shouldError);

        if (status.hasWarning())
          assertTrue(
              "Had warnings but shouldn't: "
                  + status.getMessageMatchingSeverity(RefactoringStatus.WARNING),
              shouldWarn);
        else assertFalse("No warning although expected", shouldWarn);

        for (int i = 0; i < topLevelName.length; i++) {
          String className = topLevelName[i].substring(topLevelName[i].indexOf('.') + 1);
          assertEqualLines(
              "invalid output.",
              getFileContents(getOutputTestFileName(className)),
              cu[i].getSource());
        }
      }
    } finally {
      for (int i = 0; i < topLevelName.length; i++) JavaProjectHelper.delete(cu[i]);
    }
  }