use of org.eclipse.core.runtime.NullProgressMonitor in project che by eclipse.
the class OrganizeImportsOperation method run.
/**
* Runs the operation.
*
* @param monitor
* the progress monitor
* @throws CoreException
* thrown when the operation failed
* @throws OperationCanceledException
* Runtime error thrown when operation is canceled.
*/
public void run(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
try {
monitor.beginTask(Messages.format(CodeGenerationMessages.OrganizeImportsOperation_description, BasicElementLabels.getFileName(fCompilationUnit)), 10);
edit = createTextEdit(new SubProgressMonitor(monitor, 9));
if (edit == null)
return;
JavaModelUtil.applyEdit(fCompilationUnit, edit, fDoSave, new SubProgressMonitor(monitor, 1));
} finally {
monitor.done();
}
}
use of org.eclipse.core.runtime.NullProgressMonitor in project che by eclipse.
the class OrganizeImportsOperation method createTextEdit.
public TextEdit createTextEdit(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
try {
fNumberOfImportsAdded = 0;
fNumberOfImportsRemoved = 0;
monitor.beginTask(Messages.format(CodeGenerationMessages.OrganizeImportsOperation_description, BasicElementLabels.getFileName(fCompilationUnit)), 9);
CompilationUnit astRoot = fASTRoot;
if (astRoot == null) {
astRoot = SharedASTProvider.getAST(fCompilationUnit, SharedASTProvider.WAIT_YES, new SubProgressMonitor(monitor, 2));
if (monitor.isCanceled())
throw new OperationCanceledException();
} else {
monitor.worked(2);
}
ImportRewrite importsRewrite = StubUtility.createImportRewrite(astRoot, false);
Set<String> oldSingleImports = new HashSet<>();
Set<String> oldDemandImports = new HashSet<>();
List<SimpleName> typeReferences = new ArrayList<>();
List<SimpleName> staticReferences = new ArrayList<>();
if (!collectReferences(astRoot, typeReferences, staticReferences, oldSingleImports, oldDemandImports))
return null;
monitor.worked(1);
processor = new TypeReferenceProcessor(oldSingleImports, oldDemandImports, astRoot, importsRewrite, fIgnoreLowerCaseNames);
Iterator<SimpleName> refIterator = typeReferences.iterator();
while (refIterator.hasNext()) {
SimpleName typeRef = refIterator.next();
processor.add(typeRef);
}
hasOpenChoices = processor.process(new SubProgressMonitor(monitor, 3));
addStaticImports(staticReferences, importsRewrite);
if (hasOpenChoices) {
choices = processor.getChoices();
ISourceRange[] ranges = processor.getChoicesSourceRanges();
if (fChooseImportQuery != null) {
TypeNameMatch[] chosen = fChooseImportQuery.chooseImports(choices, ranges);
for (int i = 0; i < chosen.length; i++) {
TypeNameMatch typeInfo = chosen[i];
importsRewrite.addImport(typeInfo.getFullyQualifiedName());
}
} else if (chosenFQN != null) {
chosenFQN.forEach(importsRewrite::addImport);
}
}
TextEdit result = importsRewrite.rewriteImports(new SubProgressMonitor(monitor, 3));
determineImportDifferences(importsRewrite, oldSingleImports, oldDemandImports);
return result;
} finally {
monitor.done();
}
}
use of org.eclipse.core.runtime.NullProgressMonitor in project che by eclipse.
the class RenameTypeProcessor method initializeSimilarElementsRenameProcessors.
// --------- Similar names
/**
* Creates and initializes the refactoring processors for similarly named elements
* @param progressMonitor progress monitor
* @param context context
* @return status
* @throws CoreException should not happen
*/
private RefactoringStatus initializeSimilarElementsRenameProcessors(IProgressMonitor progressMonitor, CheckConditionsContext context) throws CoreException {
Assert.isNotNull(fPreloadedElementToName);
Assert.isNotNull(fPreloadedElementToSelection);
final RefactoringStatus status = new RefactoringStatus();
final Set<IMethod> handledTopLevelMethods = new HashSet<IMethod>();
final Set<Warning> warnings = new HashSet<Warning>();
final List<RefactoringProcessor> processors = new ArrayList<RefactoringProcessor>();
fFinalSimilarElementToName = new HashMap<IJavaElement, String>();
CompilationUnit currentResolvedCU = null;
ICompilationUnit currentCU = null;
int current = 0;
final int max = fPreloadedElementToName.size();
//$NON-NLS-1$
progressMonitor.beginTask("", max * 3);
progressMonitor.setTaskName(RefactoringCoreMessages.RenameTypeProcessor_checking_similarly_named_declarations_refactoring_conditions);
for (Iterator<IJavaElement> iter = fPreloadedElementToName.keySet().iterator(); iter.hasNext(); ) {
final IJavaElement element = iter.next();
current++;
progressMonitor.worked(3);
// not selected? -> skip
if (!(fPreloadedElementToSelection.get(element)).booleanValue())
continue;
// already registered? (may happen with overridden methods) -> skip
if (fFinalSimilarElementToName.containsKey(element))
continue;
// CompilationUnit changed? (note: fPreloadedElementToName is sorted by CompilationUnit)
ICompilationUnit newCU = (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT);
if (!newCU.equals(currentCU)) {
checkCUCompleteConditions(status, currentResolvedCU, currentCU, processors);
if (status.hasFatalError())
return status;
// reset values
currentResolvedCU = null;
currentCU = newCU;
processors.clear();
}
final String newName = fPreloadedElementToName.get(element);
RefactoringProcessor processor = null;
if (element instanceof ILocalVariable) {
final ILocalVariable currentLocal = (ILocalVariable) element;
if (currentResolvedCU == null)
currentResolvedCU = new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(currentCU, true);
processor = createLocalRenameProcessor(currentLocal, newName, currentResolvedCU);
if (status.hasFatalError())
return status;
fFinalSimilarElementToName.put(currentLocal, newName);
}
if (element instanceof IField) {
final IField currentField = (IField) element;
processor = createFieldRenameProcessor(currentField, newName);
status.merge(checkForConflictingRename(currentField, newName));
if (status.hasFatalError())
return status;
fFinalSimilarElementToName.put(currentField, newName);
}
if (element instanceof IMethod) {
IMethod currentMethod = (IMethod) element;
if (MethodChecks.isVirtual(currentMethod)) {
final IType declaringType = currentMethod.getDeclaringType();
ITypeHierarchy hierarchy = null;
if (!declaringType.isInterface())
hierarchy = declaringType.newTypeHierarchy(new NullProgressMonitor());
final IMethod topmost = MethodChecks.getTopmostMethod(currentMethod, hierarchy, new NullProgressMonitor());
if (topmost != null)
currentMethod = topmost;
if (handledTopLevelMethods.contains(currentMethod))
continue;
handledTopLevelMethods.add(currentMethod);
final IMethod[] ripples = RippleMethodFinder2.getRelatedMethods(currentMethod, new NullProgressMonitor(), null);
if (checkForWarnings(warnings, newName, ripples))
continue;
status.merge(checkForConflictingRename(ripples, newName));
if (status.hasFatalError())
return status;
processor = createVirtualMethodRenameProcessor(currentMethod, newName, ripples, hierarchy);
fFinalSimilarElementToName.put(currentMethod, newName);
for (int i = 0; i < ripples.length; i++) {
fFinalSimilarElementToName.put(ripples[i], newName);
}
} else {
status.merge(checkForConflictingRename(new IMethod[] { currentMethod }, newName));
if (status.hasFatalError())
break;
fFinalSimilarElementToName.put(currentMethod, newName);
processor = createNonVirtualMethodRenameProcessor(currentMethod, newName);
}
}
progressMonitor.subTask(Messages.format(RefactoringCoreMessages.RenameTypeProcessor_progress_current_total, new Object[] { String.valueOf(current), String.valueOf(max) }));
status.merge(processor.checkInitialConditions(new NoOverrideProgressMonitor(progressMonitor, 1)));
if (status.hasFatalError())
return status;
status.merge(processor.checkFinalConditions(new NoOverrideProgressMonitor(progressMonitor, 1), context));
if (status.hasFatalError())
return status;
processors.add(processor);
progressMonitor.worked(1);
if (progressMonitor.isCanceled())
throw new OperationCanceledException();
}
// check last CU
checkCUCompleteConditions(status, currentResolvedCU, currentCU, processors);
status.merge(addWarnings(warnings));
progressMonitor.done();
return status;
}
use of org.eclipse.core.runtime.NullProgressMonitor in project che by eclipse.
the class RenameAnalyzeUtil method analyzeLocalRenames.
/**
* 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;
}
use of org.eclipse.core.runtime.NullProgressMonitor in project che by eclipse.
the class QuickAssistProcessor method getExtractMethodProposal.
private static boolean getExtractMethodProposal(IInvocationContext context, ASTNode coveringNode, boolean problemsAtLocation, Collection<ICommandAccess> proposals) throws CoreException {
if (!(coveringNode instanceof Expression) && !(coveringNode instanceof Statement) && !(coveringNode instanceof Block)) {
return false;
}
if (coveringNode instanceof Block) {
List<Statement> statements = ((Block) coveringNode).statements();
int startIndex = getIndex(context.getSelectionOffset(), statements);
if (startIndex == -1)
return false;
int endIndex = getIndex(context.getSelectionOffset() + context.getSelectionLength(), statements);
if (endIndex == -1 || endIndex <= startIndex)
return false;
}
if (proposals == null) {
return true;
}
final ICompilationUnit cu = context.getCompilationUnit();
final ExtractMethodRefactoring extractMethodRefactoring = new ExtractMethodRefactoring(context.getASTRoot(), context.getSelectionOffset(), context.getSelectionLength());
//$NON-NLS-1$
extractMethodRefactoring.setMethodName("extracted");
if (extractMethodRefactoring.checkInitialConditions(new NullProgressMonitor()).isOK()) {
String label = CorrectionMessages.QuickAssistProcessor_extractmethod_description;
LinkedProposalModel linkedProposalModel = new LinkedProposalModel();
extractMethodRefactoring.setLinkedProposalModel(linkedProposalModel);
Image image = JavaPluginImages.get(JavaPluginImages.DESC_MISC_PUBLIC);
int relevance = problemsAtLocation ? IProposalRelevance.EXTRACT_METHOD_ERROR : IProposalRelevance.EXTRACT_METHOD;
RefactoringCorrectionProposal proposal = new RefactoringCorrectionProposal(label, cu, extractMethodRefactoring, relevance, image);
proposal.setCommandId(EXTRACT_METHOD_INPLACE_ID);
proposal.setLinkedProposalModel(linkedProposalModel);
proposals.add(proposal);
}
return true;
}
Aggregations