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.rules;
021
022import com.google.common.annotations.VisibleForTesting;
023import com.google.common.base.Strings;
024import com.google.common.collect.Lists;
025import com.google.common.collect.Maps;
026import com.google.common.io.Closeables;
027import org.apache.commons.io.FileUtils;
028import org.apache.commons.lang.CharEncoding;
029import org.apache.commons.lang.StringUtils;
030import org.codehaus.staxmate.SMInputFactory;
031import org.codehaus.staxmate.in.SMHierarchicCursor;
032import org.codehaus.staxmate.in.SMInputCursor;
033import org.sonar.api.PropertyType;
034import org.sonar.api.ServerComponent;
035import org.sonar.api.utils.SonarException;
036import org.sonar.check.Cardinality;
037
038import javax.xml.stream.XMLInputFactory;
039import javax.xml.stream.XMLStreamException;
040
041import java.io.*;
042import java.util.ArrayList;
043import java.util.List;
044import java.util.Map;
045
046/**
047 * @since 2.3
048 * @deprecated in 4.2. Replaced by org.sonar.api.server.rule.RulesDefinition and org.sonar.api.server.rule.RulesDefinitionXmlLoader
049 */
050@Deprecated
051public final class XMLRuleParser implements ServerComponent {
052  private static final Map<String, String> TYPE_MAP = typeMapWithDeprecatedValues();
053
054  public List<Rule> parse(File file) {
055    Reader reader = null;
056    try {
057      reader = new InputStreamReader(FileUtils.openInputStream(file), CharEncoding.UTF_8);
058      return parse(reader);
059
060    } catch (IOException e) {
061      throw new SonarException("Fail to load the file: " + file, e);
062
063    } finally {
064      Closeables.closeQuietly(reader);
065    }
066  }
067
068  /**
069   * Warning : the input stream is closed in this method
070   */
071  public List<Rule> parse(InputStream input) {
072    Reader reader = null;
073    try {
074      reader = new InputStreamReader(input, CharEncoding.UTF_8);
075      return parse(reader);
076
077    } catch (IOException e) {
078      throw new SonarException("Fail to load the xml stream", e);
079
080    } finally {
081      Closeables.closeQuietly(reader);
082    }
083  }
084
085  public List<Rule> parse(Reader reader) {
086    XMLInputFactory xmlFactory = XMLInputFactory.newInstance();
087    xmlFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
088    xmlFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.FALSE);
089    // just so it won't try to load DTD in if there's DOCTYPE
090    xmlFactory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE);
091    xmlFactory.setProperty(XMLInputFactory.IS_VALIDATING, Boolean.FALSE);
092    SMInputFactory inputFactory = new SMInputFactory(xmlFactory);
093    try {
094      SMHierarchicCursor rootC = inputFactory.rootElementCursor(reader);
095      rootC.advance(); // <rules>
096      List<Rule> rules = new ArrayList<Rule>();
097
098      SMInputCursor rulesC = rootC.childElementCursor("rule");
099      while (rulesC.getNext() != null) {
100        // <rule>
101        Rule rule = Rule.create();
102        rules.add(rule);
103
104        processRule(rule, rulesC);
105      }
106      return rules;
107
108    } catch (XMLStreamException e) {
109      throw new SonarException("XML is not valid", e);
110    }
111  }
112
113  private static void processRule(Rule rule, SMInputCursor ruleC) throws XMLStreamException {
114    /* BACKWARD COMPATIBILITY WITH DEPRECATED FORMAT */
115    String keyAttribute = ruleC.getAttrValue("key");
116    if (StringUtils.isNotBlank(keyAttribute)) {
117      rule.setKey(StringUtils.trim(keyAttribute));
118    }
119
120    /* BACKWARD COMPATIBILITY WITH DEPRECATED FORMAT */
121    String priorityAttribute = ruleC.getAttrValue("priority");
122    if (StringUtils.isNotBlank(priorityAttribute)) {
123      rule.setSeverity(RulePriority.valueOf(StringUtils.trim(priorityAttribute)));
124    }
125
126    List<String> tags = Lists.newArrayList();
127    SMInputCursor cursor = ruleC.childElementCursor();
128
129    while (cursor.getNext() != null) {
130      String nodeName = cursor.getLocalName();
131
132      if (StringUtils.equalsIgnoreCase("name", nodeName)) {
133        rule.setName(StringUtils.trim(cursor.collectDescendantText(false)));
134
135      } else if (StringUtils.equalsIgnoreCase("description", nodeName)) {
136        rule.setDescription(StringUtils.trim(cursor.collectDescendantText(false)));
137
138      } else if (StringUtils.equalsIgnoreCase("key", nodeName)) {
139        rule.setKey(StringUtils.trim(cursor.collectDescendantText(false)));
140
141      } else if (StringUtils.equalsIgnoreCase("configKey", nodeName)) {
142        rule.setConfigKey(StringUtils.trim(cursor.collectDescendantText(false)));
143
144      } else if (StringUtils.equalsIgnoreCase("priority", nodeName)) {
145        rule.setSeverity(RulePriority.valueOf(StringUtils.trim(cursor.collectDescendantText(false))));
146
147      } else if (StringUtils.equalsIgnoreCase("cardinality", nodeName)) {
148        rule.setCardinality(Cardinality.valueOf(StringUtils.trim(cursor.collectDescendantText(false))));
149
150      } else if (StringUtils.equalsIgnoreCase("status", nodeName)) {
151        rule.setStatus(StringUtils.trim(cursor.collectDescendantText(false)));
152
153      } else if (StringUtils.equalsIgnoreCase("param", nodeName)) {
154        processParameter(rule, cursor);
155
156      } else if (StringUtils.equalsIgnoreCase("tag", nodeName)) {
157        tags.add(StringUtils.trim(cursor.collectDescendantText(false)));
158      }
159    }
160    if (Strings.isNullOrEmpty(rule.getKey())) {
161      throw new SonarException("Node <key> is missing in <rule>");
162    }
163    rule.setTags(tags.toArray(new String[tags.size()]));
164  }
165
166  private static void processParameter(Rule rule, SMInputCursor ruleC) throws XMLStreamException {
167    RuleParam param = rule.createParameter();
168
169    String keyAttribute = ruleC.getAttrValue("key");
170    if (StringUtils.isNotBlank(keyAttribute)) {
171      /* BACKWARD COMPATIBILITY WITH DEPRECATED FORMAT */
172      param.setKey(StringUtils.trim(keyAttribute));
173    }
174
175    String typeAttribute = ruleC.getAttrValue("type");
176    if (StringUtils.isNotBlank(typeAttribute)) {
177      /* BACKWARD COMPATIBILITY WITH DEPRECATED FORMAT */
178      param.setType(type(StringUtils.trim(typeAttribute)));
179    }
180
181    SMInputCursor paramC = ruleC.childElementCursor();
182    while (paramC.getNext() != null) {
183      String propNodeName = paramC.getLocalName();
184      String propText = StringUtils.trim(paramC.collectDescendantText(false));
185      if (StringUtils.equalsIgnoreCase("key", propNodeName)) {
186        param.setKey(propText);
187
188      } else if (StringUtils.equalsIgnoreCase("description", propNodeName)) {
189        param.setDescription(propText);
190
191      } else if (StringUtils.equalsIgnoreCase("type", propNodeName)) {
192        param.setType(type(propText));
193
194      } else if (StringUtils.equalsIgnoreCase("defaultValue", propNodeName)) {
195        param.setDefaultValue(propText);
196      }
197    }
198    if (Strings.isNullOrEmpty(param.getKey())) {
199      throw new SonarException("Node <key> is missing in <param>");
200    }
201  }
202
203  private static Map<String, String> typeMapWithDeprecatedValues() {
204    Map<String, String> map = Maps.newHashMap();
205    map.put("i", PropertyType.INTEGER.name());
206    map.put("s", PropertyType.STRING.name());
207    map.put("b", PropertyType.BOOLEAN.name());
208    map.put("r", PropertyType.REGULAR_EXPRESSION.name());
209    map.put("s{}", "s{}");
210    map.put("i{}", "i{}");
211    for (PropertyType propertyType : PropertyType.values()) {
212      map.put(propertyType.name(), propertyType.name());
213    }
214    return map;
215  }
216
217  @VisibleForTesting
218  static String type(String type) {
219    String validType = TYPE_MAP.get(type);
220    if (null != validType) {
221      return validType;
222    }
223
224    if (type.matches(".\\[.+\\]")) {
225      return type;
226    }
227    throw new SonarException("Invalid property type [" + type + "]");
228  }
229
230}