Search in sources :

Example 1 with RefactoringCorrectionProposal

use of org.eclipse.jdt.internal.ui.text.correction.proposals.RefactoringCorrectionProposal in project che by eclipse.

the class LocalCorrectionsSubProcessor method addUncaughtExceptionProposals.

public static void addUncaughtExceptionProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) throws CoreException {
    ICompilationUnit cu = context.getCompilationUnit();
    CompilationUnit astRoot = context.getASTRoot();
    ASTNode selectedNode = problem.getCoveringNode(astRoot);
    if (selectedNode == null) {
        return;
    }
    while (selectedNode != null && !(selectedNode instanceof Statement) && !(selectedNode instanceof VariableDeclarationExpression)) {
        selectedNode = selectedNode.getParent();
    }
    if (selectedNode == null) {
        return;
    }
    int offset = selectedNode.getStartPosition();
    int length = selectedNode.getLength();
    int selectionEnd = context.getSelectionOffset() + context.getSelectionLength();
    if (selectionEnd > offset + length) {
        // extend the selection if more than one statement is selected (bug 72149)
        length = selectionEnd - offset;
    }
    //Surround with proposals
    SurroundWithTryCatchRefactoring refactoring = SurroundWithTryCatchRefactoring.create(cu, offset, length);
    if (refactoring == null)
        return;
    refactoring.setLeaveDirty(true);
    if (refactoring.checkActivationBasics(astRoot).isOK()) {
        String label = CorrectionMessages.LocalCorrectionsSubProcessor_surroundwith_trycatch_description;
        Image image = JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
        RefactoringCorrectionProposal proposal = new RefactoringCorrectionProposal(label, cu, refactoring, IProposalRelevance.SURROUND_WITH_TRY_CATCH, image);
        proposal.setLinkedProposalModel(refactoring.getLinkedProposalModel());
        proposals.add(proposal);
    }
    if (JavaModelUtil.is17OrHigher(cu.getJavaProject())) {
        refactoring = SurroundWithTryCatchRefactoring.create(cu, offset, length, true);
        if (refactoring == null)
            return;
        refactoring.setLeaveDirty(true);
        if (refactoring.checkActivationBasics(astRoot).isOK()) {
            String label = CorrectionMessages.LocalCorrectionsSubProcessor_surroundwith_trymulticatch_description;
            Image image = JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
            RefactoringCorrectionProposal proposal = new RefactoringCorrectionProposal(label, cu, refactoring, IProposalRelevance.SURROUND_WITH_TRY_MULTICATCH, image);
            proposal.setLinkedProposalModel(refactoring.getLinkedProposalModel());
            proposals.add(proposal);
        }
    }
    //Catch exception
    BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(selectedNode);
    if (decl == null) {
        return;
    }
    ITypeBinding[] uncaughtExceptions = ExceptionAnalyzer.perform(decl, Selection.createFromStartLength(offset, length));
    if (uncaughtExceptions.length == 0) {
        return;
    }
    TryStatement surroundingTry = ASTResolving.findParentTryStatement(selectedNode);
    AST ast = astRoot.getAST();
    if (surroundingTry != null && (ASTNodes.isParent(selectedNode, surroundingTry.getBody()) || selectedNode.getLocationInParent() == TryStatement.RESOURCES_PROPERTY)) {
        {
            ASTRewrite rewrite = ASTRewrite.create(surroundingTry.getAST());
            String label = CorrectionMessages.LocalCorrectionsSubProcessor_addadditionalcatch_description;
            Image image = JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
            LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.ADD_ADDITIONAL_CATCH, image);
            ImportRewrite imports = proposal.createImportRewrite(context.getASTRoot());
            ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(decl, imports);
            CodeScopeBuilder.Scope scope = CodeScopeBuilder.perform(decl, Selection.createFromStartLength(offset, length)).findScope(offset, length);
            scope.setCursor(offset);
            ListRewrite clausesRewrite = rewrite.getListRewrite(surroundingTry, TryStatement.CATCH_CLAUSES_PROPERTY);
            for (int i = 0; i < uncaughtExceptions.length; i++) {
                ITypeBinding excBinding = uncaughtExceptions[i];
                String varName = StubUtility.getExceptionVariableName(cu.getJavaProject());
                String name = scope.createName(varName, false);
                SingleVariableDeclaration var = ast.newSingleVariableDeclaration();
                var.setName(ast.newSimpleName(name));
                var.setType(imports.addImport(excBinding, ast, importRewriteContext));
                CatchClause newClause = ast.newCatchClause();
                newClause.setException(var);
                String catchBody = StubUtility.getCatchBodyContent(cu, excBinding.getName(), name, selectedNode, String.valueOf('\n'));
                if (catchBody != null) {
                    ASTNode node = rewrite.createStringPlaceholder(catchBody, ASTNode.RETURN_STATEMENT);
                    newClause.getBody().statements().add(node);
                }
                clausesRewrite.insertLast(newClause, null);
                //$NON-NLS-1$
                String typeKey = "type" + i;
                //$NON-NLS-1$
                String nameKey = "name" + i;
                proposal.addLinkedPosition(rewrite.track(var.getType()), false, typeKey);
                proposal.addLinkedPosition(rewrite.track(var.getName()), false, nameKey);
                addExceptionTypeLinkProposals(proposal, excBinding, typeKey);
            }
            proposals.add(proposal);
        }
        if (JavaModelUtil.is17OrHigher(cu.getJavaProject())) {
            List<CatchClause> catchClauses = surroundingTry.catchClauses();
            if (catchClauses != null && catchClauses.size() == 1) {
                List<ITypeBinding> filteredExceptions = filterSubtypeExceptions(uncaughtExceptions);
                String label = filteredExceptions.size() > 1 ? CorrectionMessages.LocalCorrectionsSubProcessor_addexceptionstoexistingcatch_description : CorrectionMessages.LocalCorrectionsSubProcessor_addexceptiontoexistingcatch_description;
                Image image = JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
                ASTRewrite rewrite = ASTRewrite.create(ast);
                LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.ADD_EXCEPTIONS_TO_EXISTING_CATCH, image);
                ImportRewrite imports = proposal.createImportRewrite(context.getASTRoot());
                ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(decl, imports);
                CatchClause catchClause = catchClauses.get(0);
                Type type = catchClause.getException().getType();
                if (type instanceof UnionType) {
                    UnionType unionType = (UnionType) type;
                    ListRewrite listRewrite = rewrite.getListRewrite(unionType, UnionType.TYPES_PROPERTY);
                    for (int i = 0; i < filteredExceptions.size(); i++) {
                        ITypeBinding excBinding = filteredExceptions.get(i);
                        Type type2 = imports.addImport(excBinding, ast, importRewriteContext);
                        listRewrite.insertLast(type2, null);
                        //$NON-NLS-1$
                        String typeKey = "type" + i;
                        proposal.addLinkedPosition(rewrite.track(type2), false, typeKey);
                        addExceptionTypeLinkProposals(proposal, excBinding, typeKey);
                    }
                } else {
                    UnionType newUnionType = ast.newUnionType();
                    List<Type> types = newUnionType.types();
                    types.add((Type) rewrite.createCopyTarget(type));
                    for (int i = 0; i < filteredExceptions.size(); i++) {
                        ITypeBinding excBinding = filteredExceptions.get(i);
                        Type type2 = imports.addImport(excBinding, ast, importRewriteContext);
                        types.add(type2);
                        //$NON-NLS-1$
                        String typeKey = "type" + i;
                        proposal.addLinkedPosition(rewrite.track(type2), false, typeKey);
                        addExceptionTypeLinkProposals(proposal, excBinding, typeKey);
                    }
                    rewrite.replace(type, newUnionType, null);
                }
                proposals.add(proposal);
            } else if (catchClauses != null && catchClauses.size() == 0 && uncaughtExceptions.length > 1) {
                String label = CorrectionMessages.LocalCorrectionsSubProcessor_addadditionalmulticatch_description;
                Image image = JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
                ASTRewrite rewrite = ASTRewrite.create(ast);
                LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.ADD_ADDITIONAL_MULTI_CATCH, image);
                ImportRewrite imports = proposal.createImportRewrite(context.getASTRoot());
                ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(decl, imports);
                CodeScopeBuilder.Scope scope = CodeScopeBuilder.perform(decl, Selection.createFromStartLength(offset, length)).findScope(offset, length);
                scope.setCursor(offset);
                CatchClause newCatchClause = ast.newCatchClause();
                String varName = StubUtility.getExceptionVariableName(cu.getJavaProject());
                String name = scope.createName(varName, false);
                SingleVariableDeclaration var = ast.newSingleVariableDeclaration();
                var.setName(ast.newSimpleName(name));
                UnionType newUnionType = ast.newUnionType();
                List<Type> types = newUnionType.types();
                for (int i = 0; i < uncaughtExceptions.length; i++) {
                    ITypeBinding excBinding = uncaughtExceptions[i];
                    Type type2 = imports.addImport(excBinding, ast, importRewriteContext);
                    types.add(type2);
                    //$NON-NLS-1$
                    String typeKey = "type" + i;
                    proposal.addLinkedPosition(rewrite.track(type2), false, typeKey);
                    addExceptionTypeLinkProposals(proposal, excBinding, typeKey);
                }
                //$NON-NLS-1$
                String nameKey = "name";
                proposal.addLinkedPosition(rewrite.track(var.getName()), false, nameKey);
                var.setType(newUnionType);
                newCatchClause.setException(var);
                //$NON-NLS-1$
                String catchBody = StubUtility.getCatchBodyContent(cu, "Exception", name, selectedNode, String.valueOf('\n'));
                if (catchBody != null) {
                    ASTNode node = rewrite.createStringPlaceholder(catchBody, ASTNode.RETURN_STATEMENT);
                    newCatchClause.getBody().statements().add(node);
                }
                ListRewrite listRewrite = rewrite.getListRewrite(surroundingTry, TryStatement.CATCH_CLAUSES_PROPERTY);
                listRewrite.insertFirst(newCatchClause, null);
                proposals.add(proposal);
            }
        }
    }
    //Add throws declaration
    if (decl instanceof MethodDeclaration) {
        MethodDeclaration methodDecl = (MethodDeclaration) decl;
        IMethodBinding binding = methodDecl.resolveBinding();
        boolean isApplicable = (binding != null);
        if (isApplicable) {
            IMethodBinding overriddenMethod = Bindings.findOverriddenMethod(binding, true);
            if (overriddenMethod != null) {
                isApplicable = overriddenMethod.getDeclaringClass().isFromSource();
                if (!isApplicable) {
                    // bug 349051
                    ITypeBinding[] exceptionTypes = overriddenMethod.getExceptionTypes();
                    ArrayList<ITypeBinding> unhandledExceptions = new ArrayList<ITypeBinding>(uncaughtExceptions.length);
                    for (int i = 0; i < uncaughtExceptions.length; i++) {
                        ITypeBinding curr = uncaughtExceptions[i];
                        if (isSubtype(curr, exceptionTypes)) {
                            unhandledExceptions.add(curr);
                        }
                    }
                    uncaughtExceptions = unhandledExceptions.toArray(new ITypeBinding[unhandledExceptions.size()]);
                    isApplicable |= uncaughtExceptions.length > 0;
                }
            }
        }
        if (isApplicable) {
            ITypeBinding[] methodExceptions = binding.getExceptionTypes();
            ArrayList<ITypeBinding> unhandledExceptions = new ArrayList<ITypeBinding>(uncaughtExceptions.length);
            for (int i = 0; i < uncaughtExceptions.length; i++) {
                ITypeBinding curr = uncaughtExceptions[i];
                if (!isSubtype(curr, methodExceptions)) {
                    unhandledExceptions.add(curr);
                }
            }
            uncaughtExceptions = unhandledExceptions.toArray(new ITypeBinding[unhandledExceptions.size()]);
            List<Type> exceptions = methodDecl.thrownExceptionTypes();
            int nExistingExceptions = exceptions.size();
            ChangeDescription[] desc = new ChangeDescription[nExistingExceptions + uncaughtExceptions.length];
            for (int i = 0; i < exceptions.size(); i++) {
                Type elem = exceptions.get(i);
                if (isSubtype(elem.resolveBinding(), uncaughtExceptions)) {
                    desc[i] = new RemoveDescription();
                }
            }
            for (int i = 0; i < uncaughtExceptions.length; i++) {
                //$NON-NLS-1$
                desc[i + nExistingExceptions] = new InsertDescription(uncaughtExceptions[i], "");
            }
            String label = CorrectionMessages.LocalCorrectionsSubProcessor_addthrows_description;
            Image image = JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
            ChangeMethodSignatureProposal proposal = new ChangeMethodSignatureProposal(label, cu, astRoot, binding, null, desc, IProposalRelevance.ADD_THROWS_DECLARATION, image);
            for (int i = 0; i < uncaughtExceptions.length; i++) {
                addExceptionTypeLinkProposals(proposal, uncaughtExceptions[i], proposal.getExceptionTypeGroupId(i + nExistingExceptions));
            }
            proposal.setCommandId(ADD_EXCEPTION_TO_THROWS_ID);
            proposals.add(proposal);
        }
    }
}
Also used : ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) InsertDescription(org.eclipse.jdt.internal.ui.text.correction.proposals.ChangeMethodSignatureProposal.InsertDescription) ArrayList(java.util.ArrayList) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) Image(org.eclipse.swt.graphics.Image) RefactoringCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.RefactoringCorrectionProposal) SurroundWithTryCatchRefactoring(org.eclipse.jdt.internal.corext.refactoring.surround.SurroundWithTryCatchRefactoring) ChangeDescription(org.eclipse.jdt.internal.ui.text.correction.proposals.ChangeMethodSignatureProposal.ChangeDescription) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) List(java.util.List) ArrayList(java.util.ArrayList) RemoveDescription(org.eclipse.jdt.internal.ui.text.correction.proposals.ChangeMethodSignatureProposal.RemoveDescription) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) ChangeMethodSignatureProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.ChangeMethodSignatureProposal) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) IType(org.eclipse.jdt.core.IType) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) LinkedCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal)

