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