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