Example 2 with RefactoringCorrectionProposal

use of org.eclipse.jdt.internal.ui.text.correction.proposals.RefactoringCorrectionProposal 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)

Example 3 with RefactoringCorrectionProposal

use of org.eclipse.jdt.internal.ui.text.correction.proposals.RefactoringCorrectionProposal in project che by eclipse.

the class QuickAssistProcessor method getConvertAnonymousToNestedProposal.

private static boolean getConvertAnonymousToNestedProposal(IInvocationContext context, final ASTNode node, Collection<ICommandAccess> proposals) throws CoreException {
    if (!(node instanceof Name))
        return false;
    ASTNode normalized = ASTNodes.getNormalizedNode(node);
    if (normalized.getLocationInParent() != ClassInstanceCreation.TYPE_PROPERTY)
        return false;
    final AnonymousClassDeclaration anonymTypeDecl = ((ClassInstanceCreation) normalized.getParent()).getAnonymousClassDeclaration();
    if (anonymTypeDecl == null || anonymTypeDecl.resolveBinding() == null) {
        return false;
    }
    if (proposals == null) {
        return true;
    }
    final ICompilationUnit cu = context.getCompilationUnit();
    final ConvertAnonymousToNestedRefactoring refactoring = new ConvertAnonymousToNestedRefactoring(anonymTypeDecl);
    String extTypeName = ASTNodes.getSimpleNameIdentifier((Name) node);
    ITypeBinding anonymTypeBinding = anonymTypeDecl.resolveBinding();
    String className;
    if (anonymTypeBinding.getInterfaces().length == 0) {
        className = Messages.format(CorrectionMessages.QuickAssistProcessor_name_extension_from_interface, extTypeName);
    } else {
        className = Messages.format(CorrectionMessages.QuickAssistProcessor_name_extension_from_class, extTypeName);
    }
    String[][] existingTypes = ((IType) anonymTypeBinding.getJavaElement()).resolveType(className);
    int i = 1;
    while (existingTypes != null) {
        i++;
        existingTypes = ((IType) anonymTypeBinding.getJavaElement()).resolveType(className + i);
    }
    refactoring.setClassName(i == 1 ? className : className + i);
    if (refactoring.checkInitialConditions(new NullProgressMonitor()).isOK()) {
        LinkedProposalModel linkedProposalModel = new LinkedProposalModel();
        refactoring.setLinkedProposalModel(linkedProposalModel);
        String label = CorrectionMessages.QuickAssistProcessor_convert_anonym_to_nested;
        Image image = JavaPlugin.getImageDescriptorRegistry().get(JavaElementImageProvider.getTypeImageDescriptor(true, false, Flags.AccPrivate, false));
        RefactoringCorrectionProposal proposal = new RefactoringCorrectionProposal(label, cu, refactoring, IProposalRelevance.CONVERT_ANONYMOUS_TO_NESTED, image);
        proposal.setLinkedProposalModel(linkedProposalModel);
        proposal.setCommandId(CONVERT_ANONYMOUS_TO_LOCAL_ID);
        proposals.add(proposal);
    }
    return false;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) ConvertAnonymousToNestedRefactoring(org.eclipse.jdt.internal.corext.refactoring.code.ConvertAnonymousToNestedRefactoring) LinkedProposalModel(org.eclipse.jdt.internal.corext.fix.LinkedProposalModel) Image(org.eclipse.swt.graphics.Image) RefactoringCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.RefactoringCorrectionProposal) IType(org.eclipse.jdt.core.IType)

