private void failHelper1(
      int startLine,
      int startColumn,
      int endLine,
      int endColumn,
      boolean makeFinal,
      String className,
      int visibility,
      int expectedSeverity)
      throws Exception {
    ICompilationUnit cu = createCUfromTestFile(getPackageP(), false, true);
    ISourceRange selection =
        TextRangeUtil.getSelection(cu, startLine, startColumn, endLine, endColumn);
    ConvertAnonymousToNestedRefactoring ref =
        new ConvertAnonymousToNestedRefactoring(cu, selection.getOffset(), selection.getLength());

    RefactoringStatus preconditionResult = ref.checkInitialConditions(new NullProgressMonitor());
    if (preconditionResult.isOK()) preconditionResult = null;
    assertEquals("activation was supposed to be successful", null, preconditionResult);

    ref.setClassName(className);
    ref.setDeclareFinal(makeFinal);
    ref.setVisibility(visibility);

    if (preconditionResult == null)
      preconditionResult = ref.checkFinalConditions(new NullProgressMonitor());
    else preconditionResult.merge(ref.checkFinalConditions(new NullProgressMonitor()));
    if (preconditionResult.isOK()) preconditionResult = null;
    assertNotNull("precondition was supposed to fail", preconditionResult);

    assertEquals("incorrect severity:", expectedSeverity, preconditionResult.getSeverity());
  }
  @Override
  public final RefactoringStatus checkNewElementName(String newName) {
    Assert.isNotNull(newName, "new name"); // $NON-NLS-1$

    RefactoringStatus status =
        Checks.checkName(newName, JavaConventionsUtil.validateMethodName(newName, fMethod));
    if (status.isOK() && !Checks.startsWithLowerCase(newName))
      status =
          RefactoringStatus.createWarningStatus(
              fIsComposite
                  ? Messages.format(
                      RefactoringCoreMessages.Checks_method_names_lowercase2,
                      new String[] {
                        BasicElementLabels.getJavaElementName(newName), getDeclaringTypeLabel()
                      })
                  : RefactoringCoreMessages.Checks_method_names_lowercase);

    if (Checks.isAlreadyNamed(fMethod, newName))
      status.addFatalError(
          fIsComposite
              ? Messages.format(
                  RefactoringCoreMessages.RenameMethodRefactoring_same_name2,
                  new String[] {
                    BasicElementLabels.getJavaElementName(newName), getDeclaringTypeLabel()
                  })
              : RefactoringCoreMessages.RenameMethodRefactoring_same_name,
          JavaStatusContext.create(fMethod));
    return status;
  }
예제 #3
0
 @Override
 protected RefactoringStatus checkConditionsAfterNameSetting(IProgressMonitor pm) {
   RefactoringStatus status = new RefactoringStatus();
   ProjectUtil projectUtil = getProjectUtil();
   newFileName = projectUtil.appendFileExtension(info.getNewName());
   NesCComponentNameCollissionDetector detector = new NesCComponentNameCollissionDetector();
   detector.handleCollisions4NewFileName(
       newFileName, declaringIdentifier, declaringFile, getProjectUtil(), status, pm);
   try { // Handle Collisions in affected configurations.
     for (IFile file : affectedIdentifiers.keySet()) {
       if (!declaringFile.equals(file)) { // The component itself cannot reference itself.
         AstAnalyzerFactory factory = new AstAnalyzerFactory(file, projectUtil, pm);
         if (factory
             .hasConfigurationAnalyzerCreated()) { // Only configurations can reference other
                                                   // modules.
           detector.handleCollisions4NewComponentNameWithConfigurationLocalName(
               factory.getConfigurationAnalyzer(),
               file,
               info.getOldName(),
               info.getNewName(),
               status);
         }
       }
     }
   } catch (Exception e) {
     status.addFatalError(
         "Exception during condition checking. See project log for more information.");
     projectUtil.log("Exception during condition checking.", e);
   }
   return status;
 }
  /**
   * @param elements
   * @param expectedInitialStatus
   * @param expectedFinalStatus
   * @return <code>true</code> iff performed
   * @throws CoreException
   */
  private boolean perform(
      IJavaElement[] elements, int expectedInitialStatus, int expectedFinalStatus)
      throws CoreException {
    InferTypeArgumentsRefactoring refactoring =
        ((RefactoringAvailabilityTester.isInferTypeArgumentsAvailable(elements))
            ? new InferTypeArgumentsRefactoring(elements)
            : null);

    NullProgressMonitor pm = new NullProgressMonitor();
    RefactoringStatus initialStatus = refactoring.checkInitialConditions(pm);
    assertEquals(
        "wrong initial condition status: " + initialStatus,
        expectedInitialStatus,
        initialStatus.getSeverity());
    if (!initialStatus.isOK()) return false;

    refactoring.setAssumeCloneReturnsSameType(fAssumeCloneReturnsSameType);
    refactoring.setLeaveUnconstrainedRaw(fLeaveUnconstrainedRaw);

    PerformRefactoringOperation op =
        new PerformRefactoringOperation(refactoring, CheckConditionsOperation.FINAL_CONDITIONS);
    JavaCore.run(op, new NullProgressMonitor());
    RefactoringStatus finalStatus = op.getConditionStatus();
    assertEquals(
        "wrong final condition status: " + finalStatus,
        expectedFinalStatus,
        finalStatus.getSeverity());
    if (finalStatus.getSeverity() == RefactoringStatus.FATAL) return false;

    assertTrue(
        "Validation check failed: " + op.getValidationStatus(),
        !op.getValidationStatus().hasFatalError());
    assertNotNull("No Undo", op.getUndoChange());
    return true;
  }
