Search in sources :

Example 11 with ChangeCorrectionProposal

use of org.eclipse.jdt.ui.text.java.correction.ChangeCorrectionProposal in project che by eclipse.

the class LocalCorrectionsSubProcessor method addTypePrametersToRawTypeReference.

public static void addTypePrametersToRawTypeReference(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
    IProposableFix fix = Java50Fix.createRawTypeReferenceFix(context.getASTRoot(), problem);
    if (fix != null) {
        for (Iterator<ICommandAccess> iter = proposals.iterator(); iter.hasNext(); ) {
            Object element = iter.next();
            if (element instanceof FixCorrectionProposal) {
                FixCorrectionProposal fixProp = (FixCorrectionProposal) element;
                if (RAW_TYPE_REFERENCE_ID.equals(fixProp.getCommandId())) {
                    return;
                }
            }
        }
        Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
        Map<String, String> options = new Hashtable<String, String>();
        options.put(CleanUpConstants.VARIABLE_DECLARATION_USE_TYPE_ARGUMENTS_FOR_RAW_TYPE_REFERENCES, CleanUpOptions.TRUE);
        FixCorrectionProposal proposal = new FixCorrectionProposal(fix, new Java50CleanUp(options), IProposalRelevance.RAW_TYPE_REFERENCE, image, context);
        proposal.setCommandId(RAW_TYPE_REFERENCE_ID);
        proposals.add(proposal);
    }
    //Infer Generic Type Arguments... proposal
    boolean hasInferTypeArgumentsProposal = false;
    for (Iterator<ICommandAccess> iterator = proposals.iterator(); iterator.hasNext(); ) {
        Object completionProposal = iterator.next();
        if (completionProposal instanceof ChangeCorrectionProposal) {
            if (IJavaEditorActionDefinitionIds.INFER_TYPE_ARGUMENTS_ACTION.equals(((ChangeCorrectionProposal) completionProposal).getCommandId())) {
                hasInferTypeArgumentsProposal = true;
                break;
            }
        }
    }
    if (!hasInferTypeArgumentsProposal) {
        final ICompilationUnit cu = context.getCompilationUnit();
        ChangeCorrectionProposal proposal = new ChangeCorrectionProposal(CorrectionMessages.LocalCorrectionsSubProcessor_InferGenericTypeArguments, null, IProposalRelevance.INFER_GENERIC_TYPE_ARGUMENTS, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE)) {

            @Override
            public void apply(IDocument document) {
                //							action.run(new StructuredSelection(cu));
                throw new UnsupportedOperationException();
            }

            @Override
            public String getActionId() {
                return "javaInferTypeArguments";
            }

            /**
						 * {@inheritDoc}
						 */
            @Override
            public Object getAdditionalProposalInfo(IProgressMonitor monitor) {
                return CorrectionMessages.LocalCorrectionsSubProcessor_InferGenericTypeArguments_description;
            }
        };
        proposal.setCommandId(IJavaEditorActionDefinitionIds.INFER_TYPE_ARGUMENTS_ACTION);
        proposals.add(proposal);
    }
    addTypeArgumentsFromContext(context, problem, proposals);
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) ICommandAccess(org.eclipse.jdt.ui.text.java.correction.ICommandAccess) Hashtable(java.util.Hashtable) IProposableFix(org.eclipse.jdt.internal.corext.fix.IProposableFix) Image(org.eclipse.swt.graphics.Image) ChangeCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ChangeCorrectionProposal) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) FixCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.FixCorrectionProposal) Java50CleanUp(org.eclipse.jdt.internal.ui.fix.Java50CleanUp) IDocument(org.eclipse.jface.text.IDocument)

Example 12 with ChangeCorrectionProposal

use of org.eclipse.jdt.ui.text.java.correction.ChangeCorrectionProposal in project che by eclipse.

the class LocalCorrectionsSubProcessor method addMissingHashCodeProposals.

