001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2018 the original author or authors.
004//
005// This library is free software; you can redistribute it and/or
006// modify it under the terms of the GNU Lesser General Public
007// License as published by the Free Software Foundation; either
008// version 2.1 of the License, or (at your option) any later version.
009//
010// This library is distributed in the hope that it will be useful,
011// but WITHOUT ANY WARRANTY; without even the implied warranty of
012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013// Lesser General Public License for more details.
014//
015// You should have received a copy of the GNU Lesser General Public
016// License along with this library; if not, write to the Free Software
017// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
018////////////////////////////////////////////////////////////////////////////////
019
020package com.puppycrawl.tools.checkstyle.checks.coding;
021
022import java.util.Arrays;
023import java.util.LinkedList;
024import java.util.List;
025import java.util.Set;
026import java.util.stream.Collectors;
027
028import com.puppycrawl.tools.checkstyle.StatelessCheck;
029import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
030import com.puppycrawl.tools.checkstyle.api.DetailAST;
031import com.puppycrawl.tools.checkstyle.api.FullIdent;
032import com.puppycrawl.tools.checkstyle.api.TokenTypes;
033import com.puppycrawl.tools.checkstyle.utils.CheckUtils;
034
035/**
036 * Catching java.lang.Exception, java.lang.Error or java.lang.RuntimeException
037 * is almost never acceptable.
038 * @author <a href="mailto:simon@redhillconsulting.com.au">Simon Harris</a>
039 * @author <a href="mailto:IliaDubinin91@gmail.com">Ilja Dubinin</a>
040 */
041@StatelessCheck
042public final class IllegalCatchCheck extends AbstractCheck {
043
044    /**
045     * A key is pointing to the warning message text in "messages.properties"
046     * file.
047     */
048    public static final String MSG_KEY = "illegal.catch";
049
050    /** Illegal class names. */
051    private final Set<String> illegalClassNames = Arrays.stream(new String[] {"Exception", "Error",
052        "RuntimeException", "Throwable", "java.lang.Error", "java.lang.Exception",
053        "java.lang.RuntimeException", "java.lang.Throwable", }).collect(Collectors.toSet());
054
055    /**
056     * Set the list of illegal classes.
057     *
058     * @param classNames
059     *            array of illegal exception classes
060     */
061    public void setIllegalClassNames(final String... classNames) {
062        illegalClassNames.clear();
063        illegalClassNames.addAll(
064                CheckUtils.parseClassNames(classNames));
065    }
066
067    @Override
068    public int[] getDefaultTokens() {
069        return getRequiredTokens();
070    }
071
072    @Override
073    public int[] getRequiredTokens() {
074        return new int[] {TokenTypes.LITERAL_CATCH};
075    }
076
077    @Override
078    public int[] getAcceptableTokens() {
079        return getRequiredTokens();
080    }
081
082    @Override
083    public void visitToken(DetailAST detailAST) {
084        final DetailAST parameterDef =
085            detailAST.findFirstToken(TokenTypes.PARAMETER_DEF);
086        final DetailAST excTypeParent =
087                parameterDef.findFirstToken(TokenTypes.TYPE);
088        final List<DetailAST> excTypes = getAllExceptionTypes(excTypeParent);
089
090        for (DetailAST excType : excTypes) {
091            final FullIdent ident = FullIdent.createFullIdent(excType);
092
093            if (illegalClassNames.contains(ident.getText())) {
094                log(detailAST, MSG_KEY, ident.getText());
095            }
096        }
097    }
098
099    /**
100     * Finds all exception types in current catch.
101     * We need it till we can have few different exception types into one catch.
102     * @param parentToken - parent node for types (TYPE or BOR)
103     * @return list, that contains all exception types in current catch
104     */
105    private static List<DetailAST> getAllExceptionTypes(DetailAST parentToken) {
106        DetailAST currentNode = parentToken.getFirstChild();
107        final List<DetailAST> exceptionTypes = new LinkedList<>();
108        if (currentNode.getType() == TokenTypes.BOR) {
109            exceptionTypes.addAll(getAllExceptionTypes(currentNode));
110            currentNode = currentNode.getNextSibling();
111            if (currentNode != null) {
112                exceptionTypes.add(currentNode);
113            }
114        }
115        else {
116            exceptionTypes.add(currentNode);
117            currentNode = currentNode.getNextSibling();
118            while (currentNode != null) {
119                exceptionTypes.add(currentNode);
120                currentNode = currentNode.getNextSibling();
121            }
122        }
123        return exceptionTypes;
124    }
125
126}