Example 4 with RefactoringCorrectionProposal

use of org.eclipse.jdt.internal.ui.text.correction.proposals.RefactoringCorrectionProposal in project che by eclipse.

the class QuickAssistProcessor method getExtractVariableProposal.

private static boolean getExtractVariableProposal(IInvocationContext context, boolean problemsAtLocation, Collection<ICommandAccess> proposals) throws CoreException {
    ASTNode node = context.getCoveredNode();
    if (!(node instanceof Expression)) {
        if (context.getSelectionLength() != 0) {
            return false;
        }
        node = context.getCoveringNode();
        if (!(node instanceof Expression)) {
            return false;
        }
    }
    final Expression expression = (Expression) node;
    ITypeBinding binding = expression.resolveTypeBinding();
    if (binding == null || Bindings.isVoidType(binding)) {
        return false;
    }
    if (proposals == null) {
        return true;
    }
    final ICompilationUnit cu = context.getCompilationUnit();
    ExtractTempRefactoring extractTempRefactoring = new ExtractTempRefactoring(context.getASTRoot(), context.getSelectionOffset(), context.getSelectionLength());
    if (extractTempRefactoring.checkInitialConditions(new NullProgressMonitor()).isOK()) {
        LinkedProposalModel linkedProposalModel = new LinkedProposalModel();
        extractTempRefactoring.setLinkedProposalModel(linkedProposalModel);
        extractTempRefactoring.setCheckResultForCompileProblems(false);
        String label = CorrectionMessages.QuickAssistProcessor_extract_to_local_all_description;
        Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
        int relevance;
        if (context.getSelectionLength() == 0) {
            relevance = IProposalRelevance.EXTRACT_LOCAL_ALL_ZERO_SELECTION;
        } else if (problemsAtLocation) {
            relevance = IProposalRelevance.EXTRACT_LOCAL_ALL_ERROR;
        } else {
            relevance = IProposalRelevance.EXTRACT_LOCAL_ALL;
        }
        RefactoringCorrectionProposal proposal = new RefactoringCorrectionProposal(label, cu, extractTempRefactoring, relevance, image) {

            @Override
            protected void init(Refactoring refactoring) throws CoreException {
                ExtractTempRefactoring etr = (ExtractTempRefactoring) refactoring;
                // expensive
                etr.setTempName(etr.guessTempName());
            }
        };
        proposal.setCommandId(EXTRACT_LOCAL_ID);
        proposal.setLinkedProposalModel(linkedProposalModel);
        proposals.add(proposal);
    }
    ExtractTempRefactoring extractTempRefactoringSelectedOnly = new ExtractTempRefactoring(context.getASTRoot(), context.getSelectionOffset(), context.getSelectionLength());
    extractTempRefactoringSelectedOnly.setReplaceAllOccurrences(false);
    if (extractTempRefactoringSelectedOnly.checkInitialConditions(new NullProgressMonitor()).isOK()) {
        LinkedProposalModel linkedProposalModel = new LinkedProposalModel();
        extractTempRefactoringSelectedOnly.setLinkedProposalModel(linkedProposalModel);
        extractTempRefactoringSelectedOnly.setCheckResultForCompileProblems(false);
        String label = CorrectionMessages.QuickAssistProcessor_extract_to_local_description;
        Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
        int relevance;
        if (context.getSelectionLength() == 0) {
            relevance = IProposalRelevance.EXTRACT_LOCAL_ZERO_SELECTION;
        } else if (problemsAtLocation) {
            relevance = IProposalRelevance.EXTRACT_LOCAL_ERROR;
        } else {
            relevance = IProposalRelevance.EXTRACT_LOCAL;
        }
        RefactoringCorrectionProposal proposal = new RefactoringCorrectionProposal(label, cu, extractTempRefactoringSelectedOnly, relevance, image) {

            @Override
            protected void init(Refactoring refactoring) throws CoreException {
                ExtractTempRefactoring etr = (ExtractTempRefactoring) refactoring;
                // expensive
                etr.setTempName(etr.guessTempName());
            }
        };
        proposal.setCommandId(EXTRACT_LOCAL_NOT_REPLACE_ID);
        proposal.setLinkedProposalModel(linkedProposalModel);
        proposals.add(proposal);
    }
    ExtractConstantRefactoring extractConstRefactoring = new ExtractConstantRefactoring(context.getASTRoot(), context.getSelectionOffset(), context.getSelectionLength());
    if (extractConstRefactoring.checkInitialConditions(new NullProgressMonitor()).isOK()) {
        LinkedProposalModel linkedProposalModel = new LinkedProposalModel();
        extractConstRefactoring.setLinkedProposalModel(linkedProposalModel);
        extractConstRefactoring.setCheckResultForCompileProblems(false);
        String label = CorrectionMessages.QuickAssistProcessor_extract_to_constant_description;
        Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
        int relevance;
        if (context.getSelectionLength() == 0) {
            relevance = IProposalRelevance.EXTRACT_CONSTANT_ZERO_SELECTION;
        } else if (problemsAtLocation) {
            relevance = IProposalRelevance.EXTRACT_CONSTANT_ERROR;
        } else {
            relevance = IProposalRelevance.EXTRACT_CONSTANT;
        }
        RefactoringCorrectionProposal proposal = new RefactoringCorrectionProposal(label, cu, extractConstRefactoring, relevance, image) {

            @Override
            protected void init(Refactoring refactoring) throws CoreException {
                ExtractConstantRefactoring etr = (ExtractConstantRefactoring) refactoring;
                // expensive
                etr.setConstantName(etr.guessConstantName());
            }
        };
        proposal.setCommandId(EXTRACT_CONSTANT_ID);
        proposal.setLinkedProposalModel(linkedProposalModel);
        proposals.add(proposal);
    }
    return false;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) LinkedProposalModel(org.eclipse.jdt.internal.corext.fix.LinkedProposalModel) ExtractTempRefactoring(org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring) Image(org.eclipse.swt.graphics.Image) RefactoringCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.RefactoringCorrectionProposal) Refactoring(org.eclipse.ltk.core.refactoring.Refactoring) InlineTempRefactoring(org.eclipse.jdt.internal.corext.refactoring.code.InlineTempRefactoring) ExtractTempRefactoring(org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring) PromoteTempToFieldRefactoring(org.eclipse.jdt.internal.corext.refactoring.code.PromoteTempToFieldRefactoring) ExtractMethodRefactoring(org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodRefactoring) ConvertAnonymousToNestedRefactoring(org.eclipse.jdt.internal.corext.refactoring.code.ConvertAnonymousToNestedRefactoring) ExtractConstantRefactoring(org.eclipse.jdt.internal.corext.refactoring.code.ExtractConstantRefactoring) ExtractConstantRefactoring(org.eclipse.jdt.internal.corext.refactoring.code.ExtractConstantRefactoring)

