Search in sources :

Example 31 with CatchClause

use of org.eclipse.jdt.core.dom.CatchClause in project evosuite by EvoSuite.

the class ResolutionMarkerTryBlock method run.

@Override
public void run(IMarker marker) {
    // TODO Auto-generated method stub
    IResource res = marker.getResource();
    try {
        String markerMessage = (String) marker.getAttribute(IMarker.MESSAGE);
        String exception = markerMessage.split(" ")[0];
        String[] exceptionPackageArray = exception.split("\\.");
        String exceptionPackage = "";
        for (int i = 0; i < exceptionPackageArray.length - 1; i++) {
            exceptionPackage += exceptionPackageArray[i] + ".";
        }
        exception = exception.substring(exceptionPackage.length());
        System.out.println("Package: " + exceptionPackage + ", Exception: " + exception);
        ICompilationUnit icomp = CompilationUnitManager.getICompilationUnit(res);
        CompilationUnit compunit = CompilationUnitManager.getCompilationUnit(res);
        int position = marker.getAttribute(IMarker.CHAR_START, 0) + 1;
        int line = marker.getAttribute(IMarker.LINE_NUMBER, 0);
        if (position == 1) {
            position = compunit.getPosition(line, 0);
        }
        AST ast = compunit.getAST();
        ASTRewrite rewriter = ASTRewrite.create(ast);
        IJavaElement element = icomp.getElementAt(position);
        IJavaElement method = getMethod(element);
        // TypeDeclaration td = (TypeDeclaration) compunit.types().get(0);
        TypeDeclaration td = (TypeDeclaration) compunit.types().get(0);
        MethodDeclaration md = td.getMethods()[0];
        int counter = 1;
        while (!md.getName().getFullyQualifiedName().equals(method.getElementName()) && counter < td.getMethods().length) {
            md = td.getMethods()[counter];
            System.out.println(md.getName().getFullyQualifiedName() + " " + method.getElementName());
            counter++;
        }
        Block block = md.getBody();
        ListRewrite lr = rewriter.getListRewrite(block, Block.STATEMENTS_PROPERTY);
        ImportDeclaration id = ast.newImportDeclaration();
        id.setName(ast.newName(exceptionPackage + exception));
        ListRewrite lrClass = rewriter.getListRewrite(compunit, CompilationUnit.TYPES_PROPERTY);
        lrClass.insertAt(id, 0, null);
        ASTNode currentNode = null;
        List<ASTNode> list = new ArrayList<ASTNode>();
        for (Object o : lr.getOriginalList()) {
            if (o instanceof ASTNode) {
                list.add((ASTNode) o);
            }
        }
        for (int i = 0; i < list.size(); i++) {
            ASTNode node = list.get(i);
            int nodeLine = compunit.getLineNumber(node.getStartPosition());
            System.out.println(line + " " + nodeLine);
            if (line == nodeLine) {
                currentNode = node;
                break;
            }
            List childrenList = node.structuralPropertiesForType();
            for (int j = 0; j < childrenList.size(); j++) {
                StructuralPropertyDescriptor curr = (StructuralPropertyDescriptor) childrenList.get(j);
                Object child = node.getStructuralProperty(curr);
                if (child instanceof List) {
                    for (Object ob : (List) child) {
                        if (ob instanceof ASTNode) {
                            list.add((ASTNode) ob);
                        }
                    }
                } else if (child instanceof ASTNode) {
                    list.add((ASTNode) child);
                }
            }
        }
        TryStatement ts = ast.newTryStatement();
        Statement emptyStatement = (Statement) rewriter.createStringPlaceholder("\n", ASTNode.EMPTY_STATEMENT);
        Statement emptyStatement2 = (Statement) rewriter.createStringPlaceholder("\n\t", ASTNode.EMPTY_STATEMENT);
        Block b2 = ast.newBlock();
        b2.statements().add(0, ASTNode.copySubtree(b2.getAST(), currentNode));
        b2.statements().add(1, emptyStatement);
        b2.statements().add(0, emptyStatement2);
        ts.setBody(b2);
        CatchClause cc = ast.newCatchClause();
        SingleVariableDeclaration svd = ast.newSingleVariableDeclaration();
        svd.setName(ast.newSimpleName("e"));
        Type type = ast.newSimpleType(ast.newName(exception));
        svd.setType(type);
        cc.setException(svd);
        Block b3 = ast.newBlock();
        Statement printStatement = (Statement) rewriter.createStringPlaceholder("e.printStackTrace();", ASTNode.EMPTY_STATEMENT);
        b3.statements().add(0, printStatement);
        cc.setBody(b3);
        ListRewrite parentList = rewriter.getListRewrite(currentNode.getParent(), Block.STATEMENTS_PROPERTY);
        parentList.replace(currentNode, ts, null);
        parentList.insertAfter(cc, ts, null);
        ITextFileBufferManager bm = FileBuffers.getTextFileBufferManager();
        IPath path = compunit.getJavaElement().getPath();
        try {
            bm.connect(path, null, null);
            ITextFileBuffer textFileBuffer = bm.getTextFileBuffer(path, null);
            IDocument document = textFileBuffer.getDocument();
            TextEdit edits = rewriter.rewriteAST(document, null);
            edits.apply(document);
            textFileBuffer.commit(null, false);
        } catch (CoreException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MalformedTreeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadLocationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                bm.disconnect(path, null, null);
            } catch (CoreException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        // (4)
        }
        marker.delete();
    } catch (JavaModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CoreException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}
Also used : JavaModelException(org.eclipse.jdt.core.JavaModelException) ArrayList(java.util.ArrayList) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) TryStatement(org.eclipse.jdt.core.dom.TryStatement) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) ArrayList(java.util.ArrayList) List(java.util.List) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IJavaElement(org.eclipse.jdt.core.IJavaElement) AST(org.eclipse.jdt.core.dom.AST) IPath(org.eclipse.core.runtime.IPath) ITextFileBufferManager(org.eclipse.core.filebuffers.ITextFileBufferManager) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) TryStatement(org.eclipse.jdt.core.dom.TryStatement) Statement(org.eclipse.jdt.core.dom.Statement) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) MalformedTreeException(org.eclipse.text.edits.MalformedTreeException) CatchClause(org.eclipse.jdt.core.dom.CatchClause) IOException(java.io.IOException) Type(org.eclipse.jdt.core.dom.Type) CoreException(org.eclipse.core.runtime.CoreException) TextEdit(org.eclipse.text.edits.TextEdit) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) ITextFileBuffer(org.eclipse.core.filebuffers.ITextFileBuffer) Block(org.eclipse.jdt.core.dom.Block) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration) IResource(org.eclipse.core.resources.IResource) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException) StructuralPropertyDescriptor(org.eclipse.jdt.core.dom.StructuralPropertyDescriptor)