예제 #5
0
 // ----------
 private RefactoringStatus checkAccessor(
     IProgressMonitor pm, IMethod existingAccessor, String newAccessorName) throws CoreException {
   RefactoringStatus result = new RefactoringStatus();
   result.merge(checkAccessorDeclarations(pm, existingAccessor));
   result.merge(checkNewAccessor(existingAccessor, newAccessorName));
   return result;
 }
 /* (non-Javadoc)
  * @see org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant#checkConditions(org.eclipse.core.runtime.IProgressMonitor, org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext)
  */
 @Override
 public RefactoringStatus checkConditions(IProgressMonitor pm, CheckConditionsContext context)
     throws OperationCanceledException {
   RefactoringStatus result = new RefactoringStatus();
   if (element == null) result.addError("element is null");
   return result;
 }
예제 #7
0
 private RefactoringStatus validate(IProgressMonitor pm, EObject object) {
   RefactoringStatus refactoringStatus = RefactoringStatus.create(Status.OK_STATUS);
   EValidator.Registry validatorRegistry =
       extensions.getInstance(EValidator.Registry.class, object);
   EPackage epackage = object.eClass().getEPackage();
   EValidator validator = validatorRegistry.getEValidator(epackage);
   BasicDiagnostic diagnostics = new BasicDiagnostic();
   if (pm.isCanceled()) {
     refactoringStatus = RefactoringStatus.create(Status.CANCEL_STATUS);
     pm.done();
   } else {
     SubMonitor sm = SubMonitor.convert(pm, "Validating re-factoring.", IProgressMonitor.UNKNOWN);
     validator.validate(object, diagnostics, Maps.newHashMap());
     Iterator<Diagnostic> validationIterator =
         Iterables.filter(
                 diagnostics.getChildren(),
                 new Predicate<Diagnostic>() {
                   @Override
                   public boolean apply(Diagnostic diagnostic) {
                     if (diagnostic instanceof FeatureBasedDiagnostic) {
                       return FeatureBasedDiagnostic.ERROR
                           == ((FeatureBasedDiagnostic) diagnostic).getSeverity();
                     }
                     return false;
                   }
                 })
             .iterator();
     if (validationIterator.hasNext()) {
       Diagnostic diagnostic = validationIterator.next();
       refactoringStatus = RefactoringStatus.createFatalErrorStatus(diagnostic.getMessage());
     }
     sm.done();
   }
   return refactoringStatus;
 }
  protected void ensureProjectHasRefactoringEnabled(RefactoringStatus status)
      throws PreconditionFailure {
    if (FortranCorePlugin.inTestingMode()) return;

    HashSet<IFile> filesToBeRemoved = new HashSet<IFile>();

    for (IFile f : this.selectedFiles) {
      if (!PhotranVPG.getInstance().doesProjectHaveRefactoringEnabled(f)) {
        if (f.getProject() == null) {
          status.addWarning(
              Messages.bind(
                  Messages.FortranResourceRefactoring_FileIsNotInAFortranProject, f.getName()));
          filesToBeRemoved.add(f);
        } else {
          status.addWarning(
              Messages.bind(
                  Messages.FortranResourceRefactoring_AnalysisRefactoringNotEnabled,
                  f.getProject().getName()));
          filesToBeRemoved.add(f);
        }
      }
    }
    // Remove files that didn't have Refactoring enabled in their projects
    this.selectedFiles.removeAll(filesToBeRemoved);
  }
