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