Search in sources :

Example 1 with NullProgressMonitor

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();
    }
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor)

Example 2 with NullProgressMonitor

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();
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ArrayList(java.util.ArrayList) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) TypeNameMatch(org.eclipse.jdt.core.search.TypeNameMatch) TextEdit(org.eclipse.text.edits.TextEdit) HashSet(java.util.HashSet) ISourceRange(org.eclipse.jdt.core.ISourceRange)

Example 3 with NullProgressMonitor

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;
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) ArrayList(java.util.ArrayList) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) IType(org.eclipse.jdt.core.IType) ILocalVariable(org.eclipse.jdt.core.ILocalVariable) ITypeHierarchy(org.eclipse.jdt.core.ITypeHierarchy) IMethod(org.eclipse.jdt.core.IMethod) HashSet(java.util.HashSet) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IJavaElement(org.eclipse.jdt.core.IJavaElement) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IField(org.eclipse.jdt.core.IField) RefactoringASTParser(org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser) RefactoringProcessor(org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor)

Example 4 with NullProgressMonitor

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;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) SimpleName(org.eclipse.jdt.core.dom.SimpleName) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) IRegion(org.eclipse.jface.text.IRegion) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Name(org.eclipse.jdt.core.dom.Name) RefactoringASTParser(org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser) ASTNode(org.eclipse.jdt.core.dom.ASTNode) VariableDeclaration(org.eclipse.jdt.core.dom.VariableDeclaration)

Example 5 with NullProgressMonitor

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;
}
Also used : ExtractMethodRefactoring(org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodRefactoring) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) LinkedProposalModel(org.eclipse.jdt.internal.corext.fix.LinkedProposalModel) Image(org.eclipse.swt.graphics.Image) RefactoringCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.RefactoringCorrectionProposal)

Aggregations

NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)1626 CoreException (org.eclipse.core.runtime.CoreException)430 Test (org.junit.Test)353 IFile (org.eclipse.core.resources.IFile)316 IProgressMonitor (org.eclipse.core.runtime.IProgressMonitor)276 IProject (org.eclipse.core.resources.IProject)261 File (java.io.File)213 IPath (org.eclipse.core.runtime.IPath)184 IOException (java.io.IOException)162 Path (org.eclipse.core.runtime.Path)141 ArrayList (java.util.ArrayList)125 IStatus (org.eclipse.core.runtime.IStatus)116 IFolder (org.eclipse.core.resources.IFolder)90 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)70 List (java.util.List)63 SubProgressMonitor (org.eclipse.core.runtime.SubProgressMonitor)63 InvocationTargetException (java.lang.reflect.InvocationTargetException)61 IProjectDescription (org.eclipse.core.resources.IProjectDescription)58 Status (org.eclipse.core.runtime.Status)57 IResource (org.eclipse.core.resources.IResource)56