001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2022 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.imports;
021
022import com.puppycrawl.tools.checkstyle.StatelessCheck;
023import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
024import com.puppycrawl.tools.checkstyle.api.DetailAST;
025import com.puppycrawl.tools.checkstyle.api.FullIdent;
026import com.puppycrawl.tools.checkstyle.api.TokenTypes;
027import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
028
029/**
030 * <p>
031 * Checks that there are no static import statements.
032 * </p>
033 * <p>
034 * Rationale: Importing static members can lead to naming conflicts
035 * between class' members. It may lead to poor code readability since it
036 * may no longer be clear what class a member resides in (without looking
037 * at the import statement).
038 * </p>
039 * <p>
040 * If you exclude a starred import on a class this automatically excludes
041 * each member individually.
042 * </p>
043 * <p>
044 * For example: Excluding {@code java.lang.Math.*}. will allow the import
045 * of each static member in the Math class individually like
046 * {@code java.lang.Math.PI, java.lang.Math.cos, ...}.
047 * </p>
048 * <ul>
049 * <li>
050 * Property {@code excludes} - Control whether to allow for certain classes via
051 * a star notation to be excluded such as {@code java.lang.Math.*} or specific
052 * static members to be excluded like {@code java.lang.System.out} for a variable
053 * or {@code java.lang.Math.random} for a method. See notes section for details.
054 * Type is {@code java.lang.String[]}.
055 * Default value is {@code ""}.
056 * </li>
057 * </ul>
058 * <p>
059 * To configure the check:
060 * </p>
061 * <pre>
062 * &lt;module name="AvoidStaticImport"/&gt;
063 * </pre>
064 * <p>Example:</p>
065 * <pre>
066 * import static java.lang.Math.pow;          // violation
067 * import static java.lang.System.*;          // violation
068 * import java.io.File;                       // OK
069 * import java.util.*;                        // OK
070 * </pre>
071 * <p>
072 * To configure the check so that the {@code java.lang.System.out} member and all
073 * members from {@code java.lang.Math} are allowed:
074 * </p>
075 * <pre>
076 * &lt;module name="AvoidStaticImport"&gt;
077 *   &lt;property name="excludes" value="java.lang.System.out,java.lang.Math.*"/&gt;
078 * &lt;/module&gt;
079 * </pre>
080 * <p>Example:</p>
081 * <pre>
082 * import static java.lang.Math.*;            // OK
083 * import static java.lang.System.out;        // OK
084 * import static java.lang.Integer.parseInt;  // violation
085 * import java.io.*;                          // OK
086 * import java.util.*;                        // OK
087 * </pre>
088 * <p>
089 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
090 * </p>
091 * <p>
092 * Violation Message Keys:
093 * </p>
094 * <ul>
095 * <li>
096 * {@code import.avoidStatic}
097 * </li>
098 * </ul>
099 *
100 * @since 5.0
101 */
102@StatelessCheck
103public class AvoidStaticImportCheck
104    extends AbstractCheck {
105
106    /**
107     * A key is pointing to the warning message text in "messages.properties"
108     * file.
109     */
110    public static final String MSG_KEY = "import.avoidStatic";
111
112    /**
113     * Control whether to allow for certain classes via a star notation to be
114     * excluded such as {@code java.lang.Math.*} or specific static members
115     * to be excluded like {@code java.lang.System.out} for a variable or
116     * {@code java.lang.Math.random} for a method. See notes section for details.
117     */
118    private String[] excludes = CommonUtil.EMPTY_STRING_ARRAY;
119
120    @Override
121    public int[] getDefaultTokens() {
122        return getRequiredTokens();
123    }
124
125    @Override
126    public int[] getAcceptableTokens() {
127        return getRequiredTokens();
128    }
129
130    @Override
131    public int[] getRequiredTokens() {
132        return new int[] {TokenTypes.STATIC_IMPORT};
133    }
134
135    /**
136     * Setter to control whether to allow for certain classes via a star notation
137     * to be excluded such as {@code java.lang.Math.*} or specific static members
138     * to be excluded like {@code java.lang.System.out} for a variable or
139     * {@code java.lang.Math.random} for a method. See notes section for details.
140     *
141     * @param excludes a list of fully-qualified class names/specific
142     *     static members where static imports are ok
143     */
144    public void setExcludes(String... excludes) {
145        this.excludes = excludes.clone();
146    }
147
148    @Override
149    public void visitToken(final DetailAST ast) {
150        final DetailAST startingDot =
151            ast.getFirstChild().getNextSibling();
152        final FullIdent name = FullIdent.createFullIdent(startingDot);
153
154        if (!isExempt(name.getText())) {
155            log(startingDot, MSG_KEY, name.getText());
156        }
157    }
158
159    /**
160     * Checks if a class or static member is exempt from known excludes.
161     *
162     * @param classOrStaticMember
163     *                the class or static member
164     * @return true if except false if not
165     */
166    private boolean isExempt(String classOrStaticMember) {
167        boolean exempt = false;
168
169        for (String exclude : excludes) {
170            if (classOrStaticMember.equals(exclude)
171                    || isStarImportOfPackage(classOrStaticMember, exclude)) {
172                exempt = true;
173                break;
174            }
175        }
176        return exempt;
177    }
178
179    /**
180     * Returns true if classOrStaticMember is a starred name of package,
181     *  not just member name.
182     *
183     * @param classOrStaticMember - full name of member
184     * @param exclude - current exclusion
185     * @return true if member in exclusion list
186     */
187    private static boolean isStarImportOfPackage(String classOrStaticMember, String exclude) {
188        boolean result = false;
189        if (exclude.endsWith(".*")) {
190            // this section allows explicit imports
191            // to be exempt when configured using
192            // a starred import
193            final String excludeMinusDotStar =
194                exclude.substring(0, exclude.length() - 2);
195            if (classOrStaticMember.startsWith(excludeMinusDotStar)
196                    && !classOrStaticMember.equals(excludeMinusDotStar)) {
197                final String member = classOrStaticMember.substring(
198                        excludeMinusDotStar.length() + 1);
199                // if it contains a dot then it is not a member but a package
200                if (member.indexOf('.') == -1) {
201                    result = true;
202                }
203            }
204        }
205        return result;
206    }
207
208}