Search in sources :

Example 11 with TryStatement

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

the class ASTNodes method isExceptionExpected.

/**
 * Returns whether a checked exception is supposed to be caught.
 *
 * @param node the node
 * @return true if a checked exception is supposed to be caught.
 */
public static boolean isExceptionExpected(final ASTNode node) {
    ASTNode parentNode = getFirstAncestorOrNull(node, TryStatement.class, BodyDeclaration.class);
    while (parentNode instanceof TryStatement) {
        TryStatement tryStatement = (TryStatement) parentNode;
        for (Object object : tryStatement.catchClauses()) {
            CatchClause catchClause = (CatchClause) object;
            if (catchClause.getException().getType() != null && !instanceOf(catchClause.getException().getType().resolveBinding(), RuntimeException.class.getCanonicalName())) {
                return true;
            }
        }
        parentNode = getFirstAncestorOrNull(parentNode, TryStatement.class, BodyDeclaration.class);
    }
    return false;
}
Also used : TryStatement(org.eclipse.jdt.core.dom.TryStatement) ASTNode(org.eclipse.jdt.core.dom.ASTNode) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) CatchClause(org.eclipse.jdt.core.dom.CatchClause)

Example 12 with TryStatement

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

the class ASTNodeFactory method newTryStatement.

/**
 * Builds a new {@link TryStatement} instance.
 *
 * @param body         the try body
 * @param catchClauses the catch clauses for the try
 * @return a new try statement
 */
public TryStatement newTryStatement(final Block body, final CatchClause... catchClauses) {
    TryStatement tryS = ast.newTryStatement();
    tryS.setBody(body);
    addAll(tryS.catchClauses(), catchClauses);
    return tryS;
}
Also used : TryStatement(org.eclipse.jdt.core.dom.TryStatement)

Example 13 with TryStatement

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

the class SurroundWithTryCatchRefactoring method createTryCatchStatement.