예제 #9
0
 private RefactoringStatus checkAccessorDeclarations(IProgressMonitor pm, IMethod existingAccessor)
     throws CoreException {
   RefactoringStatus result = new RefactoringStatus();
   SearchPattern pattern =
       SearchPattern.createPattern(
           existingAccessor,
           IJavaSearchConstants.DECLARATIONS,
           SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE);
   IJavaSearchScope scope = SearchEngine.createHierarchyScope(fField.getDeclaringType());
   SearchResultGroup[] groupDeclarations =
       RefactoringSearchEngine.search(pattern, scope, pm, result);
   Assert.isTrue(groupDeclarations.length > 0);
   if (groupDeclarations.length != 1) {
     String message =
         Messages.format(
             RefactoringCoreMessages.RenameFieldRefactoring_overridden,
             JavaElementUtil.createMethodSignature(existingAccessor));
     result.addError(message);
   } else {
     SearchResultGroup group = groupDeclarations[0];
     Assert.isTrue(group.getSearchResults().length > 0);
     if (group.getSearchResults().length != 1) {
       String message =
           Messages.format(
               RefactoringCoreMessages.RenameFieldRefactoring_overridden_or_overrides,
               JavaElementUtil.createMethodSignature(existingAccessor));
       result.addError(message);
     }
   }
   return result;
 }
예제 #10
0
  @Override
  public void runTest() throws Throwable {
    REF.IN_TESTS = true;

    IDocument document = new Document(data.source);
    ITextSelection selection =
        new TextSelection(
            document, data.sourceSelection.getOffset(), data.sourceSelection.getLength());
    RefactoringInfo info =
        new RefactoringInfo(
            document,
            selection,
            new IGrammarVersionProvider() {

              public int getGrammarVersion() throws MisconfigurationException {
                return IGrammarVersionProvider.GRAMMAR_PYTHON_VERSION_2_7;
              }
            });
    InlineLocalRefactoring refactoring = new InlineLocalRefactoring(info);

    NullProgressMonitor monitor = new NullProgressMonitor();
    RefactoringStatus result = refactoring.checkAllConditions(monitor);

    assertTrue(
        "Refactoring is not ok: " + result.getMessageMatchingSeverity(RefactoringStatus.WARNING),
        result.isOK());

    Change change = refactoring.createChange(monitor);
    change.perform(monitor);

    assertEquals(data.result, document.get());

    REF.IN_TESTS = false;
  }
 @Override
 public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
   pm.beginTask("", 2); // $NON-NLS-1$
   RefactoringStatus result;
   try {
     result = new RefactoringStatus();
     IJavaElement element = (IJavaElement) getModifiedElement();
     // don't check for read-only since we don't go through
     // validate edit.
     result.merge(super.isValid(new SubProgressMonitor(pm, 1)));
     if (result.hasFatalError()) return result;
     if (element != null && element.exists() && element instanceof IPackageFragment) {
       IPackageFragment pack = (IPackageFragment) element;
       if (fRenameSubpackages) {
         IPackageFragment[] allPackages = JavaElementUtil.getPackageAndSubpackages(pack);
         SubProgressMonitor subPm = new SubProgressMonitor(pm, 1);
         subPm.beginTask("", allPackages.length); // $NON-NLS-1$
         for (int i = 0; i < allPackages.length; i++) {
           // don't check for read-only since we don't go through
           // validate edit.
           checkIfModifiable(result, allPackages[i].getResource(), VALIDATE_NOT_DIRTY);
           if (result.hasFatalError()) return result;
           isValid(result, allPackages[i], new SubProgressMonitor(subPm, 1));
         }
       } else {
         isValid(result, pack, new SubProgressMonitor(pm, 1));
       }
     }
   } finally {
     pm.done();
   }
   return result;
 }
