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;
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        Arrays.stream(new String[] {"finalize", }).collect(Collectors.toSet());
065
066    /** Illegal class names. */
067    private final Set<String> illegalClassNames = Arrays.stream(
068        new String[] {"Error", "RuntimeException", "Throwable", "java.lang.Error",
069                      "java.lang.RuntimeException", "java.lang.Throwable", })
070        .collect(Collectors.toSet());
071
072    /** Property for ignoring overridden methods. */
073    private boolean ignoreOverriddenMethods = true;
074
075    /**
076     * Set the list of illegal classes.
077     *
078     * @param classNames
079     *            array of illegal exception classes
080     */
081    public void setIllegalClassNames(final String... classNames) {
082        illegalClassNames.clear();
083        for (final String name : classNames) {
084            illegalClassNames.add(name);
085            final int lastDot = name.lastIndexOf('.');
086            if (lastDot > 0 && lastDot < name.length() - 1) {
087                final String shortName = name
088                        .substring(name.lastIndexOf('.') + 1);
089                illegalClassNames.add(shortName);
090            }
091        }
092    }
093
094    @Override
095    public int[] getDefaultTokens() {
096        return new int[] {TokenTypes.LITERAL_THROWS};
097    }
098
099    @Override
100    public int[] getRequiredTokens() {
101        return getDefaultTokens();
102    }
103
104    @Override
105    public int[] getAcceptableTokens() {
106        return new int[] {TokenTypes.LITERAL_THROWS};
107    }
108
109    @Override
110    public void visitToken(DetailAST detailAST) {
111        final DetailAST methodDef = detailAST.getParent();
112        // Check if the method with the given name should be ignored.
113        if (!isIgnorableMethod(methodDef)) {
114            DetailAST token = detailAST.getFirstChild();
115            while (token != null) {
116                if (token.getType() != TokenTypes.COMMA) {
117                    final FullIdent ident = FullIdent.createFullIdent(token);
118                    if (illegalClassNames.contains(ident.getText())) {
119                        log(token, MSG_KEY, ident.getText());
120                    }
121                }
122                token = token.getNextSibling();
123            }
124        }
125    }
126
127    /**
128     * Checks if current method is ignorable due to Check's properties.
129     * @param methodDef {@link TokenTypes#METHOD_DEF METHOD_DEF}
130     * @return true if method is ignorable.
131     */
132    private boolean isIgnorableMethod(DetailAST methodDef) {
133        return shouldIgnoreMethod(methodDef.findFirstToken(TokenTypes.IDENT).getText())
134            || ignoreOverriddenMethods
135               && (AnnotationUtility.containsAnnotation(methodDef, "Override")
136                  || AnnotationUtility.containsAnnotation(methodDef, "java.lang.Override"));
137    }
138
139    /**
140     * Check if the method is specified in the ignore method list.
141     * @param name the name to check
142     * @return whether the method with the passed name should be ignored
143     */
144    private boolean shouldIgnoreMethod(String name) {
145        return ignoredMethodNames.contains(name);
146    }
147
148    /**
149     * Set the list of ignore method names.
150     * @param methodNames array of ignored method names
151     */
152    public void setIgnoredMethodNames(String... methodNames) {
153        ignoredMethodNames.clear();
154        Collections.addAll(ignoredMethodNames, methodNames);
155    }
156
157    /**
158     * Sets <b>ignoreOverriddenMethods</b> property value.
159     * @param ignoreOverriddenMethods Check's property.
160     */
161    public void setIgnoreOverriddenMethods(boolean ignoreOverriddenMethods) {
162        this.ignoreOverriddenMethods = ignoreOverriddenMethods;
163    }
164}