001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2017 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.Collections;
024import java.util.Set;
025import java.util.stream.Collectors;
026
027import com.puppycrawl.tools.checkstyle.StatelessCheck;
028import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
029import com.puppycrawl.tools.checkstyle.api.DetailAST;
030import com.puppycrawl.tools.checkstyle.api.FullIdent;
031import com.puppycrawl.tools.checkstyle.api.TokenTypes;
032import com.puppycrawl.tools.checkstyle.utils.AnnotationUtility;
033import com.puppycrawl.tools.checkstyle.utils.CheckUtils;
034
035/**
036 * <p>
037 * Throwing java.lang.Error or java.lang.RuntimeException
038 * is almost never acceptable.
039 * </p>
040 * Check has following properties:
041 * <p>
042 * <b>illegalClassNames</b> - throw class names to reject.
043 * </p>
044 * <p>
045 * <b>ignoredMethodNames</b> - names of methods to ignore.
046 * </p>
047 * <p>
048 * <b>ignoreOverriddenMethods</b> - ignore checking overridden methods (marked with Override
049 *  or java.lang.Override annotation) default value is <b>true</b>.
050 * </p>
051 *
052 * @author Oliver Burn
053 * @author John Sirois
054 * @author <a href="mailto:nesterenko-aleksey@list.ru">Aleksey Nesterenko</a>
055 */
056@StatelessCheck
057public final class IllegalThrowsCheck extends AbstractCheck {
058
059    /**
060     * A key is pointing to the warning message text in "messages.properties"
061     * file.
062     */
063    public static final String MSG_KEY = "illegal.throw";
064
065    /** Methods which should be ignored. */
066    private final Set<String> ignoredMethodNames =
067        Arrays.stream(new String[] {"finalize", }).collect(Collectors.toSet());
068
069    /** Illegal class names. */
070    private final Set<String> illegalClassNames = Arrays.stream(
071        new String[] {"Error", "RuntimeException", "Throwable", "java.lang.Error",
072                      "java.lang.RuntimeException", "java.lang.Throwable", })
073        .collect(Collectors.toSet());
074
075    /** Property for ignoring overridden methods. */
076    private boolean ignoreOverriddenMethods = true;
077
078    /**
079     * Set the list of illegal classes.
080     *
081     * @param classNames
082     *            array of illegal exception classes
083     */
084    public void setIllegalClassNames(final String... classNames) {
085        illegalClassNames.clear();
086        illegalClassNames.addAll(
087                CheckUtils.parseClassNames(classNames));
088
089    }
090
091    @Override
092    public int[] getDefaultTokens() {
093        return getRequiredTokens();
094    }
095
096    @Override
097    public int[] getRequiredTokens() {
098        return new int[] {TokenTypes.LITERAL_THROWS};
099    }
100
101    @Override
102    public int[] getAcceptableTokens() {
103        return getRequiredTokens();
104    }
105
106    @Override
107    public void visitToken(DetailAST detailAST) {
108        final DetailAST methodDef = detailAST.getParent();
109        // Check if the method with the given name should be ignored.
110        if (!isIgnorableMethod(methodDef)) {
111            DetailAST token = detailAST.getFirstChild();
112            while (token != null) {
113                if (token.getType() != TokenTypes.COMMA) {
114                    final FullIdent ident = FullIdent.createFullIdent(token);
115                    if (illegalClassNames.contains(ident.getText())) {
116                        log(token, MSG_KEY, ident.getText());
117                    }
118                }
119                token = token.getNextSibling();
120            }
121        }
122    }
123
124    /**
125     * Checks if current method is ignorable due to Check's properties.
126     * @param methodDef {@link TokenTypes#METHOD_DEF METHOD_DEF}
127     * @return true if method is ignorable.
128     */
129    private boolean isIgnorableMethod(DetailAST methodDef) {
130        return shouldIgnoreMethod(methodDef.findFirstToken(TokenTypes.IDENT).getText())
131            || ignoreOverriddenMethods
132               && (AnnotationUtility.containsAnnotation(methodDef, "Override")
133                  || AnnotationUtility.containsAnnotation(methodDef, "java.lang.Override"));
134    }
135
136    /**
137     * Check if the method is specified in the ignore method list.
138     * @param name the name to check
139     * @return whether the method with the passed name should be ignored
140     */
141    private boolean shouldIgnoreMethod(String name) {
142        return ignoredMethodNames.contains(name);
143    }
144
145    /**
146     * Set the list of ignore method names.
147     * @param methodNames array of ignored method names
148     */
149    public void setIgnoredMethodNames(String... methodNames) {
150        ignoredMethodNames.clear();
151        Collections.addAll(ignoredMethodNames, methodNames);
152    }
153
154    /**
155     * Sets <b>ignoreOverriddenMethods</b> property value.
156     * @param ignoreOverriddenMethods Check's property.
157     */
158    public void setIgnoreOverriddenMethods(boolean ignoreOverriddenMethods) {
159        this.ignoreOverriddenMethods = ignoreOverriddenMethods;
160    }
161}