public static void addMissingHashCodeProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
    final ICompilationUnit cu = context.getCompilationUnit();
    CompilationUnit astRoot = context.getASTRoot();
    ASTNode selectedNode = problem.getCoveringNode(astRoot);
    if (!(selectedNode instanceof Name)) {
        return;
    }
    AbstractTypeDeclaration typeDeclaration = null;
    StructuralPropertyDescriptor locationInParent = selectedNode.getLocationInParent();
    if (locationInParent != TypeDeclaration.NAME_PROPERTY && locationInParent != EnumDeclaration.NAME_PROPERTY) {
        return;
    }
    typeDeclaration = (AbstractTypeDeclaration) selectedNode.getParent();
    ITypeBinding binding = typeDeclaration.resolveBinding();
    if (binding == null || binding.getSuperclass() == null) {
        return;
    }
    final IType type = (IType) binding.getJavaElement();
    boolean hasInstanceFields = false;
    IVariableBinding[] declaredFields = binding.getDeclaredFields();
    for (int i = 0; i < declaredFields.length; i++) {
        if (!Modifier.isStatic(declaredFields[i].getModifiers())) {
            hasInstanceFields = true;
            break;
        }
    }
    if (hasInstanceFields) {
        //Generate hashCode() and equals()... proposal
        String label = CorrectionMessages.LocalCorrectionsSubProcessor_generate_hashCode_equals_description;
        Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
        ChangeCorrectionProposal proposal = new ChangeCorrectionProposal(label, null, IProposalRelevance.GENERATE_HASHCODE_AND_EQUALS, image) {

            @Override
            public void apply(IDocument document) {
                // should never happened
                throw new UnsupportedOperationException();
            }

            @Override
            public Object getAdditionalProposalInfo(IProgressMonitor monitor) {
                return CorrectionMessages.LocalCorrectionsSubProcessor_generate_hashCode_equals_additional_info;
            }

            @Override
            public String getActionId() {
                return "javaGenerateHashCodeEquals";
            }
        };
        proposals.add(proposal);
    }
    //Override hashCode() proposal
    //$NON-NLS-1$
    IMethodBinding superHashCode = Bindings.findMethodInHierarchy(binding, "hashCode", new ITypeBinding[0]);
    if (superHashCode == null) {
        return;
    }
    String label = CorrectionMessages.LocalCorrectionsSubProcessor_override_hashCode_description;
    Image image = JavaPluginImages.get(JavaPluginImages.DESC_MISC_PUBLIC);
    ASTRewrite rewrite = ASTRewrite.create(astRoot.getAST());
    LinkedCorrectionProposal proposal2 = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.OVERRIDE_HASHCODE, image);
    ImportRewrite importRewrite = proposal2.createImportRewrite(astRoot);
    String typeQualifiedName = type.getTypeQualifiedName('.');
    final CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(cu.getJavaProject());
    try {
        ImportRewriteContext importContext = new ContextSensitiveImportRewriteContext(astRoot, problem.getOffset(), importRewrite);
        MethodDeclaration hashCode = StubUtility2.createImplementationStub(cu, rewrite, importRewrite, importContext, superHashCode, typeQualifiedName, settings, false);
        BodyDeclarationRewrite.create(rewrite, typeDeclaration).insert(hashCode, null);
        proposal2.setEndPosition(rewrite.track(hashCode));
    } catch (CoreException e) {
        JavaPlugin.log(e);
    }
    proposals.add(proposal2);
}
Also used : ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) CodeGenerationSettings(org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings) Image(org.eclipse.swt.graphics.Image) ChangeCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ChangeCorrectionProposal) IType(org.eclipse.jdt.core.IType) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) CoreException(org.eclipse.core.runtime.CoreException) LinkedCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal) IDocument(org.eclipse.jface.text.IDocument)

Example 13 with ChangeCorrectionProposal

use of org.eclipse.jdt.ui.text.java.correction.ChangeCorrectionProposal in project che by eclipse.

the class GetterSetterCorrectionSubProcessor method addGetterSetterProposal.

private static boolean addGetterSetterProposal(IInvocationContext context, ASTNode coveringNode, Collection<ICommandAccess> proposals, int relevance) {
    if (!(coveringNode instanceof SimpleName)) {
        return false;
    }
    SimpleName sn = (SimpleName) coveringNode;
    IBinding binding = sn.resolveBinding();
    if (!(binding instanceof IVariableBinding))
        return false;
    IVariableBinding variableBinding = (IVariableBinding) binding;
    if (!variableBinding.isField())
        return false;
    if (proposals == null)
        return true;
    ChangeCorrectionProposal proposal = getProposal(context.getCompilationUnit(), sn, variableBinding, relevance);
    if (proposal != null)
        proposals.add(proposal);
    return true;
}
Also used : SimpleName(org.eclipse.jdt.core.dom.SimpleName) IBinding(org.eclipse.jdt.core.dom.IBinding) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) ChangeCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ChangeCorrectionProposal)

Example 14 with ChangeCorrectionProposal

use of org.eclipse.jdt.ui.text.java.correction.ChangeCorrectionProposal in project che by eclipse.

the class ReorgQuickFixTest method testWrongTypeName.