private void createTryCatchStatement(org.eclipse.jdt.core.IBuffer buffer, String lineDelimiter) throws CoreException {
    List<Statement> result = new ArrayList<Statement>(1);
    TryStatement tryStatement = getAST().newTryStatement();
    ITypeBinding[] exceptions = fAnalyzer.getExceptions();
    ImportRewriteContext context = new ContextSensitiveImportRewriteContext(fAnalyzer.getEnclosingBodyDeclaration(), fImportRewrite);
    if (!fIsMultiCatch) {
        for (int i = 0; i < exceptions.length; i++) {
            ITypeBinding exception = exceptions[i];
            CatchClause catchClause = getAST().newCatchClause();
            tryStatement.catchClauses().add(catchClause);
            SingleVariableDeclaration decl = getAST().newSingleVariableDeclaration();
            String varName = StubUtility.getExceptionVariableName(fCUnit.getJavaProject());
            String name = fScope.createName(varName, false);
            decl.setName(getAST().newSimpleName(name));
            Type type = fImportRewrite.addImport(exception, getAST(), context);
            decl.setType(type);
            catchClause.setException(decl);
            Statement st = getCatchBody(ASTNodes.getQualifiedTypeName(type), name, lineDelimiter);
            if (st != null) {
                catchClause.getBody().statements().add(st);
            }
            fLinkedProposalModel.getPositionGroup(GROUP_EXC_TYPE + i, true).addPosition(fRewriter.track(decl.getType()), i == 0);
            fLinkedProposalModel.getPositionGroup(GROUP_EXC_NAME + i, true).addPosition(fRewriter.track(decl.getName()), false);
        }
    } else {
        List<ITypeBinding> filteredExceptions = filterSubtypeExceptions(exceptions);
        CatchClause catchClause = getAST().newCatchClause();
        SingleVariableDeclaration decl = getAST().newSingleVariableDeclaration();
        String varName = StubUtility.getExceptionVariableName(fCUnit.getJavaProject());
        String name = fScope.createName(varName, false);
        decl.setName(getAST().newSimpleName(name));
        UnionType unionType = getAST().newUnionType();
        List<Type> types = unionType.types();
        int i = 0;
        for (ITypeBinding exception : filteredExceptions) {
            Type type = fImportRewrite.addImport(exception, getAST(), context);
            types.add(type);
            fLinkedProposalModel.getPositionGroup(GROUP_EXC_TYPE + i, true).addPosition(fRewriter.track(type), i == 0);
            i++;
        }
        decl.setType(unionType);
        catchClause.setException(decl);
        fLinkedProposalModel.getPositionGroup(GROUP_EXC_NAME + 0, true).addPosition(fRewriter.track(decl.getName()), false);
        //$NON-NLS-1$
        Statement st = getCatchBody("Exception", name, lineDelimiter);
        if (st != null) {
            catchClause.getBody().statements().add(st);
        }
        tryStatement.catchClauses().add(catchClause);
    }
    List<ASTNode> variableDeclarations = getSpecialVariableDeclarationStatements();
    ListRewrite statements = fRewriter.getListRewrite(tryStatement.getBody(), Block.STATEMENTS_PROPERTY);
    boolean selectedNodeRemoved = false;
    ASTNode expressionStatement = null;
    for (int i = 0; i < fSelectedNodes.length; i++) {
        ASTNode node = fSelectedNodes[i];
        if (node instanceof VariableDeclarationStatement && variableDeclarations.contains(node)) {
            AST ast = getAST();
            VariableDeclarationStatement statement = (VariableDeclarationStatement) node;
            // Create a copy and remove the initializer
            VariableDeclarationStatement copy = (VariableDeclarationStatement) ASTNode.copySubtree(ast, statement);
            List<IExtendedModifier> modifiers = copy.modifiers();
            for (Iterator<IExtendedModifier> iter = modifiers.iterator(); iter.hasNext(); ) {
                IExtendedModifier modifier = iter.next();
                if (modifier.isModifier() && Modifier.isFinal(((Modifier) modifier).getKeyword().toFlagValue())) {
                    iter.remove();
                }
            }
            List<VariableDeclarationFragment> fragments = copy.fragments();
            for (Iterator<VariableDeclarationFragment> iter = fragments.iterator(); iter.hasNext(); ) {
                VariableDeclarationFragment fragment = iter.next();
                fragment.setInitializer(null);
            }
            CompilationUnit root = (CompilationUnit) statement.getRoot();
            int extendedStart = root.getExtendedStartPosition(statement);
            // we have a leading comment and the comment is covered by the selection
            if (extendedStart != statement.getStartPosition() && extendedStart >= fSelection.getOffset()) {
                String commentToken = buffer.getText(extendedStart, statement.getStartPosition() - extendedStart);
                commentToken = Strings.trimTrailingTabsAndSpaces(commentToken);
                Type type = statement.getType();
                String typeName = buffer.getText(type.getStartPosition(), type.getLength());
                copy.setType((Type) fRewriter.createStringPlaceholder(commentToken + typeName, type.getNodeType()));
            }
            result.add(copy);
            // convert the fragments into expression statements
            fragments = statement.fragments();
            if (!fragments.isEmpty()) {
                List<ExpressionStatement> newExpressionStatements = new ArrayList<ExpressionStatement>();
                for (Iterator<VariableDeclarationFragment> iter = fragments.iterator(); iter.hasNext(); ) {
                    VariableDeclarationFragment fragment = iter.next();
                    Expression initializer = fragment.getInitializer();
                    if (initializer != null) {
                        Assignment assignment = ast.newAssignment();
                        assignment.setLeftHandSide((Expression) fRewriter.createCopyTarget(fragment.getName()));
                        assignment.setRightHandSide((Expression) fRewriter.createCopyTarget(initializer));
                        newExpressionStatements.add(ast.newExpressionStatement(assignment));
                    }
                }
                if (!newExpressionStatements.isEmpty()) {
                    if (fSelectedNodes.length == 1) {
                        expressionStatement = fRewriter.createGroupNode(newExpressionStatements.toArray(new ASTNode[newExpressionStatements.size()]));
                    } else {
                        fRewriter.replace(statement, fRewriter.createGroupNode(newExpressionStatements.toArray(new ASTNode[newExpressionStatements.size()])), null);
                    }
                } else {
                    fRewriter.remove(statement, null);
                    selectedNodeRemoved = true;
                }
            } else {
                fRewriter.remove(statement, null);
                selectedNodeRemoved = true;
            }
        }
    }
    result.add(tryStatement);
    ASTNode replacementNode;
    if (result.size() == 1) {
        replacementNode = result.get(0);
    } else {
        replacementNode = fRewriter.createGroupNode(result.toArray(new ASTNode[result.size()]));
    }
    if (fSelectedNodes.length == 1) {
        if (expressionStatement != null) {
            statements.insertLast(expressionStatement, null);
        } else {
            if (!selectedNodeRemoved)
                statements.insertLast(fRewriter.createMoveTarget(fSelectedNodes[0]), null);
        }
        fRewriter.replace(fSelectedNodes[0], replacementNode, null);
    } else {
        ListRewrite source = fRewriter.getListRewrite(fSelectedNodes[0].getParent(), (ChildListPropertyDescriptor) fSelectedNodes[0].getLocationInParent());
        ASTNode toMove = source.createMoveTarget(fSelectedNodes[0], fSelectedNodes[fSelectedNodes.length - 1], replacementNode, null);
        statements.insertLast(toMove, null);
    }
}
Also used : UnionType(org.eclipse.jdt.core.dom.UnionType) ArrayList(java.util.ArrayList) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) IExtendedModifier(org.eclipse.jdt.core.dom.IExtendedModifier) Assignment(org.eclipse.jdt.core.dom.Assignment) TryStatement(org.eclipse.jdt.core.dom.TryStatement) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) AST(org.eclipse.jdt.core.dom.AST) Statement(org.eclipse.jdt.core.dom.Statement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) TryStatement(org.eclipse.jdt.core.dom.TryStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) CatchClause(org.eclipse.jdt.core.dom.CatchClause) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) UnionType(org.eclipse.jdt.core.dom.UnionType) Type(org.eclipse.jdt.core.dom.Type) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Expression(org.eclipse.jdt.core.dom.Expression) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement)

