private RefactoringStatus checkExpression() throws JavaModelException {
    RefactoringStatus result = new RefactoringStatus();
    result.merge(checkExpressionBinding());
    if (result.hasFatalError()) return result;
    checkAllStaticFinal();

    IExpressionFragment selectedExpression = getSelectedExpression();
    Expression associatedExpression = selectedExpression.getAssociatedExpression();
    if (associatedExpression instanceof NullLiteral)
      result.merge(
          RefactoringStatus.createFatalErrorStatus(
              RefactoringCoreMessages.ExtractConstantRefactoring_null_literals));
    else if (!ConstantChecks.isLoadTimeConstant(selectedExpression))
      result.merge(
          RefactoringStatus.createFatalErrorStatus(
              RefactoringCoreMessages.ExtractConstantRefactoring_not_load_time_constant));
    else if (associatedExpression instanceof SimpleName) {
      if (associatedExpression.getParent() instanceof QualifiedName
              && associatedExpression.getLocationInParent() == QualifiedName.NAME_PROPERTY
          || associatedExpression.getParent() instanceof FieldAccess
              && associatedExpression.getLocationInParent() == FieldAccess.NAME_PROPERTY)
        return RefactoringStatus.createFatalErrorStatus(
            RefactoringCoreMessages.ExtractConstantRefactoring_select_expression);
    }

    return result;
  }
Example #2
0
 private RefactoringStatus initialize(JavaRefactoringArguments extended) {
   final String handle = extended.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT);
   if (handle != null) {
     final IJavaElement element =
         JavaRefactoringDescriptorUtil.handleToElement(extended.getProject(), handle, false);
     if (element == null || !element.exists() || element.getElementType() != IJavaElement.FIELD)
       return JavaRefactoringDescriptorUtil.createInputFatalStatus(
           element, getProcessorName(), IJavaRefactorings.RENAME_FIELD);
     else fField = (IField) element;
   } else
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
             JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT));
   final String name = extended.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME);
   if (name != null && !"".equals(name)) // $NON-NLS-1$
   setNewElementName(name);
   else
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
             JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME));
   final String references =
       extended.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_REFERENCES);
   if (references != null) {
     fUpdateReferences = Boolean.valueOf(references).booleanValue();
   } else
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
             JavaRefactoringDescriptorUtil.ATTRIBUTE_REFERENCES));
   final String matches = extended.getAttribute(ATTRIBUTE_TEXTUAL_MATCHES);
   if (matches != null) {
     fUpdateTextualMatches = Boolean.valueOf(matches).booleanValue();
   } else
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
             ATTRIBUTE_TEXTUAL_MATCHES));
   final String getters = extended.getAttribute(ATTRIBUTE_RENAME_GETTER);
   if (getters != null) fRenameGetter = Boolean.valueOf(getters).booleanValue();
   else fRenameGetter = false;
   final String setters = extended.getAttribute(ATTRIBUTE_RENAME_SETTER);
   if (setters != null) fRenameSetter = Boolean.valueOf(setters).booleanValue();
   else fRenameSetter = false;
   final String delegate = extended.getAttribute(ATTRIBUTE_DELEGATE);
   if (delegate != null) {
     fDelegateUpdating = Boolean.valueOf(delegate).booleanValue();
   } else fDelegateUpdating = false;
   final String deprecate = extended.getAttribute(ATTRIBUTE_DEPRECATE);
   if (deprecate != null) {
     fDelegateDeprecation = Boolean.valueOf(deprecate).booleanValue();
   } else fDelegateDeprecation = false;
   return new RefactoringStatus();
 }
 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;
 }
 public RefactoringStatus checkFunctionName(final String newName) {
   if (newName == null || newName.length() == 0) {
     return RefactoringStatus.createFatalErrorStatus(
         NLS.bind(Messages.RIdentifiers_error_EmptyFor_message, "The function name"));
   }
   return new RefactoringStatus();
 }
