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