@Test
public void testWrongTypeName() throws Exception {
    IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);
    StringBuffer buf = new StringBuffer();
    buf.append("package test1;\n");
    buf.append("\n");
    buf.append("public class E {\n");
    buf.append("}\n");
    ICompilationUnit cu = pack1.createCompilationUnit("X.java", buf.toString(), false, null);
    CompilationUnit astRoot = getASTRoot(cu);
    ArrayList proposals = collectCorrections(cu, astRoot);
    assertNumberOfProposals(proposals, 2);
    assertCorrectLabels(proposals);
    boolean hasRename = true, hasMove = true;
    for (int i = 0; i < proposals.size(); i++) {
        ChangeCorrectionProposal curr = (ChangeCorrectionProposal) proposals.get(i);
        if (curr instanceof CorrectMainTypeNameProposal) {
            assertTrue("Duplicated proposal", hasRename);
            hasRename = false;
            CUCorrectionProposal proposal = (CUCorrectionProposal) curr;
            String preview = getPreviewContent(proposal);
            buf = new StringBuffer();
            buf.append("package test1;\n");
            buf.append("\n");
            buf.append("public class X {\n");
            buf.append("}\n");
            assertEqualString(preview, buf.toString());
        } else {
            assertTrue("Duplicated proposal", hasMove);
            hasMove = false;
            curr.apply(null);
            ICompilationUnit cu2 = pack1.getCompilationUnit("E.java");
            assertTrue("CU does not exist", cu2.exists());
            buf = new StringBuffer();
            buf.append("package test1;\n");
            buf.append("\n");
            buf.append("public class E {\n");
            buf.append("}\n");
            assertEqualStringIgnoreDelim(cu2.getSource(), buf.toString());
        }
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) CUCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.CUCorrectionProposal) ArrayList(java.util.ArrayList) CorrectMainTypeNameProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.CorrectMainTypeNameProposal) ChangeCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ChangeCorrectionProposal) Test(org.junit.Test)

Example 15 with ChangeCorrectionProposal

use of org.eclipse.jdt.ui.text.java.correction.ChangeCorrectionProposal in project flux by eclipse.

the class QuickAssistProcessor method getSplitVariableProposals.