Example #5
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;
  }
  @Override
  public RefactoringStatus checkInitialConditions(IProgressMonitor pm)
      throws CoreException, OperationCanceledException {
    if (functionClause == null) {
      return RefactoringStatus.createFatalErrorStatus("No function clause was given!");
    } else {

      ExpressionPosRpcMessage m = new ExpressionPosRpcMessage();
      String path = selection.getFilePath();
      String moduleName = functionClause.getModule().getModuleName();
      String functionName = functionClause.getFunctionName();
      int arity = functionClause.getArity();

      int clauseIndex = 1;
      if (!(functionClause instanceof IErlFunction))
        // FIXME: avoid hacking!!!
        clauseIndex = Integer.valueOf(functionClause.getName().substring(1));

      m =
          (ExpressionPosRpcMessage)
              WranglerBackendManager.getRefactoringBackend()
                  .callWithParser(
                      m,
                      "fold_expr_by_name_eclipse",
                      "sssiixi",
                      path,
                      moduleName,
                      functionName,
                      arity,
                      clauseIndex,
                      selection.getSearchPath(),
                      GlobalParameters.getTabWidth());

      if (m.isSuccessful()) {
        syntaxTree = m.getSyntaxTree();
        // TODO: store positions, selectedpositions
        positions = m.getPositionDefinitions(selection.getDocument());
        selectedPositions = new ArrayList<IErlRange>();
      } else {
        return RefactoringStatus.createFatalErrorStatus(m.getMessageString());
      }
    }

    return new RefactoringStatus();
  }
 @Override
 public RefactoringStatus isValid(IProgressMonitor pm)
     throws CoreException, OperationCanceledException {
   if (!isValid()) {
     return RefactoringStatus.createFatalErrorStatus(
         Messages.UndoDeleteContextReferenceChange_InvalidRefMsg);
   }
   return new RefactoringStatus();
 }
  @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();
    }
  }
 public static RefactoringStatus createInputFatalStatus(
     final Object element, final String name, final String id) {
   if (element != null) {
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringMessages.InitializableRefactoring_input_not_exists,
             new String[] {
               LanguageElementLabels.getTextLabel(
                   element, LanguageElementLabels.ALL_FULLY_QUALIFIED),
               name,
               id
             }));
   } else {
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringMessages.InitializableRefactoring_inputs_do_not_exist,
             new String[] {name, id}));
   }
 }
  @Override
  public RefactoringStatus checkInitialConditions(final IProgressMonitor monitor)
      throws CoreException {
    final SubMonitor progress = SubMonitor.convert(monitor, 6);
    RAstNode rootNode = null;
    try {
      if (fSelectionRegion != null) {
        fSourceUnit.connect(progress.newChild(1));
        try {
          final AbstractDocument document = fSourceUnit.getDocument(monitor);
          final RHeuristicTokenScanner scanner = fAdapter.getScanner(fSourceUnit);

          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, scanner);
            final AstInfo ast = modelInfo.getAst();
            if (ast != null) {
              rootNode =
                  (RAstNode)
                      AstSelection.search(
                              ast.root,
                              region.getOffset(),
                              region.getOffset() + region.getLength(),
                              AstSelection.MODE_COVERING_SAME_LAST)
                          .getCovering();
            }
          }
        } finally {
          fSourceUnit.disconnect(progress.newChild(1));
        }
      }

      if (rootNode == null) {
        return RefactoringStatus.createFatalErrorStatus(
            Messages.ExtractTemp_error_InvalidSelection_message);
      }
      final RefactoringStatus result = new RefactoringStatus();
      fAdapter.checkInitialToModify(result, fElementSet);
      progress.worked(1);

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

      searchVariables(rootNode, result);
      progress.worked(2);
      return result;
    } finally {
      progress.done();
    }
  }
  @Override
  public RefactoringStatus checkInitialConditions(IProgressMonitor pm)
      throws CoreException, OperationCanceledException {

    RefactoringStatus status = new RefactoringStatus();

    if ((!(getTargetFragment() instanceof TestMethod)) || (getTargetFragment() == null)) {
      status.merge(
          RefactoringStatus.createFatalErrorStatus("Selection is not valid. Select a method."));
    } else {
      targetMethod = (TestMethod) getTargetFragment();
    }

    if (status.hasEntries()) {
      status.merge(
          RefactoringStatus.createFatalErrorStatus(
              "Note: Select the bigger method wich groups smaller ones, press group incremental tests, all asserts will be brought to the selected method, the smaller methods will be removed."));
    }
    return status;
  }
 @Override
 public RefactoringStatus checkFinalConditions(IProgressMonitor pm)
     throws CoreException, OperationCanceledException {
   IErlSelection sel = GlobalParameters.getWranglerSelection();
   IRefactoringRpcMessage message = run(sel);
   if (message.isSuccessful()) {
     changedFiles = message.getRefactoringChangeset();
     return new RefactoringStatus();
   } else {
     return RefactoringStatus.createFatalErrorStatus(message.getMessageString());
   }
 }
  /* (non-Javadoc)
   * @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#checkInitialConditions(org.eclipse.core.runtime.IProgressMonitor)
   */
  public RefactoringStatus checkInitialConditions(IProgressMonitor pm)
      throws CoreException, OperationCanceledException {
    // allow only projects or only non-projects to be selected;
    // note that the selection may contain multiple types of resource
    if (!(Resources.containsOnlyProjects(fResources)
        || Resources.containsOnlyNonProjects(fResources))) {
      return RefactoringStatus.createFatalErrorStatus(
          RefactoringCoreMessages.DeleteResourcesProcessor_delete_error_mixed_types);
    }

    return new RefactoringStatus();
  }