Example 32 with CatchClause

use of org.eclipse.jdt.core.dom.CatchClause in project eclipse.jdt.ls by eclipse.

the class QuickAssistProcessor method getCatchClauseToThrowsProposals.

public static boolean getCatchClauseToThrowsProposals(IInvocationContext context, ASTNode node, Collection<ChangeCorrectionProposal> resultingCollections) {
    if (resultingCollections == null) {
        return true;
    }
    CatchClause catchClause = (CatchClause) ASTResolving.findAncestor(node, ASTNode.CATCH_CLAUSE);
    if (catchClause == null) {
        return false;
    }
    Statement statement = ASTResolving.findParentStatement(node);
    if (statement != catchClause.getParent() && statement != catchClause.getBody()) {
        // selection is in a statement inside the body
        return false;
    }
    Type type = catchClause.getException().getType();
    if (!type.isSimpleType() && !type.isUnionType() && !type.isNameQualifiedType()) {
        return false;
    }
    BodyDeclaration bodyDeclaration = ASTResolving.findParentBodyDeclaration(catchClause);
    if (!(bodyDeclaration instanceof MethodDeclaration) && !(bodyDeclaration instanceof Initializer)) {
        return false;
    }
    AST ast = bodyDeclaration.getAST();
    Type selectedMultiCatchType = null;
    if (type.isUnionType() && node instanceof Name) {
        Name topMostName = ASTNodes.getTopMostName((Name) node);
        ASTNode parent = topMostName.getParent();
        if (parent instanceof SimpleType) {
            selectedMultiCatchType = (SimpleType) parent;
        } else if (parent instanceof NameQualifiedType) {
            selectedMultiCatchType = (NameQualifiedType) parent;
        }
    }
    if (bodyDeclaration instanceof MethodDeclaration) {
        MethodDeclaration methodDeclaration = (MethodDeclaration) bodyDeclaration;
        ASTRewrite rewrite = ASTRewrite.create(ast);
        if (selectedMultiCatchType != null) {
            removeException(rewrite, (UnionType) type, selectedMultiCatchType);
            addExceptionToThrows(ast, methodDeclaration, rewrite, selectedMultiCatchType);
            String label = CorrectionMessages.QuickAssistProcessor_exceptiontothrows_description;
            ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(), rewrite, IProposalRelevance.REPLACE_EXCEPTION_WITH_THROWS);
            resultingCollections.add(proposal);
        } else {
            removeCatchBlock(rewrite, catchClause);
            if (type.isUnionType()) {
                UnionType unionType = (UnionType) type;
                List<Type> types = unionType.types();
                for (Type elementType : types) {
                    if (!(elementType instanceof SimpleType || elementType instanceof NameQualifiedType)) {
                        return false;
                    }
                    addExceptionToThrows(ast, methodDeclaration, rewrite, elementType);
                }
            } else {
                addExceptionToThrows(ast, methodDeclaration, rewrite, type);
            }
            String label = CorrectionMessages.QuickAssistProcessor_catchclausetothrows_description;
            ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(), rewrite, IProposalRelevance.REPLACE_CATCH_CLAUSE_WITH_THROWS);
            resultingCollections.add(proposal);
        }
    }
    {
        // for initializers or method declarations
        ASTRewrite rewrite = ASTRewrite.create(ast);
        if (selectedMultiCatchType != null) {
            removeException(rewrite, (UnionType) type, selectedMultiCatchType);
            String label = CorrectionMessages.QuickAssistProcessor_removeexception_description;
            ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_EXCEPTION);
            resultingCollections.add(proposal);
        } else {
            removeCatchBlock(rewrite, catchClause);
            String label = CorrectionMessages.QuickAssistProcessor_removecatchclause_description;
            ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_CATCH_CLAUSE);
            resultingCollections.add(proposal);
        }
    }
    return true;
}
Also used : UnionType(org.eclipse.jdt.core.dom.UnionType) AST(org.eclipse.jdt.core.dom.AST) Statement(org.eclipse.jdt.core.dom.Statement) ThrowStatement(org.eclipse.jdt.core.dom.ThrowStatement) SwitchStatement(org.eclipse.jdt.core.dom.SwitchStatement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) TryStatement(org.eclipse.jdt.core.dom.TryStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) CatchClause(org.eclipse.jdt.core.dom.CatchClause) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Name(org.eclipse.jdt.core.dom.Name) ASTRewriteCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.ASTRewriteCorrectionProposal) SimpleType(org.eclipse.jdt.core.dom.SimpleType) UnionType(org.eclipse.jdt.core.dom.UnionType) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) QualifiedType(org.eclipse.jdt.core.dom.QualifiedType) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType) ArrayType(org.eclipse.jdt.core.dom.ArrayType) SimpleType(org.eclipse.jdt.core.dom.SimpleType) Type(org.eclipse.jdt.core.dom.Type) Initializer(org.eclipse.jdt.core.dom.Initializer) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType)

Aggregations

CatchClause (org.eclipse.jdt.core.dom.CatchClause)32 TryStatement (org.eclipse.jdt.core.dom.TryStatement)15 SingleVariableDeclaration (org.eclipse.jdt.core.dom.SingleVariableDeclaration)14 ASTNode (org.eclipse.jdt.core.dom.ASTNode)13 ArrayList (java.util.ArrayList)12 Statement (org.eclipse.jdt.core.dom.Statement)10 AST (org.eclipse.jdt.core.dom.AST)9 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)9 Type (org.eclipse.jdt.core.dom.Type)9 UnionType (org.eclipse.jdt.core.dom.UnionType)9 Block (org.eclipse.jdt.core.dom.Block)8 ExpressionStatement (org.eclipse.jdt.core.dom.ExpressionStatement)8 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)6 BodyDeclaration (org.eclipse.jdt.core.dom.BodyDeclaration)6 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)6 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)6 SwitchStatement (org.eclipse.jdt.core.dom.SwitchStatement)6 VariableDeclarationExpression (org.eclipse.jdt.core.dom.VariableDeclarationExpression)6 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)6 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)6