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 java.util.Collection;
023import org.apache.commons.lang.StringUtils;
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.ce.ComputeEngineSide;
029import org.sonar.api.server.ServerSide;
030import org.sonar.api.utils.ValidationMessages;
031import org.sonar.check.BelongsToProfile;
032
033/**
034 * @since 2.3
035 */
036@ServerSide
037@ComputeEngineSide
038public final class AnnotationProfileParser {
039
040  private final RuleFinder ruleFinder;
041
042  public AnnotationProfileParser(RuleFinder ruleFinder) {
043    this.ruleFinder = ruleFinder;
044  }
045
046  public RulesProfile parse(String repositoryKey, String profileName, String language, Collection<Class> annotatedClasses, ValidationMessages messages) {
047    RulesProfile profile = RulesProfile.create(profileName, language);
048    for (Class<?> aClass : annotatedClasses) {
049      BelongsToProfile belongsToProfile = aClass.getAnnotation(BelongsToProfile.class);
050      addRule(aClass, belongsToProfile, profile, repositoryKey, messages);
051    }
052    return profile;
053  }
054
055  private void addRule(Class aClass, BelongsToProfile annotation, RulesProfile profile, String repositoryKey, ValidationMessages messages) {
056    if ((annotation != null) && StringUtils.equals(annotation.title(), profile.getName())) {
057      String ruleKey = RuleAnnotationUtils.getRuleKey(aClass);
058      Rule rule = ruleFinder.findByKey(repositoryKey, ruleKey);
059      if (rule == null) {
060        messages.addWarningText("Rule not found: [repository=" + repositoryKey + ", key=" + ruleKey + "]");
061
062      } else {
063        RulePriority priority = null;
064        if (annotation.priority() != null) {
065          priority = RulePriority.fromCheckPriority(annotation.priority());
066        }
067        profile.activateRule(rule, priority);
068      }
069    }
070  }
071}