001/*
002 * SonarQube, open source software quality management tool.
003 * Copyright (C) 2008-2013 SonarSource
004 * mailto:contact AT sonarsource DOT com
005 *
006 * SonarQube 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 * SonarQube 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.ServerComponent;
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 */
036public final class AnnotationProfileParser implements ServerComponent {
037
038  private final RuleFinder ruleFinder;
039
040  public AnnotationProfileParser(RuleFinder ruleFinder) {
041    this.ruleFinder = ruleFinder;
042  }
043
044  public RulesProfile parse(String repositoryKey, String profileName, String language, Collection<Class> annotatedClasses, ValidationMessages messages) {
045    RulesProfile profile = RulesProfile.create(profileName, language);
046    for (Class<?> aClass : annotatedClasses) {
047      BelongsToProfile belongsToProfile = aClass.getAnnotation(BelongsToProfile.class);
048      addRule(aClass, belongsToProfile, profile, repositoryKey, messages);
049    }
050    return profile;
051  }
052
053  private void addRule(Class aClass, BelongsToProfile annotation, RulesProfile profile, String repositoryKey, ValidationMessages messages) {
054    if ((annotation != null) && StringUtils.equals(annotation.title(), profile.getName())) {
055      String ruleKey = RuleAnnotationUtils.getRuleKey(aClass);
056      Rule rule = ruleFinder.findByKey(repositoryKey, ruleKey);
057      if (rule == null) {
058        messages.addWarningText("Rule not found: [repository=" + repositoryKey + ", key=" + ruleKey + "]");
059
060      } else {
061        RulePriority priority = null;
062        if (annotation.priority() != null) {
063          priority = RulePriority.fromCheckPriority(annotation.priority());
064        }
065        profile.activateRule(rule, priority);
066      }
067    }
068  }
069}