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