001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2020 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>Example:</p>
068 * <pre>
069 * import java.util.Scanner;         // OK
070 * import java.io.*;                 // violation
071 * import static java.lang.Math.*;   // violation
072 * import java.util.*;               // violation
073 * import java.net.*;                // violation
074 * </pre>
075 * <p>
076 * To configure the check so that star imports from packages
077 * {@code java.io and java.net} as well as static members from class
078 * {@code java.lang.Math} are allowed:
079 * </p>
080 * <pre>
081 * &lt;module name="AvoidStarImport"&gt;
082 *   &lt;property name="excludes" value="java.io,java.net,java.lang.Math"/&gt;
083 * &lt;/module&gt;
084 * </pre>
085 * <p>Example:</p>
086 * <pre>
087 * import java.util.Scanner;         // OK
088 * import java.io.*;                 // OK
089 * import static java.lang.Math.*;   // OK
090 * import java.util.*;               // violation
091 * import java.net.*;                // OK
092 * </pre>
093 * <p>
094 * To configure the check so that star imports from all packages are allowed:
095 * </p>
096 * <pre>
097 * &lt;module name="AvoidStarImport"&gt;
098 *   &lt;property name="allowClassImports" value="true"/&gt;
099 * &lt;/module&gt;
100 * </pre>
101 * <p>Example:</p>
102 * <pre>
103 * import java.util.Scanner;         // OK
104 * import java.io.*;                 // OK
105 * import static java.lang.Math.*;   // violation
106 * import java.util.*;               // OK
107 * import java.net.*;                // OK
108 * </pre>
109 * <p>
110 * To configure the check so that starred static member imports from all packages are allowed:
111 * </p>
112 * <pre>
113 * &lt;module name="AvoidStarImport"&gt;
114 *   &lt;property name="allowStaticMemberImports" value="true"/&gt;
115 * &lt;/module&gt;
116 * </pre>
117 * <p>Example:</p>
118 * <pre>
119 * import java.util.Scanner;         // OK
120 * import java.io.*;                 // violation
121 * import static java.lang.Math.*;   // OK
122 * import java.util.*;               // violation
123 * import java.net.*;                // violation
124 * </pre>
125 *
126 * @since 3.0
127 */
128@StatelessCheck
129public class AvoidStarImportCheck
130    extends AbstractCheck {
131
132    /**
133     * A key is pointing to the warning message text in "messages.properties"
134     * file.
135     */
136    public static final String MSG_KEY = "import.avoidStar";
137
138    /** Suffix for the star import. */
139    private static final String STAR_IMPORT_SUFFIX = ".*";
140
141    /** Specify packages where star imports are allowed. */
142    private final List<String> excludes = new ArrayList<>();
143
144    /**
145     * Control whether to allow starred class imports like
146     * {@code import java.util.*;}.
147     */
148    private boolean allowClassImports;
149
150    /**
151     * Control whether to allow starred static member imports like
152     * {@code import static org.junit.Assert.*;}.
153     */
154    private boolean allowStaticMemberImports;
155
156    @Override
157    public int[] getDefaultTokens() {
158        return getRequiredTokens();
159    }
160
161    @Override
162    public int[] getAcceptableTokens() {
163        return getRequiredTokens();
164    }
165
166    @Override
167    public int[] getRequiredTokens() {
168        // original implementation checks both IMPORT and STATIC_IMPORT tokens to avoid ".*" imports
169        // however user can allow using "import" or "import static"
170        // by configuring allowClassImports and allowStaticMemberImports
171        // To avoid potential confusion when user specifies conflicting options on configuration
172        // (see example below) we are adding both tokens to Required list
173        //   <module name="AvoidStarImport">
174        //      <property name="tokens" value="IMPORT"/>
175        //      <property name="allowStaticMemberImports" value="false"/>
176        //   </module>
177        return new int[] {TokenTypes.IMPORT, TokenTypes.STATIC_IMPORT};
178    }
179
180    /**
181     * Setter to specify packages where star imports are allowed.
182     *
183     * @param excludesParam a list of package names/fully-qualifies class names
184     *     where star imports are ok.
185     */
186    public void setExcludes(String... excludesParam) {
187        for (final String exclude : excludesParam) {
188            if (exclude.endsWith(STAR_IMPORT_SUFFIX)) {
189                excludes.add(exclude);
190            }
191            else {
192                excludes.add(exclude + STAR_IMPORT_SUFFIX);
193            }
194        }
195    }
196
197    /**
198     * Setter to control whether to allow starred class imports like
199     * {@code import java.util.*;}.
200     *
201     * @param allow true to allow false to disallow
202     */
203    public void setAllowClassImports(boolean allow) {
204        allowClassImports = allow;
205    }
206
207    /**
208     * Setter to control whether to allow starred static member imports like
209     * {@code import static org.junit.Assert.*;}.
210     *
211     * @param allow true to allow false to disallow
212     */
213    public void setAllowStaticMemberImports(boolean allow) {
214        allowStaticMemberImports = allow;
215    }
216
217    @Override
218    public void visitToken(final DetailAST ast) {
219        if (ast.getType() == TokenTypes.IMPORT) {
220            if (!allowClassImports) {
221                final DetailAST startingDot = ast.getFirstChild();
222                logsStarredImportViolation(startingDot);
223            }
224        }
225        else if (!allowStaticMemberImports) {
226            // must navigate past the static keyword
227            final DetailAST startingDot = ast.getFirstChild().getNextSibling();
228            logsStarredImportViolation(startingDot);
229        }
230    }
231
232    /**
233     * Gets the full import identifier.  If the import is a starred import and
234     * it's not excluded then a violation is logged.
235     *
236     * @param startingDot the starting dot for the import statement
237     */
238    private void logsStarredImportViolation(DetailAST startingDot) {
239        final FullIdent name = FullIdent.createFullIdent(startingDot);
240        final String importText = name.getText();
241        if (importText.endsWith(STAR_IMPORT_SUFFIX) && !excludes.contains(importText)) {
242            log(startingDot, MSG_KEY, importText);
243        }
244    }
245
246}