Example #14
0
  public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
    IField primary = (IField) fField.getPrimaryElement();
    if (primary == null || !primary.exists()) {
      String message =
          Messages.format(
              RefactoringCoreMessages.RenameFieldRefactoring_deleted,
              BasicElementLabels.getFileName(fField.getCompilationUnit()));
      return RefactoringStatus.createFatalErrorStatus(message);
    }
    fField = primary;

    return Checks.checkIfCuBroken(fField);
  }
 @Override
 public RefactoringStatus checkInitialConditions(final IProgressMonitor pm)
     throws CoreException, OperationCanceledException {
   // FIXME: what kind of preconditions do I need?
   final IErlMemberSelection sel = (IErlMemberSelection) GlobalParameters.getWranglerSelection();
   final StateDataToRecordRpcMessage message = runFirst(sel);
   if (!message.isSuccessful()) {
     return RefactoringStatus.createFatalErrorStatus(message.getMessageString());
   } else {
     fieldCount = message.getFieldCount();
     stateFuns = message.getStateFuns();
     return new RefactoringStatus();
   }
 }
 /*
  * Used from www.eclipse.org/articles/article.php?file=Article-Unleashing-the-Power-of-Refactoring/index.html
  */
 @Override
 public RefactoringStatus checkInitialConditions(IProgressMonitor pm)
     throws CoreException, OperationCanceledException {
   RefactoringStatus status = new RefactoringStatus();
   try {
     pm.beginTask("Checking preconditions...", 1);
     if (method == null) {
       status.merge(RefactoringStatus.createFatalErrorStatus("Method has not been specified."));
     } else if (varName == null) {
       status.merge(RefactoringStatus.createFatalErrorStatus("Variable has not been specified."));
     } else if (!method.exists()) {
       status.merge(RefactoringStatus.createFatalErrorStatus("Method does not exist."));
     } else {
       if (!method.isBinary() && !method.getCompilationUnit().isStructureKnown()) {
         status.merge(
             RefactoringStatus.createFatalErrorStatus(
                 "Compilation unit contains compile errors."));
       }
     }
   } finally {
     pm.done();
   }
   return status;
 }