private static boolean getSplitVariableProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
    VariableDeclarationFragment fragment;
    if (node instanceof VariableDeclarationFragment) {
        fragment = (VariableDeclarationFragment) node;
    } else if (node.getLocationInParent() == VariableDeclarationFragment.NAME_PROPERTY) {
        fragment = (VariableDeclarationFragment) node.getParent();
    } else {
        return false;
    }
    if (fragment.getInitializer() == null) {
        return false;
    }
    Statement statement;
    ASTNode fragParent = fragment.getParent();
    if (fragParent instanceof VariableDeclarationStatement) {
        statement = (VariableDeclarationStatement) fragParent;
    } else if (fragParent instanceof VariableDeclarationExpression) {
        if (fragParent.getLocationInParent() == TryStatement.RESOURCES_PROPERTY) {
            return false;
        }
        statement = (Statement) fragParent.getParent();
    } else {
        return false;
    }
    // statement is ForStatement or VariableDeclarationStatement
    ASTNode statementParent = statement.getParent();
    StructuralPropertyDescriptor property = statement.getLocationInParent();
    if (!property.isChildListProperty()) {
        return false;
    }
    List<? extends ASTNode> list = ASTNodes.getChildListProperty(statementParent, (ChildListPropertyDescriptor) property);
    if (resultingCollections == null) {
        return true;
    }
    AST ast = statement.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    String label = CorrectionMessages.QuickAssistProcessor_splitdeclaration_description;
    //		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
    ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.SPLIT_VARIABLE_DECLARATION);
    boolean commandConflict = false;
    for (Iterator<ICommandAccess> iterator = resultingCollections.iterator(); iterator.hasNext(); ) {
        Object completionProposal = iterator.next();
        if (completionProposal instanceof ChangeCorrectionProposal) {
            if (SPLIT_JOIN_VARIABLE_DECLARATION_ID.equals(((ChangeCorrectionProposal) completionProposal).getCommandId())) {
                commandConflict = true;
            }
        }
    }
    if (!commandConflict) {
        proposal.setCommandId(SPLIT_JOIN_VARIABLE_DECLARATION_ID);
    }
    Statement newStatement;
    int insertIndex = list.indexOf(statement);
    Expression placeholder = (Expression) rewrite.createMoveTarget(fragment.getInitializer());
    ITypeBinding binding = fragment.getInitializer().resolveTypeBinding();
    if (placeholder instanceof ArrayInitializer && binding != null && binding.isArray()) {
        ArrayCreation creation = ast.newArrayCreation();
        creation.setInitializer((ArrayInitializer) placeholder);
        final ITypeBinding componentType = binding.getElementType();
        Type type = null;
        if (componentType.isPrimitive())
            type = ast.newPrimitiveType(PrimitiveType.toCode(componentType.getName()));
        else
            type = ast.newSimpleType(ast.newSimpleName(componentType.getName()));
        creation.setType(ast.newArrayType(type, binding.getDimensions()));
        placeholder = creation;
    }
    Assignment assignment = ast.newAssignment();
    assignment.setRightHandSide(placeholder);
    assignment.setLeftHandSide(ast.newSimpleName(fragment.getName().getIdentifier()));
    if (statement instanceof VariableDeclarationStatement) {
        newStatement = ast.newExpressionStatement(assignment);
        // add after declaration
        insertIndex += 1;
    } else {
        rewrite.replace(fragment.getParent(), assignment, null);
        VariableDeclarationFragment newFrag = ast.newVariableDeclarationFragment();
        newFrag.setName(ast.newSimpleName(fragment.getName().getIdentifier()));
        newFrag.extraDimensions().addAll(DimensionRewrite.copyDimensions(fragment.extraDimensions(), rewrite));
        VariableDeclarationExpression oldVarDecl = (VariableDeclarationExpression) fragParent;
        VariableDeclarationStatement newVarDec = ast.newVariableDeclarationStatement(newFrag);
        newVarDec.setType((Type) rewrite.createCopyTarget(oldVarDecl.getType()));
        newVarDec.modifiers().addAll(ASTNodeFactory.newModifiers(ast, oldVarDecl.getModifiers()));
        newStatement = newVarDec;
    }
    ListRewrite listRewriter = rewrite.getListRewrite(statementParent, (ChildListPropertyDescriptor) property);
    listRewriter.insertAt(newStatement, insertIndex, null);
    resultingCollections.add(proposal);
    return true;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) DoStatement(org.eclipse.jdt.core.dom.DoStatement) Statement(org.eclipse.jdt.core.dom.Statement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) TryStatement(org.eclipse.jdt.core.dom.TryStatement) IfStatement(org.eclipse.jdt.core.dom.IfStatement) WhileStatement(org.eclipse.jdt.core.dom.WhileStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) ICommandAccess(org.eclipse.jdt.ui.text.java.correction.ICommandAccess) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) ChangeCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ChangeCorrectionProposal) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) Assignment(org.eclipse.jdt.core.dom.Assignment) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType) IType(org.eclipse.jdt.core.IType) UnionType(org.eclipse.jdt.core.dom.UnionType) ArrayType(org.eclipse.jdt.core.dom.ArrayType) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) SimpleType(org.eclipse.jdt.core.dom.SimpleType) Type(org.eclipse.jdt.core.dom.Type) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) ConditionalExpression(org.eclipse.jdt.core.dom.ConditionalExpression) ThisExpression(org.eclipse.jdt.core.dom.ThisExpression) Expression(org.eclipse.jdt.core.dom.Expression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) CastExpression(org.eclipse.jdt.core.dom.CastExpression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) PostfixExpression(org.eclipse.jdt.core.dom.PostfixExpression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ArrayCreation(org.eclipse.jdt.core.dom.ArrayCreation) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) StructuralPropertyDescriptor(org.eclipse.jdt.core.dom.StructuralPropertyDescriptor) ArrayInitializer(org.eclipse.jdt.core.dom.ArrayInitializer)

Aggregations

ChangeCorrectionProposal (org.eclipse.jdt.ui.text.java.correction.ChangeCorrectionProposal)16 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)12 IPackageFragment (org.eclipse.jdt.core.IPackageFragment)8 ArrayList (java.util.ArrayList)7 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)7 CUCorrectionProposal (org.eclipse.jdt.ui.text.java.correction.CUCorrectionProposal)5 Test (org.junit.Test)5 CorrectPackageDeclarationProposal (org.eclipse.jdt.internal.ui.text.correction.proposals.CorrectPackageDeclarationProposal)4 ICommandAccess (org.eclipse.jdt.ui.text.java.correction.ICommandAccess)4 Image (org.eclipse.swt.graphics.Image)4 IType (org.eclipse.jdt.core.IType)3 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)3 IDocument (org.eclipse.jface.text.IDocument)3 Hashtable (java.util.Hashtable)2 IProgressMonitor (org.eclipse.core.runtime.IProgressMonitor)2 ASTNode (org.eclipse.jdt.core.dom.ASTNode)2 CorrectMainTypeNameProposal (org.eclipse.jdt.internal.ui.text.correction.proposals.CorrectMainTypeNameProposal)2 IMarker (org.eclipse.core.resources.IMarker)1 IResource (org.eclipse.core.resources.IResource)1 CoreException (org.eclipse.core.runtime.CoreException)1