use of org.eclipse.core.runtime.SubProgressMonitor 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.SubProgressMonitor 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.SubProgressMonitor in project che by eclipse.
the class AddImportsOperation method evaluateEdits.
private TextEdit evaluateEdits(CompilationUnit root, ImportRewrite importRewrite, int offset, int length, IProgressMonitor monitor) throws JavaModelException {
SimpleName nameNode = null;
if (root != null) {
// got an AST
ASTNode node = NodeFinder.perform(root, offset, length);
if (node instanceof MarkerAnnotation) {
node = ((Annotation) node).getTypeName();
}
if (node instanceof QualifiedName) {
nameNode = ((QualifiedName) node).getName();
} else if (node instanceof SimpleName) {
nameNode = (SimpleName) node;
}
}
String name, simpleName, containerName;
int qualifierStart;
int simpleNameStart;
if (nameNode != null) {
simpleName = nameNode.getIdentifier();
simpleNameStart = nameNode.getStartPosition();
if (nameNode.getLocationInParent() == QualifiedName.NAME_PROPERTY) {
Name qualifier = ((QualifiedName) nameNode.getParent()).getQualifier();
containerName = qualifier.getFullyQualifiedName();
name = JavaModelUtil.concatenateName(containerName, simpleName);
qualifierStart = qualifier.getStartPosition();
} else if (nameNode.getLocationInParent() == NameQualifiedType.NAME_PROPERTY) {
NameQualifiedType nameQualifiedType = (NameQualifiedType) nameNode.getParent();
Name qualifier = nameQualifiedType.getQualifier();
containerName = qualifier.getFullyQualifiedName();
name = JavaModelUtil.concatenateName(containerName, simpleName);
qualifierStart = qualifier.getStartPosition();
List<Annotation> annotations = nameQualifiedType.annotations();
if (!annotations.isEmpty()) {
// don't remove annotations
simpleNameStart = annotations.get(0).getStartPosition();
}
} else if (nameNode.getLocationInParent() == MethodInvocation.NAME_PROPERTY) {
ASTNode qualifier = ((MethodInvocation) nameNode.getParent()).getExpression();
if (qualifier instanceof Name) {
containerName = ASTNodes.asString(qualifier);
name = JavaModelUtil.concatenateName(containerName, simpleName);
qualifierStart = qualifier.getStartPosition();
} else {
return null;
}
} else {
//$NON-NLS-1$
containerName = "";
name = simpleName;
qualifierStart = simpleNameStart;
}
IBinding binding = nameNode.resolveBinding();
if (binding != null && !binding.isRecovered()) {
if (binding instanceof ITypeBinding) {
ITypeBinding typeBinding = ((ITypeBinding) binding).getTypeDeclaration();
String qualifiedBindingName = typeBinding.getQualifiedName();
if (containerName.length() > 0 && !qualifiedBindingName.equals(name)) {
return null;
}
ImportRewriteContext context = new ContextSensitiveImportRewriteContext(root, qualifierStart, importRewrite);
String res = importRewrite.addImport(typeBinding, context);
if (containerName.length() > 0 && !res.equals(simpleName)) {
// adding import failed
fStatus = JavaUIStatus.createError(IStatus.ERROR, CodeGenerationMessages.AddImportsOperation_error_importclash, null);
return null;
}
if (containerName.length() == 0 && res.equals(simpleName)) {
// no change necessary
return null;
}
return new ReplaceEdit(qualifierStart, simpleNameStart - qualifierStart, new String());
} else if (JavaModelUtil.is50OrHigher(fCompilationUnit.getJavaProject()) && (binding instanceof IVariableBinding || binding instanceof IMethodBinding)) {
boolean isField = binding instanceof IVariableBinding;
ITypeBinding declaringClass = isField ? ((IVariableBinding) binding).getDeclaringClass() : ((IMethodBinding) binding).getDeclaringClass();
if (declaringClass == null) {
// variableBinding.getDeclaringClass() is null for array.length
return null;
}
if (Modifier.isStatic(binding.getModifiers())) {
if (containerName.length() > 0) {
if (containerName.equals(declaringClass.getName()) || containerName.equals(declaringClass.getQualifiedName())) {
ASTNode node = nameNode.getParent();
boolean isDirectlyAccessible = false;
while (node != null) {
if (isTypeDeclarationSubTypeCompatible(node, declaringClass)) {
isDirectlyAccessible = true;
break;
}
node = node.getParent();
}
if (!isDirectlyAccessible) {
if (Modifier.isPrivate(declaringClass.getModifiers())) {
fStatus = JavaUIStatus.createError(IStatus.ERROR, Messages.format(CodeGenerationMessages.AddImportsOperation_error_not_visible_class, BasicElementLabels.getJavaElementName(declaringClass.getName())), null);
return null;
}
String res = importRewrite.addStaticImport(declaringClass.getQualifiedName(), binding.getName(), isField);
if (!res.equals(simpleName)) {
// adding import failed
return null;
}
}
//$NON-NLS-1$
return new ReplaceEdit(qualifierStart, simpleNameStart - qualifierStart, "");
}
}
}
// no static imports for packages
return null;
} else {
return null;
}
}
if (binding != null && binding.getKind() != IBinding.TYPE) {
// recovered binding
return null;
}
} else {
IBuffer buffer = fCompilationUnit.getBuffer();
qualifierStart = getNameStart(buffer, offset);
int nameEnd = getNameEnd(buffer, offset + length);
int len = nameEnd - qualifierStart;
name = buffer.getText(qualifierStart, len).trim();
if (name.length() == 0) {
return null;
}
simpleName = Signature.getSimpleName(name);
containerName = Signature.getQualifier(name);
IJavaProject javaProject = fCompilationUnit.getJavaProject();
if (simpleName.length() == 0 || JavaConventionsUtil.validateJavaTypeName(simpleName, javaProject).matches(IStatus.ERROR) || (containerName.length() > 0 && JavaConventionsUtil.validateJavaTypeName(containerName, javaProject).matches(IStatus.ERROR))) {
fStatus = JavaUIStatus.createError(IStatus.ERROR, CodeGenerationMessages.AddImportsOperation_error_invalid_selection, null);
return null;
}
simpleNameStart = getSimpleNameStart(buffer, qualifierStart, containerName);
int res = importRewrite.getDefaultImportRewriteContext().findInContext(containerName, simpleName, ImportRewriteContext.KIND_TYPE);
if (res == ImportRewriteContext.RES_NAME_CONFLICT) {
fStatus = JavaUIStatus.createError(IStatus.ERROR, CodeGenerationMessages.AddImportsOperation_error_importclash, null);
return null;
} else if (res == ImportRewriteContext.RES_NAME_FOUND) {
//$NON-NLS-1$
return new ReplaceEdit(qualifierStart, simpleNameStart - qualifierStart, "");
}
}
IJavaSearchScope searchScope = SearchEngine.createJavaSearchScope(new IJavaElement[] { fCompilationUnit.getJavaProject() });
TypeNameMatch[] types = findAllTypes(simpleName, searchScope, nameNode, new SubProgressMonitor(monitor, 1));
if (types.length == 0) {
fStatus = JavaUIStatus.createError(IStatus.ERROR, Messages.format(CodeGenerationMessages.AddImportsOperation_error_notresolved_message, BasicElementLabels.getJavaElementName(simpleName)), null);
return null;
}
if (monitor.isCanceled()) {
throw new OperationCanceledException();
}
TypeNameMatch chosen;
if (types.length > 1 && fQuery != null) {
chosen = fQuery.chooseImport(types, containerName);
if (chosen == null) {
throw new OperationCanceledException();
}
} else {
chosen = types[0];
}
ImportRewriteContext context = root == null ? null : new ContextSensitiveImportRewriteContext(root, simpleNameStart, importRewrite);
importRewrite.addImport(chosen.getFullyQualifiedName(), context);
//$NON-NLS-1$
return new ReplaceEdit(qualifierStart, simpleNameStart - qualifierStart, "");
}
use of org.eclipse.core.runtime.SubProgressMonitor in project che by eclipse.
the class RenameMethodProcessor method doCheckFinalConditions.
@Override
protected RefactoringStatus doCheckFinalConditions(IProgressMonitor pm, CheckConditionsContext context) throws CoreException {
try {
RefactoringStatus result = new RefactoringStatus();
//$NON-NLS-1$
pm.beginTask("", 9);
// TODO workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=40367
if (!Checks.isAvailable(fMethod)) {
result.addFatalError(RefactoringCoreMessages.RenameMethodProcessor_is_binary, JavaStatusContext.create(fMethod));
return result;
}
result.merge(Checks.checkIfCuBroken(fMethod));
if (result.hasFatalError())
return result;
pm.setTaskName(RefactoringCoreMessages.RenameMethodRefactoring_taskName_checkingPreconditions);
result.merge(checkNewElementName(getNewElementName()));
if (result.hasFatalError())
return result;
boolean mustAnalyzeShadowing;
IMethod[] newNameMethods = searchForDeclarationsOfClashingMethods(new SubProgressMonitor(pm, 1));
if (newNameMethods.length == 0) {
mustAnalyzeShadowing = false;
pm.worked(1);
} else {
IType[] outerTypes = searchForOuterTypesOfReferences(newNameMethods, new SubProgressMonitor(pm, 1));
if (outerTypes.length > 0) {
//There exists a reference to a clashing method, where the reference is in a nested type.
//That nested type could be a type in a ripple method's hierarchy, which could
//cause the reference to bind to the new ripple method instead of to
//its old binding (a method of an enclosing scope).
//-> Getting *more* references than before -> Semantics not preserved.
//Examples: RenameVirtualMethodInClassTests#testFail39() and #testFail41()
//TODO: could pass declaringTypes to the RippleMethodFinder and check whether
//a hierarchy contains one of outerTypes (or an outer type of an outerType, recursively).
mustAnalyzeShadowing = true;
} else {
boolean hasOldRefsInInnerTypes = true;
//(recursively), whether they declare a rippleMethod
if (hasOldRefsInInnerTypes) {
//There exists a reference to a ripple method in a nested type
//of a type in the hierarchy of any ripple method.
//When that reference is renamed, and one of the supertypes of the
//nested type declared a method matching the new name, then
//the renamed reference will bind to the method in its supertype,
//since inherited methods bind stronger than methods from enclosing scopes.
//Getting *less* references than before -> Semantics not preserved.
//Examples: RenamePrivateMethodTests#testFail2(), RenamePrivateMethodTests#testFail5()
mustAnalyzeShadowing = true;
} else {
mustAnalyzeShadowing = false;
}
}
}
String binaryRefsDescription = Messages.format(RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description, BasicElementLabels.getJavaElementName(getCurrentElementName()));
ReferencesInBinaryContext binaryRefs = new ReferencesInBinaryContext(binaryRefsDescription);
initializeMethodsToRename(new SubProgressMonitor(pm, 1), binaryRefs);
pm.setTaskName(RefactoringCoreMessages.RenameMethodRefactoring_taskName_searchingForReferences);
fOccurrences = getOccurrences(new SubProgressMonitor(pm, 3), result, binaryRefs);
binaryRefs.addErrorIfNecessary(result);
pm.setTaskName(RefactoringCoreMessages.RenameMethodRefactoring_taskName_checkingPreconditions);
if (fUpdateReferences)
result.merge(checkRelatedMethods());
//removes CUs with syntax errors
result.merge(analyzeCompilationUnits());
pm.worked(1);
if (result.hasFatalError())
return result;
createChanges(new SubProgressMonitor(pm, 1), result);
if (fUpdateReferences & mustAnalyzeShadowing)
result.merge(analyzeRenameChanges(new SubProgressMonitor(pm, 1)));
else
pm.worked(1);
return result;
} finally {
pm.done();
}
}
use of org.eclipse.core.runtime.SubProgressMonitor in project che by eclipse.
the class RenameMethodProcessor method batchFindNewOccurrences.
//Lower memory footprint than batchFindNewOccurrences. Not used because it is too slow.
//Final solution is maybe to do searches in chunks of ~ 50 CUs.
// private SearchResultGroup[] findNewOccurrences(IMethod[] newMethods, ICompilationUnit[] newDeclarationWCs, IProgressMonitor pm) throws CoreException {
// pm.beginTask("", fOccurrences.length * 2); //$NON-NLS-1$
//
// SearchPattern refsPattern= RefactoringSearchEngine.createOrPattern(newMethods, IJavaSearchConstants.REFERENCES);
// SearchParticipant[] searchParticipants= SearchUtils.getDefaultSearchParticipants();
// IJavaSearchScope scope= RefactoringScopeFactory.create(newMethods);
// MethodOccurenceCollector requestor= new MethodOccurenceCollector(getNewElementName());
// SearchEngine searchEngine= new SearchEngine(fWorkingCopyOwner);
//
// //TODO: should process only references
// for (int j= 0; j < fOccurrences.length; j++) { //should be getReferences()
// //cut memory peak by holding only one reference CU at a time in memory
// ICompilationUnit originalCu= fOccurrences[j].getCompilationUnit();
// ICompilationUnit newWc= null;
// try {
// ICompilationUnit wc= RenameAnalyzeUtil.findWorkingCopyForCu(newDeclarationWCs, originalCu);
// if (wc == null) {
// newWc= RenameAnalyzeUtil.createNewWorkingCopy(originalCu, fChangeManager, fWorkingCopyOwner,
// new SubProgressMonitor(pm, 1));
// }
// searchEngine.search(refsPattern, searchParticipants, scope, requestor, new SubProgressMonitor(pm, 1));
// } finally {
// if (newWc != null)
// newWc.discardWorkingCopy();
// }
// }
// SearchResultGroup[] newResults= RefactoringSearchEngine.groupByResource(requestor.getResults());
// pm.done();
// return newResults;
// }
private SearchResultGroup[] batchFindNewOccurrences(IMethod[] wcNewMethods, final IMethod[] wcOldMethods, ICompilationUnit[] newDeclarationWCs, IProgressMonitor pm, RefactoringStatus status) throws CoreException {
//$NON-NLS-1$
pm.beginTask("", 2);
SearchPattern refsPattern = RefactoringSearchEngine.createOrPattern(wcNewMethods, IJavaSearchConstants.REFERENCES);
SearchParticipant[] searchParticipants = SearchUtils.getDefaultSearchParticipants();
IJavaSearchScope scope = RefactoringScopeFactory.create(wcNewMethods);
MethodOccurenceCollector requestor;
if (getDelegateUpdating()) {
// There will be two new matches inside the delegate(s) (the invocation
// and the javadoc) which are OK and must not be reported.
// Note that except these ocurrences, the delegate bodies are empty
// (as they were created this way).
requestor = new MethodOccurenceCollector(getNewElementName()) {
@Override
public void acceptSearchMatch(ICompilationUnit unit, SearchMatch match) throws CoreException {
for (int i = 0; i < wcOldMethods.length; i++) if (wcOldMethods[i].equals(match.getElement()))
return;
super.acceptSearchMatch(unit, match);
}
};
} else
requestor = new MethodOccurenceCollector(getNewElementName());
SearchEngine searchEngine = new SearchEngine(fWorkingCopyOwner);
ArrayList<ICompilationUnit> needWCs = new ArrayList<ICompilationUnit>();
HashSet<ICompilationUnit> declaringCUs = new HashSet<ICompilationUnit>(newDeclarationWCs.length);
for (int i = 0; i < newDeclarationWCs.length; i++) declaringCUs.add(newDeclarationWCs[i].getPrimary());
for (int i = 0; i < fOccurrences.length; i++) {
ICompilationUnit cu = fOccurrences[i].getCompilationUnit();
if (!declaringCUs.contains(cu))
needWCs.add(cu);
}
ICompilationUnit[] otherWCs = null;
try {
otherWCs = RenameAnalyzeUtil.createNewWorkingCopies(needWCs.toArray(new ICompilationUnit[needWCs.size()]), fChangeManager, fWorkingCopyOwner, new SubProgressMonitor(pm, 1));
searchEngine.search(refsPattern, searchParticipants, scope, requestor, new SubProgressMonitor(pm, 1));
} finally {
pm.done();
if (otherWCs != null) {
for (int i = 0; i < otherWCs.length; i++) {
otherWCs[i].discardWorkingCopy();
}
}
}
SearchResultGroup[] newResults = RefactoringSearchEngine.groupByCu(requestor.getResults(), status);
return newResults;
}
Aggregations