Example #17
0
  /**
   * Checks whether the given move included is vaild
   *
   * @param destination
   * @return a staus indicating whether the included is valid or not
   */
  public RefactoringStatus verifyDestination(IResource destination) {
    RefactoringStatus status = new RefactoringStatus();

    Assert.isNotNull(destination);
    if (!destination.exists() || destination.isPhantom())
      return RefactoringStatus.createFatalErrorStatus(
          PhpRefactoringCoreMessages.getString("MoveDelegate.2")); // $NON-NLS-1$
    if (!destination.isAccessible())
      return RefactoringStatus.createFatalErrorStatus(
          PhpRefactoringCoreMessages.getString("MoveDelegate.3")); // $NON-NLS-1$
    Assert.isTrue(destination.getType() != IResource.ROOT);

    IResource[] sourceResources = fProcessor.getSourceSelection();
    for (IResource element : sourceResources) {
      if (destination.equals(element.getParent()))
        return RefactoringStatus.createFatalErrorStatus(
            PhpRefactoringCoreMessages.getString("MoveDelegate.4")); // $NON-NLS-1$
      if (destination.equals(element)) {
        return RefactoringStatus.createFatalErrorStatus(
            PhpRefactoringCoreMessages.getString("MoveDelegate.5")); // $NON-NLS-1$
      }
    }
    return status;
  }
