/**
   * @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;
  }
Exemple #2
0
  private SearchResultGroup[] getNewReferences(
      IProgressMonitor pm,
      RefactoringStatus status,
      WorkingCopyOwner owner,
      ICompilationUnit[] newWorkingCopies)
      throws CoreException {
    pm.beginTask("", 2); // $NON-NLS-1$
    ICompilationUnit declaringCuWorkingCopy =
        RenameAnalyzeUtil.findWorkingCopyForCu(newWorkingCopies, fField.getCompilationUnit());
    if (declaringCuWorkingCopy == null) return new SearchResultGroup[0];

    IField field = getFieldInWorkingCopy(declaringCuWorkingCopy, getNewElementName());
    if (field == null || !field.exists()) return new SearchResultGroup[0];

    CollectingSearchRequestor requestor = null;
    if (fDelegateUpdating
        && RefactoringAvailabilityTester.isDelegateCreationAvailable(getField())) {
      // There will be two new matches inside the delegate (the invocation
      // and the javadoc) which are OK and must not be reported.
      final IField oldField =
          getFieldInWorkingCopy(declaringCuWorkingCopy, getCurrentElementName());
      requestor =
          new CollectingSearchRequestor() {
            public void acceptSearchMatch(SearchMatch match) throws CoreException {
              if (!oldField.equals(match.getElement())) super.acceptSearchMatch(match);
            }
          };
    } else requestor = new CollectingSearchRequestor();

    SearchPattern newPattern = SearchPattern.createPattern(field, IJavaSearchConstants.REFERENCES);
    IJavaSearchScope scope = RefactoringScopeFactory.create(fField, true, true);
    return RefactoringSearchEngine.search(
        newPattern, owner, scope, requestor, new SubProgressMonitor(pm, 1), status);
  }
 /**
  * Note: This method is for internal use only. Clients should not call this method.
  *
  * @param selection the java text selection
  * @noreference This method is not intended to be referenced by clients.
  */
 @Override
 public void selectionChanged(JavaTextSelection selection) {
   try {
     setEnabled(RefactoringAvailabilityTester.isGeneralizeTypeAvailable(selection));
   } catch (JavaModelException e) {
     setEnabled(false);
   }
 }
 @Override
 public void selectionChanged(IStructuredSelection selection) {
   try {
     setEnabled(RefactoringAvailabilityTester.isGeneralizeTypeAvailable(selection));
   } catch (JavaModelException e) {
     if (JavaModelUtil.isExceptionToBeLogged(e)) JavaPlugin.log(e);
     setEnabled(false);
   }
 }
Exemple #5
0
 /**
  * Returns the maximum number of delegates which can be created for the input elements of this
  * refactoring.
  *
  * @return maximum number of delegates
  */
 public int getDelegateCount() {
   int count = 0;
   try {
     if (RefactoringAvailabilityTester.isDelegateCreationAvailable(getField())) count++;
     if (fRenameGetter && getGetter() != null) count++;
     if (fRenameSetter && getSetter() != null) count++;
   } catch (CoreException e) {
     // no-op
   }
   return count;
 }
Exemple #6
0
  private RefactoringStatus addDelegates() throws JavaModelException, CoreException {

    RefactoringStatus status = new RefactoringStatus();
    CompilationUnitRewrite rewrite = new CompilationUnitRewrite(fField.getCompilationUnit());
    rewrite.setResolveBindings(true);

    // add delegate for the field
    if (RefactoringAvailabilityTester.isDelegateCreationAvailable(fField)) {
      FieldDeclaration fieldDeclaration =
          ASTNodeSearchUtil.getFieldDeclarationNode(fField, rewrite.getRoot());
      if (fieldDeclaration.fragments().size() > 1) {
        status.addWarning(
            Messages.format(
                RefactoringCoreMessages
                    .DelegateCreator_cannot_create_field_delegate_more_than_one_fragment,
                BasicElementLabels.getJavaElementName(fField.getElementName())),
            JavaStatusContext.create(fField));
      } else if (((VariableDeclarationFragment) fieldDeclaration.fragments().get(0))
              .getInitializer()
          == null) {
        status.addWarning(
            Messages.format(
                RefactoringCoreMessages.DelegateCreator_cannot_create_field_delegate_no_initializer,
                BasicElementLabels.getJavaElementName(fField.getElementName())),
            JavaStatusContext.create(fField));
      } else {
        DelegateFieldCreator creator = new DelegateFieldCreator();
        creator.setDeclareDeprecated(fDelegateDeprecation);
        creator.setDeclaration(fieldDeclaration);
        creator.setNewElementName(getNewElementName());
        creator.setSourceRewrite(rewrite);
        creator.prepareDelegate();
        creator.createEdit();
      }
    }

    // add delegates for getter and setter methods
    // there may be getters even if the field is static final
    if (getGetter() != null && fRenameGetter)
      addMethodDelegate(getGetter(), getNewGetterName(), rewrite);
    if (getSetter() != null && fRenameSetter)
      addMethodDelegate(getSetter(), getNewSetterName(), rewrite);

    final CompilationUnitChange change = rewrite.createChange(true);
    if (change != null) {
      change.setKeepPreviewEdits(true);
      fChangeManager.manage(fField.getCompilationUnit(), change);
    }

    return status;
  }
 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;
 }
  /**
   * Create move refactoring session.
   *
   * @param cmr move settings, contains resource paths to move.
   * @return refactoring session id.
   * @throws JavaModelException when JavaModel has a failure
   * @throws RefactoringException when impossible to create move refactoring session
   */
  @POST
  @Path("move/create")
  @Consumes("application/json")
  @Produces("text/plain")
  public String createMoveRefactoring(CreateMoveRefactoring cmr)
      throws JavaModelException, RefactoringException {
    IJavaProject javaProject = model.getJavaProject(cmr.getProjectPath());
    IJavaElement[] javaElements;
    try {
      Function<ElementToMove, IJavaElement> map =
          javaElement -> {
            try {
              if (javaElement.isPack()) {
                return javaProject.findPackageFragment(
                    new org.eclipse.core.runtime.Path(javaElement.getPath()));
              } else {
                return javaProject.findType(javaElement.getPath()).getCompilationUnit();
              }
            } catch (JavaModelException e) {
              throw new IllegalArgumentException(e);
            }
          };
      javaElements = cmr.getElements().stream().map(map).toArray(IJavaElement[]::new);

    } catch (IllegalArgumentException e) {
      if (e.getCause() instanceof JavaModelException) {
        throw (JavaModelException) e.getCause();
      } else {
        throw e;
      }
    }
    if (RefactoringAvailabilityTester.isMoveAvailable(new IResource[0], javaElements)) {
      return manager.createMoveRefactoringSession(javaElements);
    }

    throw new RefactoringException("Can't create move refactoring.");
  }
Exemple #9
0
 public boolean isApplicable() throws CoreException {
   return RefactoringAvailabilityTester.isRenameFieldAvailable(fField);
 }
 @Override
 public boolean isApplicable() throws CoreException {
   return RefactoringAvailabilityTester.isRenameAvailable(fMethod);
 }