001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2019 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 java.util.ArrayList;
023import java.util.List;
024
025import com.puppycrawl.tools.checkstyle.StatelessCheck;
026import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
027import com.puppycrawl.tools.checkstyle.api.DetailAST;
028import com.puppycrawl.tools.checkstyle.api.FullIdent;
029import com.puppycrawl.tools.checkstyle.api.TokenTypes;
030
031/**
032 * <p>
033 * Checks that there are no import statements that use the {@code *} notation.
034 * </p>
035 * <p>
036 * Rationale: Importing all classes from a package or static
037 * members from a class leads to tight coupling between packages
038 * or classes and might lead to problems when a new version of a
039 * library introduces name clashes.
040 * </p>
041 * <p>
042 * Note that property {@code excludes} is not recursive, subpackages of excluded
043 * packages are not automatically excluded.
044 * </p>
045 * <ul>
046 * <li>
047 * Property {@code excludes} - Specify packages where star imports are allowed.
048 * Default value is {@code {}}.
049 * </li>
050 * <li>
051 * Property {@code allowClassImports} - Control whether to allow starred class
052 * imports like {@code import java.util.*;}.
053 * Default value is {@code false}.
054 * </li>
055 * <li>
056 * Property {@code allowStaticMemberImports} - Control whether to allow starred
057 * static member imports like {@code import static org.junit.Assert.*;}.
058 * Default value is {@code false}.
059 * </li>
060 * </ul>
061 * <p>
062 * To configure the check:
063 * </p>
064 * <pre>
065 * &lt;module name="AvoidStarImport"/&gt;
066 * </pre>
067 * <p>
068 * To configure the check so that star imports from packages
069 * {@code java.io and java.net} as well as static members from class
070 * {@code java.lang.Math} are allowed:
071 * </p>
072 * <pre>
073 * &lt;module name="AvoidStarImport"&gt;
074 *   &lt;property name="excludes" value="java.io,java.net,java.lang.Math"/&gt;
075 * &lt;/module&gt;
076 * </pre>
077 *
078 * @since 3.0
079 */
080@StatelessCheck
081public class AvoidStarImportCheck
082    extends AbstractCheck {
083
084    /**
085     * A key is pointing to the warning message text in "messages.properties"
086     * file.
087     */
088    public static final String MSG_KEY = "import.avoidStar";
089
090    /** Suffix for the star import. */
091    private static final String STAR_IMPORT_SUFFIX = ".*";
092
093    /** Specify packages where star imports are allowed. */
094    private final List<String> excludes = new ArrayList<>();
095
096    /**
097     * Control whether to allow starred class imports like
098     * {@code import java.util.*;}.
099     */
100    private boolean allowClassImports;
101
102    /**
103     * Control whether to allow starred static member imports like
104     * {@code import static org.junit.Assert.*;}.
105     */
106    private boolean allowStaticMemberImports;
107
108    @Override
109    public int[] getDefaultTokens() {
110        return getRequiredTokens();
111    }
112
113    @Override
114    public int[] getAcceptableTokens() {
115        return getRequiredTokens();
116    }
117
118    @Override
119    public int[] getRequiredTokens() {
120        // original implementation checks both IMPORT and STATIC_IMPORT tokens to avoid ".*" imports
121        // however user can allow using "import" or "import static"
122        // by configuring allowClassImports and allowStaticMemberImports
123        // To avoid potential confusion when user specifies conflicting options on configuration
124        // (see example below) we are adding both tokens to Required list
125        //   <module name="AvoidStarImport">
126        //      <property name="tokens" value="IMPORT"/>
127        //      <property name="allowStaticMemberImports" value="false"/>
128        //   </module>
129        return new int[] {TokenTypes.IMPORT, TokenTypes.STATIC_IMPORT};
130    }
131
132    /**
133     * Setter to specify packages where star imports are allowed.
134     *
135     * @param excludesParam a list of package names/fully-qualifies class names
136     *     where star imports are ok.
137     */
138    public void setExcludes(String... excludesParam) {
139        for (final String exclude : excludesParam) {
140            if (exclude.endsWith(STAR_IMPORT_SUFFIX)) {
141                excludes.add(exclude);
142            }
143            else {
144                excludes.add(exclude + STAR_IMPORT_SUFFIX);
145            }
146        }
147    }
148
149    /**
150     * Setter to control whether to allow starred class imports like
151     * {@code import java.util.*;}.
152     *
153     * @param allow true to allow false to disallow
154     */
155    public void setAllowClassImports(boolean allow) {
156        allowClassImports = allow;
157    }
158
159    /**
160     * Setter to control whether to allow starred static member imports like
161     * {@code import static org.junit.Assert.*;}.
162     *
163     * @param allow true to allow false to disallow
164     */
165    public void setAllowStaticMemberImports(boolean allow) {
166        allowStaticMemberImports = allow;
167    }
168
169    @Override
170    public void visitToken(final DetailAST ast) {
171        if (!allowClassImports && ast.getType() == TokenTypes.IMPORT) {
172            final DetailAST startingDot = ast.getFirstChild();
173            logsStarredImportViolation(startingDot);
174        }
175        else if (!allowStaticMemberImports
176            && ast.getType() == TokenTypes.STATIC_IMPORT) {
177            // must navigate past the static keyword
178            final DetailAST startingDot = ast.getFirstChild().getNextSibling();
179            logsStarredImportViolation(startingDot);
180        }
181    }
182
183    /**
184     * Gets the full import identifier.  If the import is a starred import and
185     * it's not excluded then a violation is logged.
186     * @param startingDot the starting dot for the import statement
187     */
188    private void logsStarredImportViolation(DetailAST startingDot) {
189        final FullIdent name = FullIdent.createFullIdent(startingDot);
190        final String importText = name.getText();
191        if (importText.endsWith(STAR_IMPORT_SUFFIX) && !excludes.contains(importText)) {
192            log(startingDot.getLineNo(), MSG_KEY, importText);
193        }
194    }
195
196}