001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2017 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.api.AbstractCheck;
023import com.puppycrawl.tools.checkstyle.api.DetailAST;
024import com.puppycrawl.tools.checkstyle.api.FullIdent;
025import com.puppycrawl.tools.checkstyle.api.TokenTypes;
026import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
027
028/**
029 * <p>
030 * Check that finds static imports.
031 * </p>
032 * <p>
033 * Rationale: Importing static members can lead to naming conflicts
034 * between class' members. It may lead to poor code readability since it
035 * may no longer be clear what class a member resides (without looking
036 * at the import statement).
037 * </p>
038 * <p>
039 * An example of how to configure the check is:
040 * </p>
041 * <pre>
042 * &lt;module name="AvoidStaticImport"&gt;
043 *   &lt;property name="excludes"
044 *       value="java.lang.System.out,java.lang.Math.*"/&gt;
045 * &lt;/module&gt;
046 * </pre>
047 * The optional "excludes" property allows for certain classes via a star
048 * notation to be excluded such as java.lang.Math.* or specific
049 * static members to be excluded like java.lang.System.out for a variable
050 * or java.lang.Math.random for a method.
051 *
052 * <p>
053 * If you exclude a starred import on a class this automatically
054 * excludes each member individually.
055 * </p>
056 *
057 * <p>
058 * For example:
059 * Excluding java.lang.Math.* will allow the import of
060 * each static member in the Math class individually like
061 * java.lang.Math.PI
062 * </p>
063 * @author Travis Schneeberger
064 */
065public class AvoidStaticImportCheck
066    extends AbstractCheck {
067
068    /**
069     * A key is pointing to the warning message text in "messages.properties"
070     * file.
071     */
072    public static final String MSG_KEY = "import.avoidStatic";
073
074    /** The classes/static members to exempt from this check. */
075    private String[] excludes = CommonUtils.EMPTY_STRING_ARRAY;
076
077    @Override
078    public int[] getDefaultTokens() {
079        return getAcceptableTokens();
080    }
081
082    @Override
083    public int[] getAcceptableTokens() {
084        return new int[] {TokenTypes.STATIC_IMPORT};
085    }
086
087    @Override
088    public int[] getRequiredTokens() {
089        return getAcceptableTokens();
090    }
091
092    /**
093     * Sets the list of classes or static members to be exempt from the check.
094     * @param excludes a list of fully-qualified class names/specific
095     *     static members where static imports are ok
096     */
097    public void setExcludes(String... excludes) {
098        this.excludes = excludes.clone();
099    }
100
101    @Override
102    public void visitToken(final DetailAST ast) {
103        final DetailAST startingDot =
104            ast.getFirstChild().getNextSibling();
105        final FullIdent name = FullIdent.createFullIdent(startingDot);
106
107        if (!isExempt(name.getText())) {
108            log(startingDot.getLineNo(), MSG_KEY, name.getText());
109        }
110    }
111
112    /**
113     * Checks if a class or static member is exempt from known excludes.
114     *
115     * @param classOrStaticMember
116     *                the class or static member
117     * @return true if except false if not
118     */
119    private boolean isExempt(String classOrStaticMember) {
120        boolean exempt = false;
121
122        for (String exclude : excludes) {
123            if (classOrStaticMember.equals(exclude)
124                    || isStarImportOfPackage(classOrStaticMember, exclude)) {
125                exempt = true;
126                break;
127            }
128        }
129        return exempt;
130    }
131
132    /**
133     * Returns true if classOrStaticMember is a starred name of package,
134     *  not just member name.
135     * @param classOrStaticMember - full name of member
136     * @param exclude - current exclusion
137     * @return true if member in exclusion list
138     */
139    private static boolean isStarImportOfPackage(String classOrStaticMember, String exclude) {
140        boolean result = false;
141        if (exclude.endsWith(".*")) {
142            //this section allows explicit imports
143            //to be exempt when configured using
144            //a starred import
145            final String excludeMinusDotStar =
146                exclude.substring(0, exclude.length() - 2);
147            if (classOrStaticMember.startsWith(excludeMinusDotStar)
148                    && !classOrStaticMember.equals(excludeMinusDotStar)) {
149                final String member = classOrStaticMember.substring(
150                        excludeMinusDotStar.length() + 1);
151                //if it contains a dot then it is not a member but a package
152                if (member.indexOf('.') == -1) {
153                    result = true;
154                }
155            }
156        }
157        return result;
158    }
159}