Example 14 with TryStatement

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

the class TryWithResourceRefactoring method visit.

@Override
public boolean visit(TryStatement node) {
    final List<Statement> tryStmts = asList(node.getBody());
    if (tryStmts.size() >= 1 && tryStmts.get(0).getNodeType() == TRY_STATEMENT) {
        final TryStatement innerTryStmt = as(tryStmts.get(0), TryStatement.class);
        if (innerTryStmt != null && !innerTryStmt.resources().isEmpty() && innerTryStmt.catchClauses().isEmpty()) {
            return collapseTryStatements(node, innerTryStmt);
        }
    }
    final VariableDeclarationStatement previousDeclStmt = as(getPreviousStatement(node), VariableDeclarationStatement.class);
    if (previousDeclStmt == null) {
        return VISIT_SUBTREE;
    }
    final VariableDeclarationFragment previousDeclFragment = getUniqueFragment(previousDeclStmt);
    final List<Statement> finallyStmts = asList(node.getFinally());
    if (previousDeclFragment != null && finallyStmts.size() >= 1) {
        final List<ASTNode> nodesToRemove = new ArrayList<ASTNode>();
        nodesToRemove.add(previousDeclStmt);
        final Statement finallyStmt = finallyStmts.get(0);
        nodesToRemove.add(finallyStmts.size() == 1 ? node.getFinally() : finallyStmt);
        final ExpressionStatement finallyEs = as(finallyStmt, ExpressionStatement.class);
        final IfStatement finallyIs = as(finallyStmt, IfStatement.class);
        if (finallyEs != null) {
            final MethodInvocation mi = as(finallyEs.getExpression(), MethodInvocation.class);
            if (methodClosesCloseables(mi) && areSameVariables(previousDeclFragment, mi.getExpression())) {
                final VariableDeclarationExpression newResource = newResource(tryStmts, previousDeclStmt, previousDeclFragment, nodesToRemove);
                return refactorToTryWithResources(node, newResource, nodesToRemove);
            }
        } else if (finallyIs != null && asList(finallyIs.getThenStatement()).size() == 1 && asList(finallyIs.getElseStatement()).isEmpty()) {
            final Expression nullCheckedExpr = getNullCheckedExpression(finallyIs.getExpression());
            final Statement thenStmt = asList(finallyIs.getThenStatement()).get(0);
            final MethodInvocation mi = asExpression(thenStmt, MethodInvocation.class);
            if (methodClosesCloseables(mi) && areSameVariables(previousDeclFragment, nullCheckedExpr, mi.getExpression())) {
                final VariableDeclarationExpression newResource = newResource(tryStmts, previousDeclStmt, previousDeclFragment, nodesToRemove);
                return refactorToTryWithResources(node, newResource, nodesToRemove);
            }
        }
    }
    return VISIT_SUBTREE;
}
Also used : ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) TryStatement(org.eclipse.jdt.core.dom.TryStatement) Statement(org.eclipse.jdt.core.dom.Statement) IfStatement(org.eclipse.jdt.core.dom.IfStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) ArrayList(java.util.ArrayList) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) IfStatement(org.eclipse.jdt.core.dom.IfStatement) TryStatement(org.eclipse.jdt.core.dom.TryStatement) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) Expression(org.eclipse.jdt.core.dom.Expression) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) ASTNode(org.eclipse.jdt.core.dom.ASTNode) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement)

Example 15 with TryStatement

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

the class ASTBuilder method try0.

/**
 * Builds a new {@link TryStatement} instance.
 *
 * @param body the try body
 * @param catchClauses the catch clauses for the try
 * @return a new try statement
 */
public TryStatement try0(final Block body, CatchClause... catchClauses) {
    final TryStatement tryS = ast.newTryStatement();
    tryS.setBody(body);
    addAll(catchClauses(tryS), catchClauses);
    return tryS;
}
Also used : TryStatement(org.eclipse.jdt.core.dom.TryStatement)

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