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.coding;
021
022import java.io.File;
023
024import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
025import com.puppycrawl.tools.checkstyle.api.DetailAST;
026import com.puppycrawl.tools.checkstyle.api.FullIdent;
027import com.puppycrawl.tools.checkstyle.api.TokenTypes;
028
029/**
030 * Ensures there is a package declaration.
031 * Optionally checks if directory structure matches package name.
032 * Rationale: Classes that live in the null package cannot be
033 * imported. Many novice developers are not aware of this.
034 * Packages provide logical namespace to classes and should be stored in
035 * the form of directory levels to provide physical grouping to your classes.
036 * These directories are added to the classpath so that your classes
037 * are visible to JVM when it runs the code.
038 *
039 * @author <a href="mailto:simon@redhillconsulting.com.au">Simon Harris</a>
040 * @author Oliver Burn
041 * @author Vikramaditya Kukreja
042 */
043public final class PackageDeclarationCheck extends AbstractCheck {
044
045    /**
046     * A key is pointing to the warning message text in "messages.properties"
047     * file.
048     */
049    public static final String MSG_KEY_MISSING = "missing.package.declaration";
050
051    /**
052     * A key is pointing to the warning message text in "messages.properties"
053     * file.
054     */
055    public static final String MSG_KEY_MISMATCH = "mismatch.package.directory";
056
057    /** Line number used to log violation when no AST nodes are present in file. */
058    private static final int DEFAULT_LINE_NUMBER = 1;
059
060    /** Is package defined. */
061    private boolean defined;
062
063    /** Whether to check for directory and package name match. */
064    private boolean matchDirectoryStructure = true;
065
066    /**
067     * Set whether to check for directory and package name match.
068     * @param matchDirectoryStructure the new value.
069     */
070    public void setMatchDirectoryStructure(boolean matchDirectoryStructure) {
071        this.matchDirectoryStructure = matchDirectoryStructure;
072    }
073
074    @Override
075    public int[] getDefaultTokens() {
076        return new int[] {TokenTypes.PACKAGE_DEF};
077    }
078
079    @Override
080    public int[] getRequiredTokens() {
081        return getDefaultTokens();
082    }
083
084    @Override
085    public int[] getAcceptableTokens() {
086        return new int[] {TokenTypes.PACKAGE_DEF};
087    }
088
089    @Override
090    public void beginTree(DetailAST ast) {
091        defined = false;
092    }
093
094    @Override
095    public void finishTree(DetailAST ast) {
096        if (!defined) {
097            int lineNumber = DEFAULT_LINE_NUMBER;
098            if (ast != null) {
099                lineNumber = ast.getLineNo();
100            }
101            log(lineNumber, MSG_KEY_MISSING);
102        }
103    }
104
105    @Override
106    public void visitToken(DetailAST ast) {
107        defined = true;
108
109        if (matchDirectoryStructure) {
110
111            final DetailAST packageNameAst = ast.getLastChild().getPreviousSibling();
112            final FullIdent fullIdent = FullIdent.createFullIdent(packageNameAst);
113            final String packageName = fullIdent.getText().replace('.', File.separatorChar);
114
115            final String directoryName = getDirectoryName();
116
117            if (!directoryName.endsWith(packageName)) {
118                log(fullIdent.getLineNo(), MSG_KEY_MISMATCH, packageName);
119            }
120        }
121    }
122
123    /**
124     * Returns the directory name this file is in.
125     * @return Directory name.
126     */
127    private String getDirectoryName() {
128        final String fileName = getFileContents().getFileName();
129        final int lastSeparatorPos = fileName.lastIndexOf(File.separatorChar);
130        return fileName.substring(0, lastSeparatorPos);
131    }
132}