001/*
002 * SonarQube, open source software quality management tool.
003 * Copyright (C) 2008-2014 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 java.io.InputStreamReader;
023import java.io.Reader;
024import java.nio.charset.StandardCharsets;
025import java.util.HashMap;
026import java.util.Map;
027import javax.xml.stream.XMLInputFactory;
028import javax.xml.stream.XMLStreamException;
029import org.apache.commons.io.IOUtils;
030import org.apache.commons.lang.StringUtils;
031import org.codehaus.staxmate.SMInputFactory;
032import org.codehaus.staxmate.in.SMHierarchicCursor;
033import org.codehaus.staxmate.in.SMInputCursor;
034import org.sonar.api.rules.ActiveRule;
035import org.sonar.api.rules.Rule;
036import org.sonar.api.rules.RuleFinder;
037import org.sonar.api.rules.RulePriority;
038import org.sonar.api.server.ServerSide;
039import org.sonar.api.utils.ValidationMessages;
040
041/**
042 * @since 2.3
043 */
044@ServerSide
045public class XMLProfileParser {
046
047  private final RuleFinder ruleFinder;
048
049  /**
050   * For backward compatibility.
051   *
052   * @deprecated since 2.5. Plugins shouldn't directly instantiate this class,
053   * because it should be retrieved as an IoC dependency.
054   */
055  @Deprecated
056  public XMLProfileParser(RuleFinder ruleFinder) {
057    this.ruleFinder = ruleFinder;
058  }
059
060  public RulesProfile parseResource(ClassLoader classloader, String xmlClassPath, ValidationMessages messages) {
061    Reader reader = new InputStreamReader(classloader.getResourceAsStream(xmlClassPath), StandardCharsets.UTF_8);
062    try {
063      return parse(reader, messages);
064
065    } finally {
066      IOUtils.closeQuietly(reader);
067    }
068  }
069
070  public RulesProfile parse(Reader reader, ValidationMessages messages) {
071    RulesProfile profile = RulesProfile.create();
072    SMInputFactory inputFactory = initStax();
073    try {
074      SMHierarchicCursor rootC = inputFactory.rootElementCursor(reader);
075      rootC.advance(); // <profile>
076      SMInputCursor cursor = rootC.childElementCursor();
077      while (cursor.getNext() != null) {
078        String nodeName = cursor.getLocalName();
079        if (StringUtils.equals("rules", nodeName)) {
080          SMInputCursor rulesCursor = cursor.childElementCursor("rule");
081          processRules(rulesCursor, profile, messages);
082
083        } else if (StringUtils.equals("name", nodeName)) {
084          profile.setName(StringUtils.trim(cursor.collectDescendantText(false)));
085
086        } else if (StringUtils.equals("language", nodeName)) {
087          profile.setLanguage(StringUtils.trim(cursor.collectDescendantText(false)));
088        }
089      }
090    } catch (XMLStreamException e) {
091      messages.addErrorText("XML is not valid: " + e.getMessage());
092    }
093    checkProfile(profile, messages);
094    return profile;
095  }
096
097  private static void checkProfile(RulesProfile profile, ValidationMessages messages) {
098    if (StringUtils.isBlank(profile.getName())) {
099      messages.addErrorText("The mandatory node <name> is missing.");
100    }
101    if (StringUtils.isBlank(profile.getLanguage())) {
102      messages.addErrorText("The mandatory node <language> is missing.");
103    }
104  }
105
106  private static SMInputFactory initStax() {
107    XMLInputFactory xmlFactory = XMLInputFactory.newInstance();
108    xmlFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
109    xmlFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.FALSE);
110    // just so it won't try to load DTD in if there's DOCTYPE
111    xmlFactory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE);
112    xmlFactory.setProperty(XMLInputFactory.IS_VALIDATING, Boolean.FALSE);
113    return new SMInputFactory(xmlFactory);
114  }
115
116  private void processRules(SMInputCursor rulesCursor, RulesProfile profile, ValidationMessages messages) throws XMLStreamException {
117    Map<String, String> parameters = new HashMap<>();
118    while (rulesCursor.getNext() != null) {
119      SMInputCursor ruleCursor = rulesCursor.childElementCursor();
120
121      String repositoryKey = null;
122      String key = null;
123      RulePriority priority = null;
124      parameters.clear();
125
126      while (ruleCursor.getNext() != null) {
127        String nodeName = ruleCursor.getLocalName();
128
129        if (StringUtils.equals("repositoryKey", nodeName)) {
130          repositoryKey = StringUtils.trim(ruleCursor.collectDescendantText(false));
131
132        } else if (StringUtils.equals("key", nodeName)) {
133          key = StringUtils.trim(ruleCursor.collectDescendantText(false));
134
135        } else if (StringUtils.equals("priority", nodeName)) {
136          priority = RulePriority.valueOf(StringUtils.trim(ruleCursor.collectDescendantText(false)));
137
138        } else if (StringUtils.equals("parameters", nodeName)) {
139          SMInputCursor propsCursor = ruleCursor.childElementCursor("parameter");
140          processParameters(propsCursor, parameters);
141        }
142      }
143
144      Rule rule = ruleFinder.findByKey(repositoryKey, key);
145      if (rule == null) {
146        messages.addWarningText("Rule not found: " + ruleToString(repositoryKey, key));
147
148      } else {
149        ActiveRule activeRule = profile.activateRule(rule, priority);
150        for (Map.Entry<String, String> entry : parameters.entrySet()) {
151          if (rule.getParam(entry.getKey()) == null) {
152            messages.addWarningText("The parameter '" + entry.getKey() + "' does not exist in the rule: " + ruleToString(repositoryKey, key));
153          } else {
154            activeRule.setParameter(entry.getKey(), entry.getValue());
155          }
156        }
157      }
158    }
159  }
160
161  private static String ruleToString(String repositoryKey, String key) {
162    return "[repository=" + repositoryKey + ", key=" + key + "]";
163  }
164
165  private static void processParameters(SMInputCursor propsCursor, Map<String, String> parameters) throws XMLStreamException {
166    while (propsCursor.getNext() != null) {
167      SMInputCursor propCursor = propsCursor.childElementCursor();
168      String key = null;
169      String value = null;
170      while (propCursor.getNext() != null) {
171        String nodeName = propCursor.getLocalName();
172        if (StringUtils.equals("key", nodeName)) {
173          key = StringUtils.trim(propCursor.collectDescendantText(false));
174
175        } else if (StringUtils.equals("value", nodeName)) {
176          value = StringUtils.trim(propCursor.collectDescendantText(false));
177        }
178      }
179      if (key != null) {
180        parameters.put(key, value);
181      }
182    }
183  }
184
185}