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