Example usage for org.eclipse.jdt.core.dom AST newTryStatement

List of usage examples for org.eclipse.jdt.core.dom AST newTryStatement

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom AST newTryStatement.

Prototype

public TryStatement newTryStatement() 

Source Link

Document

Creates a new unparented try statement node owned by this AST.

Usage

From source file:com.idega.eclipse.ejbwizards.IDOEntityCreator.java

License:Open Source License

private void createHomeImplementation(IProgressMonitor monitor, ICompilationUnit iUnit, String typePackage,
        String name) throws JavaModelException, MalformedTreeException, BadLocationException {
    iUnit.getBuffer().setContents("");
    String source = iUnit.getBuffer().getContents();
    Document document = new Document(source);

    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(iUnit);/*  w w w .  j a  va 2  s.  c  om*/

    CompilationUnit unit = (CompilationUnit) parser.createAST(monitor);
    unit.recordModifications();

    AST ast = unit.getAST();

    // Package statement
    unit.setPackage(getPackageDeclaration(ast, typePackage));

    // class declaration
    TypeDeclaration classType = getTypeDeclaration(ast, name + "HomeImpl", false, "IDOFactory", null,
            getHomeImplImports());
    classType.superInterfaceTypes().add(ast.newSimpleType(ast.newSimpleName(name + "Home")));
    addHomeImplImport("com.idega.data.IDOFactory");
    unit.types().add(classType);

    // create() method
    MethodDeclaration methodConstructor = ast.newMethodDeclaration();
    methodConstructor.setConstructor(false);
    if (this.isJDK1_5) {
        MarkerAnnotation annotation = ast.newMarkerAnnotation();
        annotation.setTypeName(ast.newSimpleName("Override"));
        methodConstructor.modifiers().add(annotation);
    }
    methodConstructor.modifiers().addAll(ast.newModifiers(Modifier.PUBLIC));
    if (this.isJDK1_5) {
        ParameterizedType returnType = ast.newParameterizedType(ast.newSimpleType(ast.newSimpleName("Class")));
        returnType.typeArguments().add(ast.newSimpleType(ast.newSimpleName(name + "Home")));
        methodConstructor.setReturnType2(returnType);
    } else {
        methodConstructor.setReturnType2(ast.newSimpleType(ast.newSimpleName("Class")));
    }
    methodConstructor.setName(ast.newSimpleName("getEntityInterfaceClass"));

    classType.bodyDeclarations().add(methodConstructor);

    Block constructorBlock = ast.newBlock();
    methodConstructor.setBody(constructorBlock);

    TypeLiteral typeLiteral = ast.newTypeLiteral();
    typeLiteral.setType(ast.newSimpleType(ast.newSimpleName(name)));

    ReturnStatement returnStatement = ast.newReturnStatement();
    returnStatement.setExpression(typeLiteral);
    constructorBlock.statements().add(returnStatement);

    // create() method
    methodConstructor = ast.newMethodDeclaration();
    methodConstructor.setConstructor(false);
    methodConstructor.modifiers().addAll(ast.newModifiers(Modifier.PUBLIC));
    methodConstructor.setReturnType2(ast.newSimpleType(ast.newSimpleName(name)));
    methodConstructor.setName(ast.newSimpleName("create"));
    methodConstructor.thrownExceptions().add(ast.newName("CreateException"));
    addHomeImplImport("javax.ejb.CreateException");
    classType.bodyDeclarations().add(methodConstructor);

    constructorBlock = ast.newBlock();
    methodConstructor.setBody(constructorBlock);

    SuperMethodInvocation superMethodInvocation = ast.newSuperMethodInvocation();
    superMethodInvocation.setName(ast.newSimpleName("createIDO"));

    CastExpression ce = ast.newCastExpression();
    ce.setType(ast.newSimpleType(ast.newSimpleName(name)));
    ce.setExpression(superMethodInvocation);

    returnStatement = ast.newReturnStatement();
    returnStatement.setExpression(ce);
    constructorBlock.statements().add(returnStatement);

    // findByPrimarKey(Object) method
    methodConstructor = ast.newMethodDeclaration();
    methodConstructor.setConstructor(false);
    methodConstructor.modifiers().addAll(ast.newModifiers(Modifier.PUBLIC));
    methodConstructor.setReturnType2(ast.newSimpleType(ast.newSimpleName(name)));
    methodConstructor.setName(ast.newSimpleName("findByPrimaryKey"));
    methodConstructor.thrownExceptions().add(ast.newName("FinderException"));
    addHomeImplImport("javax.ejb.FinderException");
    classType.bodyDeclarations().add(methodConstructor);

    SingleVariableDeclaration variableDeclaration = ast.newSingleVariableDeclaration();
    variableDeclaration.modifiers().addAll(ast.newModifiers(Modifier.NONE));
    variableDeclaration.setType(ast.newSimpleType(ast.newSimpleName("Object")));
    variableDeclaration.setName(ast.newSimpleName("pk"));
    methodConstructor.parameters().add(variableDeclaration);

    constructorBlock = ast.newBlock();
    methodConstructor.setBody(constructorBlock);

    superMethodInvocation = ast.newSuperMethodInvocation();
    superMethodInvocation.setName(ast.newSimpleName("findByPrimaryKeyIDO"));
    superMethodInvocation.arguments().add(ast.newSimpleName("pk"));

    ce = ast.newCastExpression();
    ce.setType(ast.newSimpleType(ast.newSimpleName(name)));
    ce.setExpression(superMethodInvocation);

    returnStatement = ast.newReturnStatement();
    returnStatement.setExpression(ce);
    constructorBlock.statements().add(returnStatement);

    if (this.isLegacyEntity) {
        // createLegacy() method
        methodConstructor = ast.newMethodDeclaration();
        methodConstructor.setConstructor(false);
        methodConstructor.modifiers().addAll(ast.newModifiers(Modifier.PUBLIC));
        methodConstructor.setReturnType2(ast.newSimpleType(ast.newSimpleName(name)));
        methodConstructor.setName(ast.newSimpleName("createLegacy"));
        classType.bodyDeclarations().add(methodConstructor);

        constructorBlock = ast.newBlock();
        methodConstructor.setBody(constructorBlock);

        TryStatement tryStatement = ast.newTryStatement();
        constructorBlock.statements().add(tryStatement);
        Block tryBlock = ast.newBlock();
        tryStatement.setBody(tryBlock);

        MethodInvocation mi = ast.newMethodInvocation();
        mi.setName(ast.newSimpleName("create"));

        returnStatement = ast.newReturnStatement();
        returnStatement.setExpression(mi);
        tryBlock.statements().add(returnStatement);

        CatchClause catchClause = ast.newCatchClause();
        tryStatement.catchClauses().add(catchClause);
        variableDeclaration = ast.newSingleVariableDeclaration();
        variableDeclaration.modifiers().addAll(ast.newModifiers(Modifier.NONE));
        variableDeclaration.setType(ast.newSimpleType(ast.newSimpleName(("CreateException"))));
        variableDeclaration.setName(ast.newSimpleName("ce"));
        catchClause.setException(variableDeclaration);
        Block catchBlock = ast.newBlock();
        catchClause.setBody(catchBlock);

        ClassInstanceCreation cc = ast.newClassInstanceCreation();
        cc.setType(ast.newSimpleType(ast.newSimpleName("RuntimeException")));
        mi = ast.newMethodInvocation();
        mi.setExpression(ast.newSimpleName("ce"));
        mi.setName(ast.newSimpleName("getMessage"));
        cc.arguments().add(mi);

        ThrowStatement throwStatement = ast.newThrowStatement();
        throwStatement.setExpression(cc);
        catchBlock.statements().add(throwStatement);

        // findByPrimarKey(int) method
        methodConstructor = ast.newMethodDeclaration();
        methodConstructor.setConstructor(false);
        methodConstructor.modifiers().addAll(ast.newModifiers(Modifier.PUBLIC));
        methodConstructor.setReturnType2(ast.newSimpleType(ast.newSimpleName(name)));
        methodConstructor.setName(ast.newSimpleName("findByPrimaryKey"));
        methodConstructor.thrownExceptions().add(ast.newName("FinderException"));
        classType.bodyDeclarations().add(methodConstructor);

        variableDeclaration = ast.newSingleVariableDeclaration();
        variableDeclaration.modifiers().addAll(ast.newModifiers(Modifier.NONE));
        variableDeclaration.setType(ast.newPrimitiveType(PrimitiveType.INT));
        variableDeclaration.setName(ast.newSimpleName("id"));
        methodConstructor.parameters().add(variableDeclaration);

        constructorBlock = ast.newBlock();
        methodConstructor.setBody(constructorBlock);

        superMethodInvocation = ast.newSuperMethodInvocation();
        superMethodInvocation.setName(ast.newSimpleName("findByPrimaryKeyIDO"));
        superMethodInvocation.arguments().add(ast.newSimpleName("id"));

        ce = ast.newCastExpression();
        ce.setType(ast.newSimpleType(ast.newSimpleName(name)));
        ce.setExpression(superMethodInvocation);

        returnStatement = ast.newReturnStatement();
        returnStatement.setExpression(ce);
        constructorBlock.statements().add(returnStatement);

        // findByPrimarKeyLegacy(int) method
        methodConstructor = ast.newMethodDeclaration();
        methodConstructor.setConstructor(false);
        methodConstructor.modifiers().addAll(ast.newModifiers(Modifier.PUBLIC));
        methodConstructor.setReturnType2(ast.newSimpleType(ast.newSimpleName(name)));
        methodConstructor.setName(ast.newSimpleName("findByPrimaryKeyLegacy"));
        methodConstructor.thrownExceptions().add(ast.newName("SQLException"));
        addHomeImplImport("java.sql.SQLException");
        classType.bodyDeclarations().add(methodConstructor);

        variableDeclaration = ast.newSingleVariableDeclaration();
        variableDeclaration.modifiers().addAll(ast.newModifiers(Modifier.NONE));
        variableDeclaration.setType(ast.newPrimitiveType(PrimitiveType.INT));
        variableDeclaration.setName(ast.newSimpleName("id"));
        methodConstructor.parameters().add(variableDeclaration);

        constructorBlock = ast.newBlock();
        methodConstructor.setBody(constructorBlock);

        tryStatement = ast.newTryStatement();
        constructorBlock.statements().add(tryStatement);
        tryBlock = ast.newBlock();
        tryStatement.setBody(tryBlock);

        mi = ast.newMethodInvocation();
        mi.setName(ast.newSimpleName("findByPrimaryKey"));
        mi.arguments().add(ast.newSimpleName("id"));

        returnStatement = ast.newReturnStatement();
        returnStatement.setExpression(mi);
        tryBlock.statements().add(returnStatement);

        catchClause = ast.newCatchClause();
        tryStatement.catchClauses().add(catchClause);
        variableDeclaration = ast.newSingleVariableDeclaration();
        variableDeclaration.modifiers().addAll(ast.newModifiers(Modifier.NONE));
        variableDeclaration.setType(ast.newSimpleType(ast.newSimpleName(("FinderException"))));
        variableDeclaration.setName(ast.newSimpleName("fe"));
        catchClause.setException(variableDeclaration);
        catchBlock = ast.newBlock();
        catchClause.setBody(catchBlock);

        cc = ast.newClassInstanceCreation();
        cc.setType(ast.newSimpleType(ast.newSimpleName("SQLException")));
        mi = ast.newMethodInvocation();
        mi.setExpression(ast.newSimpleName("fe"));
        mi.setName(ast.newSimpleName("getMessage"));
        cc.arguments().add(mi);

        throwStatement = ast.newThrowStatement();
        throwStatement.setExpression(cc);
        catchBlock.statements().add(throwStatement);
    }

    MethodFilter[] validFilter = { new MethodFilter(WizardConstants.EJB_CREATE_START, MethodFilter.TYPE_PREFIX),
            new MethodFilter(WizardConstants.EJB_HOME_START, MethodFilter.TYPE_PREFIX),
            new MethodFilter(WizardConstants.EJB_FIND_START, MethodFilter.TYPE_PREFIX) };
    List methods = filterMethods(getType().getMethods(), validFilter, null);
    for (Iterator iter = methods.iterator(); iter.hasNext();) {
        IMethod method = (IMethod) iter.next();
        String fullMethodName = method.getElementName();
        String methodName = cutAwayEJBSuffix(fullMethodName);
        String[] parameterNames = method.getParameterNames();

        String returnType = method.getReturnType();
        if (fullMethodName.startsWith(WizardConstants.EJB_FIND_START)
                || fullMethodName.startsWith(WizardConstants.EJB_CREATE_START)) {
            if (!(Signature.getSimpleName(Signature.toString(method.getReturnType()))
                    .indexOf(Signature.getSimpleName("java.util.Collection")) != -1)
                    && !(Signature.getSimpleName(Signature.toString(method.getReturnType()))
                            .indexOf(Signature.getSimpleName("java.util.Set")) != -1)) {
                returnType = name;
            }
        }
        if (!returnType.equals(name)) {
            returnType = getReturnType(returnType);
        }

        methodConstructor = getMethodDeclaration(ast, method, methodName, returnType, getHomeImplImports(),
                false);
        classType.bodyDeclarations().add(methodConstructor);

        constructorBlock = ast.newBlock();
        methodConstructor.setBody(constructorBlock);

        constructorBlock.statements().add(getIDOCheckOutStatement(ast, getHomeImplImports()));

        if (fullMethodName.startsWith(WizardConstants.EJB_FIND_START)) {
            if (Signature.getSimpleName(Signature.toString(method.getReturnType()))
                    .indexOf(Signature.getSimpleName("java.util.Collection")) != -1) {
                constructorBlock.statements().add(
                        getDataCollectingStatement(ast, returnType, "ids", fullMethodName, parameterNames));
                constructorBlock.statements().add(getIDOCheckInStatement(ast));
                constructorBlock.statements()
                        .add(getObjectReturnStatement(ast, "getEntityCollectionForPrimaryKeys", "ids"));
            } else if (Signature.getSimpleName(Signature.toString(method.getReturnType()))
                    .indexOf(Signature.getSimpleName("java.util.Set")) != -1) {
                constructorBlock.statements().add(
                        getDataCollectingStatement(ast, returnType, "ids", fullMethodName, parameterNames));
                constructorBlock.statements().add(getIDOCheckInStatement(ast));
                constructorBlock.statements()
                        .add(getObjectReturnStatement(ast, "getEntitySetForPrimaryKeys", "ids"));
            } else {
                constructorBlock.statements()
                        .add(getDataCollectingStatement(ast, "Object", "pk", fullMethodName, parameterNames));
                constructorBlock.statements().add(getIDOCheckInStatement(ast));
                constructorBlock.statements().add(getObjectReturnStatement(ast, "findByPrimaryKey", "pk"));
            }
        } else if (fullMethodName.startsWith(WizardConstants.EJB_HOME_START)) {
            constructorBlock.statements().add(
                    getDataCollectingStatement(ast, returnType, "theReturn", fullMethodName, parameterNames));
            constructorBlock.statements().add(getIDOCheckInStatement(ast));
            constructorBlock.statements().add(getPrimitiveReturnStatement(ast, "theReturn"));
        } else if (fullMethodName.startsWith(WizardConstants.EJB_CREATE_START)) {
            constructorBlock.statements()
                    .add(getDataCollectingStatement(ast, "Object", "pk", fullMethodName, parameterNames));

            ce = ast.newCastExpression();
            ce.setType(ast.newSimpleType(ast.newSimpleName(getType().getTypeQualifiedName())));
            ce.setExpression(ast.newSimpleName("entity"));

            ParenthesizedExpression pe = ast.newParenthesizedExpression();
            pe.setExpression(ce);
            MethodInvocation mi = ast.newMethodInvocation();
            mi.setExpression(pe);
            mi.setName(ast.newSimpleName("ejbPostCreate"));
            constructorBlock.statements().add(ast.newExpressionStatement(mi));

            constructorBlock.statements().add(getIDOCheckInStatement(ast));

            TryStatement tryStatement = ast.newTryStatement();
            constructorBlock.statements().add(tryStatement);
            Block tryBlock = ast.newBlock();
            tryStatement.setBody(tryBlock);

            mi = ast.newMethodInvocation();
            mi.setName(ast.newSimpleName("findByPrimaryKey"));
            mi.arguments().add(ast.newSimpleName("pk"));

            returnStatement = ast.newReturnStatement();
            returnStatement.setExpression(mi);
            tryBlock.statements().add(returnStatement);

            CatchClause catchClause = ast.newCatchClause();
            tryStatement.catchClauses().add(catchClause);
            variableDeclaration = ast.newSingleVariableDeclaration();
            variableDeclaration.modifiers().addAll(ast.newModifiers(Modifier.NONE));
            variableDeclaration.setType(ast.newSimpleType(ast.newSimpleName(("FinderException"))));
            variableDeclaration.setName(ast.newSimpleName("fe"));
            catchClause.setException(variableDeclaration);
            Block catchBlock = ast.newBlock();
            catchClause.setBody(catchBlock);

            ClassInstanceCreation cc = ast.newClassInstanceCreation();
            cc.setType(ast.newSimpleType(ast.newSimpleName("IDOCreateException")));
            addHomeImplImport("com.idega.data.IDOCreateException");
            cc.arguments().add(ast.newSimpleName(("fe")));

            ThrowStatement throwStatement = ast.newThrowStatement();
            throwStatement.setExpression(cc);
            catchBlock.statements().add(throwStatement);

            catchClause = ast.newCatchClause();
            tryStatement.catchClauses().add(catchClause);
            variableDeclaration = ast.newSingleVariableDeclaration();
            variableDeclaration.modifiers().addAll(ast.newModifiers(Modifier.NONE));
            variableDeclaration.setType(ast.newSimpleType(ast.newSimpleName(("Exception"))));
            variableDeclaration.setName(ast.newSimpleName("e"));
            catchClause.setException(variableDeclaration);
            catchBlock = ast.newBlock();
            catchClause.setBody(catchBlock);

            cc = ast.newClassInstanceCreation();
            cc.setType(ast.newSimpleType(ast.newSimpleName("IDOCreateException")));
            cc.arguments().add(ast.newSimpleName(("e")));

            throwStatement = ast.newThrowStatement();
            throwStatement.setExpression(cc);
            catchBlock.statements().add(throwStatement);
        }
    }

    writeImports(ast, unit, getHomeImplImports());
    commitChanges(iUnit, unit, document);
}

