Search in sources :

Example 21 with TryStatement

use of org.eclipse.jdt.core.dom.TryStatement in project AutoRefactor by JnRouvignac.

the class InlineCodeRatherThanPeremptoryConditionCleanUp method removeForwardCode.

private void removeForwardCode(final Statement statement, final Statement unconditionnalStatement) {
    if (ASTNodes.canHaveSiblings(statement)) {
        TextEditGroup group = new TextEditGroup(MultiFixMessages.InlineCodeRatherThanPeremptoryConditionCleanUp_description);
        ASTRewrite rewrite = cuRewrite.getASTRewrite();
        rewrite.remove(ASTNodes.getNextSiblings(statement), group);
        removeForwardCode((Block) statement.getParent(), unconditionnalStatement);
    } else if (statement.getParent() instanceof TryStatement) {
        removeForwardCode((TryStatement) statement.getParent(), unconditionnalStatement);
    }
}
Also used : TryStatement(org.eclipse.jdt.core.dom.TryStatement) ASTRewrite(org.autorefactor.jdt.core.dom.ASTRewrite) TextEditGroup(org.eclipse.text.edits.TextEditGroup)

Example 22 with TryStatement

use of org.eclipse.jdt.core.dom.TryStatement in project AutoRefactor by JnRouvignac.

the class ASTNodes method fallsThrough.

/**
 * Return true if the statement falls through.
 *
 * @param statement the statement
 * @return true if the statement falls through.
 */
public static boolean fallsThrough(final Statement statement) {
    List<Statement> statements = asList(statement);
    if (statements.isEmpty()) {
        return false;
    }
    Statement lastStatement = statements.get(statements.size() - 1);
    switch(lastStatement.getNodeType()) {
        case ASTNode.RETURN_STATEMENT:
        case ASTNode.THROW_STATEMENT:
        case ASTNode.BREAK_STATEMENT:
        case ASTNode.CONTINUE_STATEMENT:
            return true;
        case ASTNode.BLOCK:
            Block block = (Block) lastStatement;
            return fallsThrough(block);
        case ASTNode.IF_STATEMENT:
            IfStatement ifStatement = (IfStatement) lastStatement;
            Statement thenStatement = ifStatement.getThenStatement();
            Statement elseStatement = ifStatement.getElseStatement();
            return fallsThrough(thenStatement) && fallsThrough(elseStatement);
        case ASTNode.TRY_STATEMENT:
            TryStatement tryStatement = (TryStatement) lastStatement;
            if (!fallsThrough(tryStatement.getBody()) || tryStatement.getFinally() != null && !fallsThrough(tryStatement.getFinally())) {
                return false;
            }
            if (tryStatement.catchClauses() != null) {
                for (Object catchClause : tryStatement.catchClauses()) {
                    if (!fallsThrough(((CatchClause) catchClause).getBody())) {
                        return false;
                    }
                }
            }
            return true;
        default:
            return false;
    }
}
Also used : IfStatement(org.eclipse.jdt.core.dom.IfStatement) TryStatement(org.eclipse.jdt.core.dom.TryStatement) DoStatement(org.eclipse.jdt.core.dom.DoStatement) Statement(org.eclipse.jdt.core.dom.Statement) ThrowStatement(org.eclipse.jdt.core.dom.ThrowStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) TryStatement(org.eclipse.jdt.core.dom.TryStatement) SwitchStatement(org.eclipse.jdt.core.dom.SwitchStatement) IfStatement(org.eclipse.jdt.core.dom.IfStatement) WhileStatement(org.eclipse.jdt.core.dom.WhileStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) LabeledStatement(org.eclipse.jdt.core.dom.LabeledStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) Block(org.eclipse.jdt.core.dom.Block) CatchClause(org.eclipse.jdt.core.dom.CatchClause)

Example 23 with TryStatement

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

the class CodeGenerator method createTryStatementForPostProcessing.

/*
	 * try
	 * {
	 *    var0.doSth();
	 * }
	 * catch(Throwable t)
	 * {
	 *    org.uni.saarland.sw.prototype.capture.PostProcessor.captureException(<logRecNo>);
	 * }
	 */
@SuppressWarnings("unchecked")
private TryStatement createTryStatementForPostProcessing(final AST ast, final Statement stmt, final int logRecNo) {
    final TryStatement tryStmt = this.createTryStmtWithEmptyCatch(ast, stmt);
    final CatchClause cc = (CatchClause) tryStmt.catchClauses().get(0);
    final MethodInvocation m = ast.newMethodInvocation();
    m.setExpression(ast.newName(new String[] { "de", "unisb", "cs", "st", "testcarver", "capture", "PostProcessor" }));
    m.setName(ast.newSimpleName("captureException"));
    m.arguments().add(ast.newNumberLiteral(String.valueOf(logRecNo)));
    cc.getBody().statements().add(ast.newExpressionStatement(m));
    MethodInvocation m2 = ast.newMethodInvocation();
    m2.setExpression(ast.newSimpleName("t"));
    m2.setName(ast.newSimpleName("printStackTrace"));
    cc.getBody().statements().add(ast.newExpressionStatement(m2));
    return tryStmt;
}
Also used : TryStatement(org.eclipse.jdt.core.dom.TryStatement) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) CatchClause(org.eclipse.jdt.core.dom.CatchClause)

Example 24 with TryStatement

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

the class CodeGenerator method createTryStmtWithEmptyCatch.

/*
	 * Needed to preserve program flow: 
	 * 
	 * try
	 * {
	 *    var0.doSth();
	 * }
	 * catch(Throwable t) {}
	 */
@SuppressWarnings("unchecked")
private TryStatement createTryStmtWithEmptyCatch(final AST ast, Statement stmt) {
    final TryStatement tryStmt = ast.newTryStatement();
    tryStmt.getBody().statements().add(stmt);
    final CatchClause cc = ast.newCatchClause();
    SingleVariableDeclaration excDecl = ast.newSingleVariableDeclaration();
    excDecl.setType(ast.newSimpleType(ast.newSimpleName("Throwable")));
    excDecl.setName(ast.newSimpleName("t"));
    cc.setException(excDecl);
    tryStmt.catchClauses().add(cc);
    return tryStmt;
}
Also used : TryStatement(org.eclipse.jdt.core.dom.TryStatement) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) CatchClause(org.eclipse.jdt.core.dom.CatchClause)

Example 25 with TryStatement

use of org.eclipse.jdt.core.dom.TryStatement 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)

Aggregations

TryStatement (org.eclipse.jdt.core.dom.TryStatement)25 Statement (org.eclipse.jdt.core.dom.Statement)12 CatchClause (org.eclipse.jdt.core.dom.CatchClause)11 ASTNode (org.eclipse.jdt.core.dom.ASTNode)10 Block (org.eclipse.jdt.core.dom.Block)8 ArrayList (java.util.ArrayList)7 ExpressionStatement (org.eclipse.jdt.core.dom.ExpressionStatement)7 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)7 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)7 IfStatement (org.eclipse.jdt.core.dom.IfStatement)6 ReturnStatement (org.eclipse.jdt.core.dom.ReturnStatement)6 SingleVariableDeclaration (org.eclipse.jdt.core.dom.SingleVariableDeclaration)6 Type (org.eclipse.jdt.core.dom.Type)6 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)6 ForStatement (org.eclipse.jdt.core.dom.ForStatement)5 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)5 List (java.util.List)4 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)4 AST (org.eclipse.jdt.core.dom.AST)4 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)4