예제 #12
0
 /** Checks if created method will shadow or will be shadowed by other elements. */
 private RefactoringStatus checkPossibleConflicts(IProgressMonitor pm) throws CoreException {
   List<SearchMatch> references = Lists.newArrayList();
   // top-level function
   if (parentMember.getParent() instanceof DartUnit) {
     RefactoringStatus conflictsStatus =
         RenameTopLevelProcessor.analyzePossibleConflicts(
             unit.getLibrary(), DartElement.FUNCTION, false, references, methodName);
     if (!conflictsStatus.isOK()) {
       return convertRenameToCreateStatus(conflictsStatus);
     }
   }
   // method of class
   if (parentMember.getParent() instanceof DartClass) {
     ClassElement enclosingClassElement = (ClassElement) parentMember.getParent().getElement();
     Type enclosingType = (Type) BindingUtils.getDartElement(enclosingClassElement);
     RefactoringStatus conflictsStatus =
         RenameTypeMemberProcessor.analyzePossibleConflicts(
             DartElement.FUNCTION, enclosingType, methodName, references, methodName, pm);
     if (!conflictsStatus.isOK()) {
       return convertRenameToCreateStatus(conflictsStatus);
     }
   }
   // OK
   return new RefactoringStatus();
 }
  private void performRefactoringAndUndo(
      String varName,
      String packName,
      String cuName,
      String initialContents,
      String finalContents,
      int start,
      int length)
      throws Exception {
    ICompilationUnit unit = createUnit(packName, cuName, initialContents);
    ExtractTempRefactoring temp = new ExtractTempRefactoring(unit, start, length);
    temp.setTempName(varName);
    RefactoringStatus result = performRefactoring(temp, true, false);

    result = ignoreKnownErrors(result);

    assertTrue("Refactoring produced an error: " + result, result.isOK());

    assertContents(unit, finalContents);

    // undo
    assertTrue("anythingToUndo", RefactoringCore.getUndoManager().anythingToUndo());
    assertTrue("! anythingToRedo", !RefactoringCore.getUndoManager().anythingToRedo());

    RefactoringCore.getUndoManager().performUndo(null, new NullProgressMonitor());
    assertContents(unit, initialContents);

    // redo
    assertTrue("! anythingToUndo", !RefactoringCore.getUndoManager().anythingToUndo());
    assertTrue("anythingToRedo", RefactoringCore.getUndoManager().anythingToRedo());
    RefactoringCore.getUndoManager().performRedo(null, new NullProgressMonitor());
    assertContents(unit, finalContents);
  }
예제 #14
0
  @Override
  public RefactoringStatus checkInitialConditions(IProgressMonitor pm)
      throws CoreException, OperationCanceledException {
    RefactoringStatus status = new RefactoringStatus();

    try {
      pm.beginTask("Checking preconditions...", 6);

      if (mSelectionStart == -1 || mSelectionEnd == -1) {
        status.addFatalError("No selection to convert");
        return status;
      }

      // Make sure the selection is contiguous
      if (mTreeSelection != null) {
        List<CanvasViewInfo> infos = getSelectedViewInfos();
        if (!validateNotEmpty(infos, status)) {
          return status;
        }
      }

      // Ensures that we have a valid DOM model:
      if (mElements.size() == 0) {
        status.addFatalError("Nothing to convert");
        return status;
      }

      pm.worked(1);
      return status;

    } finally {
      pm.done();
    }
  }