Example 5 with RefactoringCorrectionProposal

use of org.eclipse.jdt.internal.ui.text.correction.proposals.RefactoringCorrectionProposal in project che by eclipse.

the class QuickAssistProcessor method getConvertLocalToFieldProposal.

private static boolean getConvertLocalToFieldProposal(IInvocationContext context, final ASTNode node, Collection<ICommandAccess> proposals) throws CoreException {
    if (!(node instanceof SimpleName))
        return false;
    SimpleName name = (SimpleName) node;
    IBinding binding = name.resolveBinding();
    if (!(binding instanceof IVariableBinding))
        return false;
    IVariableBinding varBinding = (IVariableBinding) binding;
    if (varBinding.isField() || varBinding.isParameter())
        return false;
    ASTNode decl = context.getASTRoot().findDeclaringNode(varBinding);
    if (decl == null || decl.getLocationInParent() != VariableDeclarationStatement.FRAGMENTS_PROPERTY)
        return false;
    if (proposals == null) {
        return true;
    }
    PromoteTempToFieldRefactoring refactoring = new PromoteTempToFieldRefactoring((VariableDeclaration) decl);
    if (refactoring.checkInitialConditions(new NullProgressMonitor()).isOK()) {
        String label = CorrectionMessages.QuickAssistProcessor_convert_local_to_field_description;
        Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
        LinkedProposalModel linkedProposalModel = new LinkedProposalModel();
        refactoring.setLinkedProposalModel(linkedProposalModel);
        RefactoringCorrectionProposal proposal = new RefactoringCorrectionProposal(label, context.getCompilationUnit(), refactoring, IProposalRelevance.CONVERT_LOCAL_TO_FIELD, image);
        proposal.setLinkedProposalModel(linkedProposalModel);
        proposal.setCommandId(CONVERT_LOCAL_TO_FIELD_ID);
        proposals.add(proposal);
    }
    return true;
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) PromoteTempToFieldRefactoring(org.eclipse.jdt.internal.corext.refactoring.code.PromoteTempToFieldRefactoring) 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