From source file:de.ovgu.cide.export.physical.ahead.ReturnExtractionHelper.java

License:Open Source License

/**
 * surround method body with try catch block.
 * //ww  w . ja v  a 2 s . c o  m
 * if the last statement in the body is not a return statement (can happen
 * e.g., when the last statement is a hook method), then also a dummy return
 * statement is introduced that should never occur though.
 * 
 * @param method
 */
private void surroundBodyWithTryCatch(MethodDeclaration method) {
    AST ast = method.getAST();
    Block oldBody = method.getBody();
    boolean lastStatementIsReturn = oldBody.statements()
            .get(oldBody.statements().size() - 1) instanceof ReturnStatement;

    Block newBody = ast.newBlock();
    method.setBody(newBody);

    TryStatement tryStatement = ast.newTryStatement();
    newBody.statements().add(tryStatement);
    tryStatement.setBody(oldBody);

    if (!lastStatementIsReturn && !RefactoringUtils.isVoid(method.getReturnType2())) {
        addDummyReturnStatementHack(method, oldBody);
    }

    CatchClause catchClause = ast.newCatchClause();
    SingleVariableDeclaration exceptionDeclaration = ast.newSingleVariableDeclaration();
    exceptionDeclaration.setName(ast.newSimpleName("r"));
    exceptionDeclaration.setType(createExceptionType(method));

    catchClause.setException(exceptionDeclaration);
    catchClause.setBody(ast.newBlock());
    ReturnStatement returnStatement = ast.newReturnStatement();
    FieldAccess fieldAccess = ast.newFieldAccess();
    fieldAccess.setName(ast.newSimpleName("value"));
    fieldAccess.setExpression(ast.newSimpleName("r"));
    if (RefactoringUtils.isVoid(method.getReturnType2())) {
    } else if (method.getReturnType2().isPrimitiveType()) {
        returnStatement.setExpression(fieldAccess);
    } else {
        CastExpression cast = ast.newCastExpression();
        cast.setExpression(fieldAccess);
        cast.setType((Type) ASTNode.copySubtree(ast, method.getReturnType2()));
        returnStatement.setExpression(cast);
    }
    catchClause.getBody().statements().add(returnStatement);

    tryStatement.catchClauses().add(catchClause);
}