예제 #15
0
 private static void checkHierarchyOfEnclosedTypes(
     IType destinationType, RefactoringStatus result, IType type) throws JavaModelException {
   IType[] enclosedTypes = getAllEnclosedTypes(type);
   for (int i = 0; i < enclosedTypes.length; i++) {
     IType enclosedType = enclosedTypes[i];
     if (destinationType.getElementName().equals(enclosedType.getElementName())) {
       String message =
           Messages.format(
               RefactoringCoreMessages.MemberCheckUtil_type_name_conflict3,
               new String[] {getQualifiedLabel(enclosedType), getQualifiedLabel(type)});
       RefactoringStatusContext context =
           JavaStatusContext.create(
               destinationType.getCompilationUnit(), destinationType.getNameRange());
       result.addError(message, context);
     }
     if (typeNameExistsInEnclosingTypeChain(destinationType, enclosedType.getElementName())) {
       String message =
           Messages.format(
               RefactoringCoreMessages.MemberCheckUtil_type_name_conflict4,
               new String[] {getQualifiedLabel(enclosedType), getQualifiedLabel(type)});
       RefactoringStatusContext context =
           JavaStatusContext.create(
               destinationType.getCompilationUnit(), destinationType.getNameRange());
       result.addError(message, context);
     }
   }
 }
  public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
    try {
      pm.beginTask("", 7); // $NON-NLS-1$

      RefactoringStatus result = Checks.validateEdit(fCu, getValidationContext());
      if (result.hasFatalError()) return result;
      pm.worked(1);

      if (fCuRewrite == null) {
        JavaScriptUnit cuNode =
            RefactoringASTParser.parseWithASTProvider(fCu, true, new SubProgressMonitor(pm, 3));
        fCuRewrite = new CompilationUnitRewrite(fCu, cuNode);
      } else {
        pm.worked(3);
      }
      result.merge(checkSelection(new SubProgressMonitor(pm, 3)));

      if (result.hasFatalError()) return result;

      if (isLiteralNodeSelected()) fReplaceAllOccurrences = false;

      return result;
    } finally {
      pm.done();
    }
  }
 /*
  * @see org.eclipse.jdt.internal.ui.text.correction.proposals.CUCorrectionProposal#getAdditionalProposalInfo(org.eclipse.core.runtime.IProgressMonitor)
  * @since 3.6
  */
 @Override
 public Object getAdditionalProposalInfo(IProgressMonitor monitor) {
   if (fRefactoringStatus != null && fRefactoringStatus.hasFatalError()) {
     return fRefactoringStatus.getEntryWithHighestSeverity().getMessage();
   }
   return super.getAdditionalProposalInfo(monitor);
 }
예제 #18
0
  /**
   * Final check before the actual refactoring
   *
   * @return status
   * @throws OperationCanceledException
   */
  public RefactoringStatus checkFinalConditions() throws OperationCanceledException {
    RefactoringStatus status = new RefactoringStatus();
    IContainer destination = fProcessor.getDestination();
    IProject sourceProject = fProcessor.getSourceSelection()[0].getProject();
    IProject destinationProject = destination.getProject();
    if (sourceProject != destinationProject)
      status.merge(MoveUtils.checkMove(phpFiles, sourceProject, destination));

    // Checks if one of the resources already exists with the same name in
    // the destination
    IPath dest = fProcessor.getDestination().getFullPath();
    IResource[] sourceResources = fProcessor.getSourceSelection();

    for (IResource element : sourceResources) {
      String newFilePath = dest.toOSString() + File.separatorChar + element.getName();
      IResource resource =
          ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(newFilePath));
      if (resource != null && resource.exists()) {
        status.merge(
            RefactoringStatus.createFatalErrorStatus(
                NLS.bind(
                    PhpRefactoringCoreMessages.getString("MoveDelegate.6"),
                    element.getName(),
                    dest.toOSString()))); // $NON-NLS-1$
      }
    }
    return status;
  }
예제 #19
0
 private static void checkMethodInType(
     IType destinationType, RefactoringStatus result, IMethod method) throws JavaModelException {
   IMethod[] destinationTypeMethods = destinationType.getMethods();
   IMethod found = findMethod(method, destinationTypeMethods);
   if (found != null) {
     RefactoringStatusContext context =
         JavaStatusContext.create(destinationType.getCompilationUnit(), found.getSourceRange());
     String message =
         Messages.format(
             RefactoringCoreMessages.MemberCheckUtil_signature_exists,
             new String[] {
               BasicElementLabels.getJavaElementName(method.getElementName()),
               getQualifiedLabel(destinationType)
             });
     result.addError(message, context);
   } else {
     IMethod similar = Checks.findMethod(method, destinationType);
     if (similar != null) {
       String message =
           Messages.format(
               RefactoringCoreMessages.MemberCheckUtil_same_param_count,
               new String[] {
                 BasicElementLabels.getJavaElementName(method.getElementName()),
                 getQualifiedLabel(destinationType)
               });
       RefactoringStatusContext context =
           JavaStatusContext.create(
               destinationType.getCompilationUnit(), similar.getSourceRange());
       result.addWarning(message, context);
     }
   }
 }
 @Override
 public void replayRefactoring(RefactoringDescriptor refactoringDescriptor) throws CoreException {
   try {
     // FIXME: This is a temporary hack. It is required to overcome the problem that sometimes
     // Eclipse does not finish updating
     // program's structure yet, and thus, the refactoring can not be properly initialized (i.e.
     // the refactored element is not found).
     // Find a better solution, e.g. listen for some Eclipse "refreshing" process to complete.
     Thread.sleep(1500);
   } catch (InterruptedException e) {
     // do nothing
   }
   RefactoringStatus initializationStatus = new RefactoringStatus();
   Refactoring refactoring = refactoringDescriptor.createRefactoring(initializationStatus);
   if (!initializationStatus.isOK()) {
     Debugger.debugWarning(
         "Failed to initialize a refactoring from its descriptor: " + refactoringDescriptor);
     unperformedRefactorings.add(getTime());
     return;
   }
   // This remove is needed to ensure that multiple replays in the same run do not overlap
   unperformedRefactorings.remove(getTime());
   PerformRefactoringOperation performRefactoringOperation =
       new PerformRefactoringOperation(refactoring, CheckConditionsOperation.ALL_CONDITIONS);
   performRefactoringOperation.run(null);
   if (performRefactoringOperation.getConditionStatus().hasFatalError()) {
     throw new RuntimeException(
         "Failed to check preconditions of refactoring: " + refactoring.getName());
   }
   if (performRefactoringOperation.getValidationStatus().hasFatalError()) {
     throw new RuntimeException("Failed to validate refactoring: " + refactoring.getName());
   }
 }
