001    /*
002     * Sonar, open source software quality management tool.
003     * Copyright (C) 2009 SonarSource SA
004     * mailto:contact AT sonarsource DOT com
005     *
006     * Sonar is free software; you can redistribute it and/or
007     * modify it under the terms of the GNU Lesser General Public
008     * License as published by the Free Software Foundation; either
009     * version 3 of the License, or (at your option) any later version.
010     *
011     * Sonar is distributed in the hope that it will be useful,
012     * but WITHOUT ANY WARRANTY; without even the implied warranty of
013     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014     * Lesser General Public License for more details.
015     *
016     * You should have received a copy of the GNU Lesser General Public
017     * License along with Sonar; if not, write to the Free Software
018     * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02
019     */
020    package org.sonar.squid.ast.visitor;
021    
022    import org.sonar.squid.api.SourcePackage;
023    import org.sonar.squid.api.SourceCode;
024    import org.sonar.squid.indexer.SquidIndex;
025    
026    import com.puppycrawl.tools.checkstyle.api.DetailAST;
027    import com.puppycrawl.tools.checkstyle.api.FullIdent;
028    import com.puppycrawl.tools.checkstyle.api.TokenTypes;
029    
030    public class PackageVisitor extends AstVisitor {
031    
032      private SquidIndex indexer;
033    
034      public PackageVisitor(SquidIndex indexer) {
035        this.indexer = indexer;
036      }
037    
038      @Override
039      public void visitFile(DetailAST ast) {
040        if (ast == null) {
041          // ast can be null for empty classes
042          return;
043        }
044        SourceCode packageRes = extractPackage(ast);
045        if (peekResource().hasChild(packageRes)) {
046          packageRes = indexer.search(packageRes.getKey());
047        }
048        addResource(packageRes);
049      }
050    
051      @Override
052      public void leaveFile(DetailAST ast) {
053        if (ast == null) {
054          // ast can be null for empty classes
055          return;
056        }
057        popResource();
058      }
059    
060      private SourcePackage extractPackage(DetailAST ast) {
061        SourcePackage packageRes;
062        if (ast.getType() != TokenTypes.PACKAGE_DEF) {
063          packageRes = new SourcePackage("[default]");
064        } else {
065          String packageName = FullIdent.createFullIdent(ast.getLastChild().getPreviousSibling()).getText();
066          packageRes = new SourcePackage(packageName);
067        }
068        return packageRes;
069      }
070    }