Example #18
0
 /**
  * Checks if {@link #selectionRange} selects {@link DartExpression} or set of {@link
  * DartStatement}s which can be extracted, and location in AST allows extracting.
  */
 private RefactoringStatus checkSelection(IProgressMonitor pm) throws CoreException {
   Selection selection = Selection.createFromStartLength(selectionStart, selectionLength);
   selectionAnalyzer = new ExtractMethodAnalyzer(unit, selection);
   unitNode.accept(selectionAnalyzer);
   // may be fatal error
   {
     RefactoringStatus status = selectionAnalyzer.getStatus();
     if (status.hasFatalError()) {
       return status;
     }
   }
   // update selection
   selectionLength = selectionAnalyzer.getSelectionExclusiveEnd() - selectionStart;
   selectionRange = SourceRangeFactory.forStartLength(selectionStart, selectionLength);
   // check selected nodes
   DartNode[] selectedNodes = selectionAnalyzer.getSelectedNodes();
   if (selectedNodes.length > 0) {
     parentMember =
         ASTNodes.getParent(selectionAnalyzer.getLastCoveringNode(), DartClassMember.class);
     // single expression selected
     if (selectedNodes.length == 1
         && !utils.rangeIncludesNonWhitespaceOutsideNode(
             selectionRange, selectionAnalyzer.getFirstSelectedNode())) {
       DartNode selectedNode = selectionAnalyzer.getFirstSelectedNode();
       if (selectedNode instanceof DartExpression) {
         selectionExpression = (DartExpression) selectedNode;
         return new RefactoringStatus();
       }
     }
     // statements selected
     {
       List<DartStatement> selectedStatements = Lists.newArrayList();
       for (DartNode selectedNode : selectedNodes) {
         if (selectedNode instanceof DartStatement) {
           selectedStatements.add((DartStatement) selectedNode);
         }
       }
       if (selectedStatements.size() == selectedNodes.length) {
         selectionStatements = selectedStatements;
         return new RefactoringStatus();
       }
     }
   }
   // invalid selection
   return RefactoringStatus.createFatalErrorStatus(
       RefactoringCoreMessages.ExtractMethodAnalyzer_single_expression_or_set);
 }
  @Override
  public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
    if (!fMethod.exists()) {
      String message =
          Messages.format(
              RefactoringCoreMessages.RenameMethodRefactoring_deleted,
              BasicElementLabels.getFileName(fMethod.getCompilationUnit()));
      return RefactoringStatus.createFatalErrorStatus(message);
    }

    RefactoringStatus result = Checks.checkAvailability(fMethod);
    if (result.hasFatalError()) return result;
    result.merge(Checks.checkIfCuBroken(fMethod));
    if (JdtFlags.isNative(fMethod))
      result.addError(RefactoringCoreMessages.RenameMethodRefactoring_no_native);
    return result;
  }
  private void checkFunction(final RefactoringStatus result) {
    if ((fFunction.getElementType() & IRElement.MASK_C2) != IRElement.R_COMMON_FUNCTION
        && (fFunction.getElementType() & IRElement.MASK_C2) != IRElement.R_COMMON_FUNCTION) {
      result.merge(
          RefactoringStatus.createFatalErrorStatus(
              Messages.FunctionToS4Method_error_SelectionAlreadyS4_message));
      return;
    }
    final RAstNode node = (RAstNode) fFunction.getAdapter(IAstNode.class);
    if (RAst.hasErrors(node)) {
      result.merge(
          RefactoringStatus.createWarningStatus(
              Messages.FunctionToS4Method_warning_SelectionSyntaxError_message));
    }
    //		if (fSelectionRegion != null
    //				&& (fSelectionRegion.getOffset() != fOperationRegion.getOffset() ||
    // fSelectionRegion.getLength() != fOperationRegion.getLength())) {
    //			result.merge(RefactoringStatus.createWarningStatus("The selected code does not equal
    // exactly the found expression(s)."));
    //		}

    RElementName elementName = fFunction.getElementName();
    while (elementName.getNextSegment() != null) {
      elementName = elementName.getNamespace();
    }
    fFunctionName = elementName.getDisplayName();

    final ArgsDefinition argsDef = fFunction.getArgsDefinition();
    final int count = (argsDef != null) ? argsDef.size() : 0;
    fVariablesList = new ArrayList(count);
    boolean dots = false;
    for (int i = 0; i < count; i++) {
      final Arg arg = argsDef.get(i);
      final Variable variable = new Variable(arg);
      if (variable.getName().equals(RTerminal.S_ELLIPSIS)) {
        dots = true;
        variable.init(true);
      } else {
        variable.init(!dots);
      }
      fVariablesList.add(variable);
    }
  }
 private RefactoringStatus initialize(JavaRefactoringArguments arguments) {
   final String selection =
       arguments.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION);
   if (selection != null) {
     int offset = -1;
     int length = -1;
     final StringTokenizer tokenizer = new StringTokenizer(selection);
     if (tokenizer.hasMoreTokens()) offset = Integer.valueOf(tokenizer.nextToken()).intValue();
     if (tokenizer.hasMoreTokens()) length = Integer.valueOf(tokenizer.nextToken()).intValue();
     if (offset >= 0 && length >= 0) {
       fSelectionStart = offset;
       fSelectionLength = length;
     } else
       return RefactoringStatus.createFatalErrorStatus(
           Messages.format(
               RefactoringCoreMessages.InitializableRefactoring_illegal_argument,
               new Object[] {selection, JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION}));
   } else
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
             JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION));
   final String handle = arguments.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT);
   if (handle != null) {
     final IJavaElement element =
         JavaRefactoringDescriptorUtil.handleToElement(arguments.getProject(), handle, false);
     if (element == null
         || !element.exists()
         || element.getElementType() != IJavaElement.COMPILATION_UNIT)
       return JavaRefactoringDescriptorUtil.createInputFatalStatus(
           element, getName(), IJavaRefactorings.EXTRACT_CONSTANT);
     else fCu = (ICompilationUnit) element;
   } else
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
             JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT));
   final String visibility = arguments.getAttribute(ATTRIBUTE_VISIBILITY);
   if (visibility != null && !"".equals(visibility)) { // $NON-NLS-1$
     int flag = 0;
     try {
       flag = Integer.parseInt(visibility);
     } catch (NumberFormatException exception) {
       return RefactoringStatus.createFatalErrorStatus(
           Messages.format(
               RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
               ATTRIBUTE_VISIBILITY));
     }
     fVisibility = JdtFlags.getVisibilityString(flag);
   }
   final String name = arguments.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME);
   if (name != null && !"".equals(name)) // $NON-NLS-1$
   fConstantName = name;
   else
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
             JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME));
   final String replace = arguments.getAttribute(ATTRIBUTE_REPLACE);
   if (replace != null) {
     fReplaceAllOccurrences = Boolean.valueOf(replace).booleanValue();
   } else
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
             ATTRIBUTE_REPLACE));
   final String declareFinal = arguments.getAttribute(ATTRIBUTE_QUALIFY);
   if (declareFinal != null) {
     fQualifyReferencesWithDeclaringClassName = Boolean.valueOf(declareFinal).booleanValue();
   } else
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
             ATTRIBUTE_QUALIFY));
   return new RefactoringStatus();
 }
 /**
  * Initializes the refactoring from scripting arguments. Used by {@link
  * RenameVirtualMethodProcessor} and {@link RenameNonVirtualMethodProcessor}
  *
  * @param extended the arguments
  * @return the resulting status
  */
 protected final RefactoringStatus initialize(JavaRefactoringArguments extended) {
   fInitialized = true;
   final String handle = extended.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT);
   if (handle != null) {
     final IJavaElement element =
         JavaRefactoringDescriptorUtil.handleToElement(extended.getProject(), handle, false);
     final String refactoring = getProcessorName();
     if (element instanceof IMethod) {
       final IMethod method = (IMethod) element;
       final IType declaring = method.getDeclaringType();
       if (declaring != null && declaring.exists()) {
         final IMethod[] methods = declaring.findMethods(method);
         if (methods != null && methods.length == 1 && methods[0] != null) {
           if (!methods[0].exists())
             return JavaRefactoringDescriptorUtil.createInputFatalStatus(
                 methods[0], refactoring, IJavaRefactorings.RENAME_METHOD);
           fMethod = methods[0];
           initializeWorkingCopyOwner();
         } else
           return JavaRefactoringDescriptorUtil.createInputFatalStatus(
               null, refactoring, IJavaRefactorings.RENAME_METHOD);
       } else
         return JavaRefactoringDescriptorUtil.createInputFatalStatus(
             element, refactoring, IJavaRefactorings.RENAME_METHOD);
     } else
       return JavaRefactoringDescriptorUtil.createInputFatalStatus(
           element, refactoring, IJavaRefactorings.RENAME_METHOD);
   } else
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
             JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT));
   final String name = extended.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME);
   if (name != null && !"".equals(name)) // $NON-NLS-1$
   setNewElementName(name);
   else
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
             JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME));
   final String references =
       extended.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_REFERENCES);
   if (references != null) {
     fUpdateReferences = Boolean.valueOf(references).booleanValue();
   } else
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
             JavaRefactoringDescriptorUtil.ATTRIBUTE_REFERENCES));
   final String delegate = extended.getAttribute(ATTRIBUTE_DELEGATE);
   if (delegate != null) {
     fDelegateUpdating = Boolean.valueOf(delegate).booleanValue();
   } else
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
             ATTRIBUTE_DELEGATE));
   final String deprecate = extended.getAttribute(ATTRIBUTE_DEPRECATE);
   if (deprecate != null) {
     fDelegateDeprecation = Boolean.valueOf(deprecate).booleanValue();
   } else
     return RefactoringStatus.createFatalErrorStatus(
         Messages.format(
             RefactoringCoreMessages.InitializableRefactoring_argument_not_exist,
             ATTRIBUTE_DEPRECATE));
   return new RefactoringStatus();
 }
