001/* 002 * SonarQube 003 * Copyright (C) 2009-2016 SonarSource SA 004 * mailto:contact AT sonarsource DOT com 005 * 006 * This program 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 * This program 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 License 017 * along with this program; if not, write to the Free Software Foundation, 018 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 019 */ 020package org.sonar.api.profiles; 021 022import org.apache.commons.lang.StringUtils; 023import org.sonar.api.server.ServerSide; 024import org.sonar.api.rules.Rule; 025import org.sonar.api.rules.RuleAnnotationUtils; 026import org.sonar.api.rules.RuleFinder; 027import org.sonar.api.rules.RulePriority; 028import org.sonar.api.utils.ValidationMessages; 029import org.sonar.check.BelongsToProfile; 030 031import java.util.Collection; 032 033/** 034 * @since 2.3 035 */ 036@ServerSide 037public final class AnnotationProfileParser { 038 039 private final RuleFinder ruleFinder; 040 041 public AnnotationProfileParser(RuleFinder ruleFinder) { 042 this.ruleFinder = ruleFinder; 043 } 044 045 public RulesProfile parse(String repositoryKey, String profileName, String language, Collection<Class> annotatedClasses, ValidationMessages messages) { 046 RulesProfile profile = RulesProfile.create(profileName, language); 047 for (Class<?> aClass : annotatedClasses) { 048 BelongsToProfile belongsToProfile = aClass.getAnnotation(BelongsToProfile.class); 049 addRule(aClass, belongsToProfile, profile, repositoryKey, messages); 050 } 051 return profile; 052 } 053 054 private void addRule(Class aClass, BelongsToProfile annotation, RulesProfile profile, String repositoryKey, ValidationMessages messages) { 055 if ((annotation != null) && StringUtils.equals(annotation.title(), profile.getName())) { 056 String ruleKey = RuleAnnotationUtils.getRuleKey(aClass); 057 Rule rule = ruleFinder.findByKey(repositoryKey, ruleKey); 058 if (rule == null) { 059 messages.addWarningText("Rule not found: [repository=" + repositoryKey + ", key=" + ruleKey + "]"); 060 061 } else { 062 RulePriority priority = null; 063 if (annotation.priority() != null) { 064 priority = RulePriority.fromCheckPriority(annotation.priority()); 065 } 066 profile.activateRule(rule, priority); 067 } 068 } 069 } 070}