RefactoringCorrectionProposal (org.eclipse.jdt.internal.ui.text.correction.proposals.RefactoringCorrectionProposal)6 Image (org.eclipse.swt.graphics.Image)6 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)5 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)4 LinkedProposalModel (org.eclipse.jdt.internal.corext.fix.LinkedProposalModel)4 IType (org.eclipse.jdt.core.IType)2 ConvertAnonymousToNestedRefactoring (org.eclipse.jdt.internal.corext.refactoring.code.ConvertAnonymousToNestedRefactoring)2 ExtractMethodRefactoring (org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodRefactoring)2 InlineTempRefactoring (org.eclipse.jdt.internal.corext.refactoring.code.InlineTempRefactoring)2 PromoteTempToFieldRefactoring (org.eclipse.jdt.internal.corext.refactoring.code.PromoteTempToFieldRefactoring)2 ArrayList (java.util.ArrayList)1 List (java.util.List)1 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)1 ImportRewrite (org.eclipse.jdt.core.dom.rewrite.ImportRewrite)1 ImportRewriteContext (org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext)1 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)1 ContextSensitiveImportRewriteContext (org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext)1 ExtractConstantRefactoring (org.eclipse.jdt.internal.corext.refactoring.code.ExtractConstantRefactoring)1 ExtractTempRefactoring (org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring)1 SurroundWithTryCatchRefactoring (org.eclipse.jdt.internal.corext.refactoring.surround.SurroundWithTryCatchRefactoring)1