From source file:org.evosuite.eclipse.quickfixes.ResolutionMarkerTryBlock.java

License:Open Source License

@Override
public void run(IMarker marker) {
    // TODO Auto-generated method stub
    IResource res = marker.getResource();

    try {//from w  w  w. j a  v a  2  s.c  om
        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();
    }

}

From source file:org.evosuite.testcarver.codegen.CodeGenerator.java

License:Open Source License

@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);/*from   w ww.  j  a va  2  s  . co m*/
    tryStmt.catchClauses().add(cc);

    return tryStmt;
}

From source file:org.jboss.forge.roaster.model.impl.statements.TryCatchStatementImpl.java

License:Open Source License

@Override
public TryStatement materialize(AST ast) {
    if (tryCatch != null) {
        return tryCatch;
    }//ww  w.  j  a v a  2s .com
    tryCatch = ast.newTryStatement();

    for (DeclareExpression<O, TryCatchStatement<O, P>> declare : catches.keySet()) {
        CatchClause clause = ast.newCatchClause();
        clause.setException(
                varToSvd((VariableDeclarationExpression) wireAndGetExpression(declare, this, ast), ast));
        clause.setBody((org.eclipse.jdt.core.dom.Block) wireAndGetStatement(catches.get(declare), this, ast));
        tryCatch.catchClauses().add(clause);
    }

    if (fine != null) {
        tryCatch.setFinally((org.eclipse.jdt.core.dom.Block) wireAndGetStatement(fine, this, ast));
    }
    if (body != null) {
        tryCatch.setBody((org.eclipse.jdt.core.dom.Block) wireAndGetStatement(body, this, ast));
    }
    return tryCatch;
}