/**
 * LTK wrapper around Analysis Server refactoring.
 *
 * @coverage dart.editor.ui.refactoring.ui
 */
public abstract class ServerRefactoring extends Refactoring {
  public interface ServerRefactoringListener {
    void requestStateChanged(boolean hasPendingRequests, RefactoringStatus optionsStatus);
  }

  protected static final RefactoringStatus TIMEOUT_STATUS =
      RefactoringStatus.createFatalErrorStatus("Timeout");

  public static String[] toStringArray(List<String> list) {
    return list.toArray(new String[list.size()]);
  }

  protected final String kind;
  private final String name;
  private final String file;
  private final int offset;
  private final int length;

  protected RefactoringStatus serverErrorStatus;
  protected RefactoringStatus initialStatus;
  protected RefactoringStatus optionsStatus;
  protected RefactoringStatus finalStatus;
  private Change change;
  private final List<String> externalFiles = Lists.newArrayList();

  private int lastId = 0;
  private final Set<Integer> pendingRequestIds = Sets.newHashSet();
  private ServerRefactoringListener listener;

  public ServerRefactoring(String kind, String name, String file, int offset, int length) {
    this.kind = kind;
    this.name = name;
    this.file = file;
    this.offset = offset;
    this.length = length;
  }

  @Override
  public RefactoringStatus checkFinalConditions(IProgressMonitor pm) {
    setOptions(false, pm);
    if (serverErrorStatus != null) {
      return serverErrorStatus;
    }
    // done if already fatal
    if (finalStatus.hasFatalError()) {
      return finalStatus;
    }
    // check for external files
    if (!externalFiles.isEmpty()) {
      finalStatus.addError(
          "The following files are external and cannot be updated",
          new StringStatusContext(null, StringUtils.join(externalFiles, "\n")));
    }
    // done
    return finalStatus;
  }

