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