예제 #21
0
파일: PyChange.java 프로젝트: httpdss/Pydev
 // protected final RefactoringStatus isValid(IProgressMonitor pm, boolean checkReadOnly, boolean
 // checkDirty) throws CoreException {
 protected final RefactoringStatus isValid(IProgressMonitor pm, int flags) throws CoreException {
   pm.beginTask("", 2); // $NON-NLS-1$
   try {
     RefactoringStatus result = new RefactoringStatus();
     Object modifiedElement = getModifiedElement();
     checkExistence(result, modifiedElement);
     if (result.hasFatalError()) return result;
     if (flags == NONE) return result;
     IResource resource = getResource(modifiedElement);
     if (resource != null) {
       ValidationState state = new ValidationState(resource);
       state.checkModificationStamp(result, fModificationStamp);
       if (result.hasFatalError()) return result;
       state.checkSameReadOnly(result, fReadOnly);
       if (result.hasFatalError()) return result;
       if ((flags & READ_ONLY) != 0) {
         state.checkReadOnly(result);
         if (result.hasFatalError()) return result;
       }
       if ((flags & DIRTY) != 0) {
         if ((flags & SAVE) != 0) {
           state.checkDirty(result, fModificationStamp, new SubProgressMonitor(pm, 1));
         } else {
           state.checkDirty(result);
         }
       }
     }
     return result;
   } finally {
     pm.done();
   }
 }
 private RefactoringStatus checkExpressionFragmentIsRValue() throws JavaModelException {
   /* Moved this functionality to Checks, to allow sharing with
   ExtractTempRefactoring, others */
   switch (Checks.checkExpressionIsRValue(getSelectedExpression().getAssociatedExpression())) {
     case Checks.NOT_RVALUE_MISC:
       return RefactoringStatus.createStatus(
           RefactoringStatus.FATAL,
           RefactoringCoreMessages.ExtractConstantRefactoring_select_expression,
           null,
           Corext.getPluginId(),
           RefactoringStatusCodes.EXPRESSION_NOT_RVALUE,
           null);
     case Checks.NOT_RVALUE_VOID:
       return RefactoringStatus.createStatus(
           RefactoringStatus.FATAL,
           RefactoringCoreMessages.ExtractConstantRefactoring_no_void,
           null,
           Corext.getPluginId(),
           RefactoringStatusCodes.EXPRESSION_NOT_RVALUE_VOID,
           null);
     case Checks.IS_RVALUE_GUESSED:
     case Checks.IS_RVALUE:
       return new RefactoringStatus();
     default:
       Assert.isTrue(false);
       return null;
   }
 }
 protected final Refactoring createRefactoring(RefactoringDescriptor descriptor)
     throws CoreException {
   RefactoringStatus status = new RefactoringStatus();
   Refactoring refactoring = descriptor.createRefactoring(status);
   assertNotNull("refactoring should not be null", refactoring);
   assertTrue("status should be ok", status.isOK());
   return refactoring;
 }
