001/*
002 * Sonar, open source software quality management tool.
003 * Copyright (C) 2008-2012 SonarSource
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 */
020package org.sonar.plugins.findbugs;
021
022import java.io.IOException;
023import java.io.Writer;
024import java.util.List;
025
026import org.sonar.api.profiles.ProfileExporter;
027import org.sonar.api.profiles.RulesProfile;
028import org.sonar.api.resources.Java;
029import org.sonar.api.rules.ActiveRule;
030import org.sonar.api.utils.SonarException;
031import org.sonar.plugins.findbugs.xml.Bug;
032import org.sonar.plugins.findbugs.xml.FindBugsFilter;
033import org.sonar.plugins.findbugs.xml.Match;
034
035import com.thoughtworks.xstream.XStream;
036
037public class FindbugsProfileExporter extends ProfileExporter {
038
039  public FindbugsProfileExporter() {
040    super(FindbugsConstants.REPOSITORY_KEY, FindbugsConstants.PLUGIN_NAME);
041    setSupportedLanguages(Java.KEY);
042    setMimeType("application/xml");
043  }
044
045  @Override
046  public void exportProfile(RulesProfile profile, Writer writer) {
047    try {
048      FindBugsFilter filter = buildFindbugsFilter(profile.getActiveRulesByRepository(FindbugsConstants.REPOSITORY_KEY));
049      XStream xstream = FindBugsFilter.createXStream();
050      writer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!-- Generated by Sonar -->\n".concat(xstream.toXML(filter)));
051    } catch (IOException e) {
052      throw new SonarException("Fail to export the Findbugs profile : " + profile, e);
053    }
054  }
055
056  protected static FindBugsFilter buildFindbugsFilter(List<ActiveRule> activeRules) {
057    FindBugsFilter root = new FindBugsFilter();
058    for (ActiveRule activeRule : activeRules) {
059      if (FindbugsConstants.REPOSITORY_KEY.equals(activeRule.getRepositoryKey())) {
060        Match child = new Match();
061        child.setBug(new Bug(activeRule.getConfigKey()));
062        root.addMatch(child);
063      }
064    }
065    return root;
066  }
067}