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.java.ast.visitor; 021 022 import org.sonar.squid.api.SourceCode; 023 import org.sonar.squid.api.SourcePackage; 024 import org.sonar.squid.indexer.SquidIndex; 025 import org.sonar.squid.measures.Metric; 026 027 import com.puppycrawl.tools.checkstyle.api.DetailAST; 028 import com.puppycrawl.tools.checkstyle.api.FullIdent; 029 import com.puppycrawl.tools.checkstyle.api.TokenTypes; 030 031 public class PackageVisitor extends AstVisitor { 032 033 private SquidIndex indexer; 034 035 public PackageVisitor(SquidIndex indexer) { 036 this.indexer = indexer; 037 } 038 039 @Override 040 public void visitFile(DetailAST ast) { 041 if (ast == null) { 042 // ast can be null for empty classes 043 return; 044 } 045 SourceCode packageRes = createSourcePackage(ast); 046 if (peekResource().hasChild(packageRes)) { 047 packageRes = indexer.search(packageRes.getKey()); 048 } 049 packageRes.setMeasure(Metric.PACKAGES, 1); 050 addResource(packageRes); 051 } 052 053 @Override 054 public void leaveFile(DetailAST ast) { 055 if (ast == null) { 056 // ast can be null for empty classes 057 return; 058 } 059 popResource(); 060 } 061 062 private SourcePackage createSourcePackage(DetailAST ast) { 063 SourcePackage packageRes; 064 if (ast.getType() != TokenTypes.PACKAGE_DEF) { 065 packageRes = new SourcePackage(""); 066 } else { 067 String packageName = FullIdent.createFullIdent(ast.getLastChild().getPreviousSibling()).getText(); 068 packageRes = new SourcePackage(packageName.replace('.', '/')); 069 } 070 return packageRes; 071 } 072 }