예제 #24
0
 protected void assertConditionsOk(RefactoringStatus conditions) {
   assertTrue(
       conditions.isOK()
           ? "OK"
           : "Error or Warning in Conditions: "
               + conditions.getEntries()[0].getMessage(), // $NON-NLS-1$ //$NON-NLS-2$
       conditions.isOK());
 }
 protected void createPerformCheckRefactoring(final JavaRefactoringDescriptor descriptor)
     throws CoreException, Exception {
   final RefactoringStatus status = new RefactoringStatus();
   final Refactoring refactoring = descriptor.createRefactoring(status);
   assertTrue("status should be ok", status.isOK());
   assertNotNull("refactoring should not be null", refactoring);
   assertEquals("was supposed to pass", null, performRefactoring(refactoring));
 }
예제 #26
0
  /*
   * (non java-doc)
   * Analyzes all compilation units in which type is referenced
   */
  private RefactoringStatus analyzeAffectedCompilationUnits() throws CoreException {
    RefactoringStatus result = new RefactoringStatus();
    fReferences = Checks.excludeCompilationUnits(fReferences, result);
    if (result.hasFatalError()) return result;

    result.merge(Checks.checkCompileErrorsInAffectedFiles(fReferences));
    return result;
  }
  @Override
  public RefactoringStatus checkInitialConditions(final IProgressMonitor monitor)
      throws CoreException {
    final SubMonitor progress = SubMonitor.convert(monitor, 6);
    try {
      if (fSelectionRegion != null) {
        fSourceUnit.connect(progress.newChild(1));
        try {
          final AbstractDocument document = fSourceUnit.getDocument(monitor);

          final IRModelInfo modelInfo =
              (IRModelInfo)
                  fSourceUnit.getModelInfo(
                      RModel.TYPE_ID, IRModelManager.MODEL_FILE, progress.newChild(1));
          if (modelInfo != null) {
            final IRegion region = fAdapter.trimToAstRegion(document, fSelectionRegion);
            ISourceStructElement element =
                LTKUtil.getCoveringSourceElement(modelInfo.getSourceElement(), region);
            while (element != null) {
              if (element instanceof IRMethod) {
                fFunction = (IRMethod) element;
                break;
              }
              element = element.getSourceParent();
            }
          }

          if (fFunction != null) {
            final ISourceStructElement source = (ISourceStructElement) fFunction;
            fOperationRegion =
                fAdapter.expandSelectionRegion(document, source.getSourceRange(), fSelectionRegion);
          }
        } finally {
          fSourceUnit.disconnect(progress.newChild(1));
        }
      }

      if (fFunction == null) {
        return RefactoringStatus.createFatalErrorStatus(
            Messages.FunctionToS4Method_error_InvalidSelection_message);
      }
      final RefactoringStatus result = new RefactoringStatus();
      fAdapter.checkInitialForModification(result, fElementSet);
      progress.worked(1);

      if (result.hasFatalError()) {
        return result;
      }

      checkFunction(result);
      progress.worked(2);
      return result;
    } finally {
      progress.done();
    }
  }
 private RefactoringStatus validateMethodName() {
   RefactoringStatus result = new RefactoringStatus();
   String text = getText();
   if ("".equals(text)) { // $NON-NLS-1$
     result.addFatalError(RefactoringMessages.ExtractMethodInputPage_validation_emptyMethodName);
     return result;
   }
   result.merge(fRefactoring.checkMethodName());
   return result;
 }
예제 #29
0
파일: PyChange.java 프로젝트: httpdss/Pydev
  protected static void checkExistence(RefactoringStatus status, Object element) {
    if (element == null) {
      status.addFatalError("Workspace Changed");

    } else if (element instanceof IResource && !((IResource) element).exists()) {
      status.addFatalError(
          StringUtils.format(
              "Resource %s does not exist", ((IResource) element).getFullPath().toString()));
    }
  }
예제 #30
0
 public void test_toLTK_Throwable() throws Exception {
   Throwable e = new Throwable("msg");
   org.eclipse.ltk.core.refactoring.RefactoringStatus ltkStatus = ServiceUtils.toLTK(e);
   org.eclipse.ltk.core.refactoring.RefactoringStatusEntry[] ltkEntries = ltkStatus.getEntries();
   assertThat(ltkEntries).hasSize(1);
   // entry[0]
   assertEquals("msg", ltkEntries[0].getMessage());
   assertEquals(
       org.eclipse.ltk.core.refactoring.RefactoringStatus.FATAL, ltkEntries[0].getSeverity());
 }