  @Override
  public RefactoringStatus checkInitialConditions(IProgressMonitor pm) {
    setOptions(true, pm);
    if (serverErrorStatus != null) {
      return serverErrorStatus;
    }
    return initialStatus;
  }

  @Override
  public Change createChange(IProgressMonitor pm) {
    setOptions(false, pm);
    return change;
  }

  @Override
  public String getName() {
    return name;
  }

  /**
   * @return {@code true} if the {@link Change} created by refactoring may be unsafe, so we want
   *     user to review the change to ensure that he understand it.
   */
  public boolean requiresPreview() {
    return false;
  }

  public void setListener(ServerRefactoringListener listener) {
    this.listener = listener;
  }

  /** Returns this {@link RefactoringOptions} subclass instance. */
  protected abstract RefactoringOptions getOptions();

  /** Sets the received {@link RefactoringFeedback}. */
  protected abstract void setFeedback(RefactoringFeedback feedback);

  protected void setOptions(boolean validateOnly) {
    setOptions(validateOnly, null);
  }

  protected void setOptions(boolean validateOnly, IProgressMonitor pm) {
    // add a new pending request ID
    final int id;
    synchronized (pendingRequestIds) {
      id = ++lastId;
      pendingRequestIds.add(id);
    }
    // do request
    serverErrorStatus = null;
    final CountDownLatch latch = new CountDownLatch(1);
    RefactoringOptions options = getOptions();
    DartCore.getAnalysisServer()
        .edit_getRefactoring(
            kind,
            file,
            offset,
            length,
            validateOnly,
            options,
            new GetRefactoringConsumer() {
              @Override
              public void computedRefactorings(
                  List<RefactoringProblem> initialProblems,
                  List<RefactoringProblem> optionsProblems,
                  List<RefactoringProblem> finalProblems,
                  RefactoringFeedback feedback,
                  SourceChange _change,
                  List<String> potentialEdits) {
                if (feedback != null) {
                  setFeedback(feedback);
                }
                externalFiles.clear();
                initialStatus = toRefactoringStatus(initialProblems);
                optionsStatus = toRefactoringStatus(optionsProblems);
                finalStatus = toRefactoringStatus(finalProblems);
                change = toLTK(_change, externalFiles);
                latch.countDown();
                requestDone(id);
              }

              @Override
              public void onError(RequestError requestError) {
                String message = "Server error: " + requestError.getMessage();
                serverErrorStatus = RefactoringStatus.createFatalErrorStatus(message);
                latch.countDown();
                requestDone(id);
              }

              private void requestDone(final int id) {
                synchronized (pendingRequestIds) {
                  pendingRequestIds.remove(id);
                  notifyListener();
                }
              }
            });
    // wait for completion
    if (pm != null) {
      while (true) {
        if (pm.isCanceled()) {
          throw new OperationCanceledException();
        }
        boolean done = Uninterruptibles.awaitUninterruptibly(latch, 10, TimeUnit.MILLISECONDS);
        if (done) {
          return;
        }
      }
    } else {
      // Wait a very short time, just in case it it can be done fast,
      // so that we don't have to disable UI and re-enable it 2 milliseconds later.
      Uninterruptibles.awaitUninterruptibly(latch, 10, TimeUnit.MILLISECONDS);
      notifyListener();
    }
  }

  private void notifyListener() {
    if (listener != null) {
      boolean hasPendingRequests = !pendingRequestIds.isEmpty();
      listener.requestStateChanged(hasPendingRequests, optionsStatus);
    }
  }
}