/** @return */
  public List<PhpCodeSnifferViolation> getViolations(File reportFile) {
    LOG.debug("Report file for PHP_CodeSniffer is " + reportFile);
    if (reportFile == null || !reportFile.exists()) {
      throw new SonarException("The XML report '" + reportFile + "' can't be found");
    }
    String reportPath = reportFile.getAbsolutePath();
    LOG.debug("Getting violations form report file");
    List<PhpCodeSnifferViolation> violations = new ArrayList<PhpCodeSnifferViolation>();
    try { // <checkstyle>
      SMInputFactory inputFactory =
          new SMInputFactory(XMLInputFactory.newInstance()); // <checkstyle>
      SMInputCursor rootNodeCursor = inputFactory.rootElementCursor(reportFile).advance(); // <file>

      SMInputCursor fileNodeCursor = rootNodeCursor.childElementCursor(FILE_NODE_NAME).advance();
      while (fileNodeCursor.asEvent() != null) {
        String fileName = fileNodeCursor.getAttrValue(FILE_NAME_ATTRIBUTE_NAME);
        SMInputCursor violationNodeCursor =
            fileNodeCursor.childElementCursor().advance(); // <error>
        while (violationNodeCursor.asEvent() != null) {
          violations.add(getViolation(fileName, violationNodeCursor));
          violationNodeCursor.advance();
        }
        fileNodeCursor.advance();
      }
      rootNodeCursor.getStreamReader().closeCompletely();
    } catch (XMLStreamException e) {
      throw new XmlParserException("Unable to parse the  XML Report '" + reportPath + "'", e);
    }
    return violations;
  }
Example #2
0
  private ValgrindError parseErrorTag(SMInputCursor error)
      throws javax.xml.stream.XMLStreamException {
    SMInputCursor child = error.childElementCursor();

    String kind = null;
    String text = null;
    ValgrindStack stack = null;
    while (child.getNext() != null) {
      String tagName = child.getLocalName();
      if ("kind".equalsIgnoreCase(tagName)) {
        kind = child.getElemStringValue();
      } else if ("xwhat".equalsIgnoreCase(tagName)) {
        text = child.childElementCursor("text").advance().getElemStringValue();
      } else if ("what".equalsIgnoreCase(tagName)) {
        text = child.getElemStringValue();
      } else if ("stack".equalsIgnoreCase(tagName)) {
        stack = parseStackTag(child);
      }
    }

    if (text == null || kind == null || stack == null) {
      String msg =
          "Valgrind error is incomplete: we require all of 'kind', '*what.text' and 'stack'";
      child.throwStreamException(msg);
    }

    return new ValgrindError(kind, text, stack);
  }
  private void processRules(
      SMInputCursor rulesCursor, RulesProfile profile, ValidationMessages messages)
      throws XMLStreamException {
    Map<String, String> parameters = new HashMap<>();
    while (rulesCursor.getNext() != null) {
      SMInputCursor ruleCursor = rulesCursor.childElementCursor();

      String repositoryKey = null;
      String key = null;
      RulePriority priority = null;
      parameters.clear();

      while (ruleCursor.getNext() != null) {
        String nodeName = ruleCursor.getLocalName();

        if (StringUtils.equals("repositoryKey", nodeName)) {
          repositoryKey = StringUtils.trim(ruleCursor.collectDescendantText(false));

        } else if (StringUtils.equals("key", nodeName)) {
          key = StringUtils.trim(ruleCursor.collectDescendantText(false));

        } else if (StringUtils.equals("priority", nodeName)) {
          priority =
              RulePriority.valueOf(StringUtils.trim(ruleCursor.collectDescendantText(false)));

        } else if (StringUtils.equals("parameters", nodeName)) {
          SMInputCursor propsCursor = ruleCursor.childElementCursor("parameter");
          processParameters(propsCursor, parameters);
        }
      }

      Rule rule = ruleFinder.findByKey(repositoryKey, key);
      if (rule == null) {
        messages.addWarningText("Rule not found: " + ruleToString(repositoryKey, key));

      } else {
        ActiveRule activeRule = profile.activateRule(rule, priority);
        for (Map.Entry<String, String> entry : parameters.entrySet()) {
          if (rule.getParam(entry.getKey()) == null) {
            messages.addWarningText(
                "The parameter '"
                    + entry.getKey()
                    + "' does not exist in the rule: "
                    + ruleToString(repositoryKey, key));
          } else {
            activeRule.setParameter(entry.getKey(), entry.getValue());
          }
        }
      }
    }
  }
  private void loadRuleKeys() {
    XMLInputFactory xmlFactory = XMLInputFactory.newInstance();
    xmlFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
    xmlFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.FALSE);
    // just so it won't try to load DTD in if there's DOCTYPE
    xmlFactory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE);
    xmlFactory.setProperty(XMLInputFactory.IS_VALIDATING, Boolean.FALSE);
    SMInputFactory inputFactory = new SMInputFactory(xmlFactory);
    InputStream inputStream =
        getClass().getResourceAsStream(AndroidLintRulesDefinition.RULES_XML_PATH);
    InputStreamReader reader = new InputStreamReader(inputStream, Charsets.UTF_8);
    try {
      SMHierarchicCursor rootC = inputFactory.rootElementCursor(reader);
      rootC.advance(); // <rules>

      SMInputCursor rulesC = rootC.childElementCursor("rule");
      while (rulesC.getNext() != null) {
        // <rule>
        SMInputCursor cursor = rulesC.childElementCursor();
        while (cursor.getNext() != null) {
          if (StringUtils.equalsIgnoreCase("key", cursor.getLocalName())) {
            String key = StringUtils.trim(cursor.collectDescendantText(false));
            ruleKeys.add(key);
          }
        }
      }

    } catch (XMLStreamException e) {
      throw new IllegalStateException("XML is not valid", e);
    }
  }
  public RulesProfile parse(Reader reader, ValidationMessages messages) {
    RulesProfile profile = RulesProfile.create();
    SMInputFactory inputFactory = initStax();
    try {
      SMHierarchicCursor rootC = inputFactory.rootElementCursor(reader);
      rootC.advance(); // <profile>
      SMInputCursor cursor = rootC.childElementCursor();
      while (cursor.getNext() != null) {
        String nodeName = cursor.getLocalName();
        if (StringUtils.equals("rules", nodeName)) {
          SMInputCursor rulesCursor = cursor.childElementCursor("rule");
          processRules(rulesCursor, profile, messages);

        } else if (StringUtils.equals("name", nodeName)) {
          profile.setName(StringUtils.trim(cursor.collectDescendantText(false)));

        } else if (StringUtils.equals("language", nodeName)) {
          profile.setLanguage(StringUtils.trim(cursor.collectDescendantText(false)));
        }
      }
    } catch (XMLStreamException e) {
      messages.addErrorText("XML is not valid: " + e.getMessage());
    }
    checkProfile(profile, messages);
    return profile;
  }
  private ParamStruct processParameter(SMInputCursor ruleC) throws XMLStreamException {
    ParamStruct param = new ParamStruct();

    // BACKWARD COMPATIBILITY WITH DEPRECATED FORMAT
    String keyAttribute = ruleC.getAttrValue("key");
    if (StringUtils.isNotBlank(keyAttribute)) {
      param.key = StringUtils.trim(keyAttribute);
    }

    // BACKWARD COMPATIBILITY WITH DEPRECATED FORMAT
    String typeAttribute = ruleC.getAttrValue("type");
    if (StringUtils.isNotBlank(typeAttribute)) {
      param.type = RuleParamType.parse(typeAttribute);
    }

    SMInputCursor paramC = ruleC.childElementCursor();
    while (paramC.getNext() != null) {
      String propNodeName = paramC.getLocalName();
      String propText = StringUtils.trim(paramC.collectDescendantText(false));
      if (StringUtils.equalsIgnoreCase("key", propNodeName)) {
        param.key = propText;

      } else if (StringUtils.equalsIgnoreCase("description", propNodeName)) {
        param.description = propText;

      } else if (StringUtils.equalsIgnoreCase("type", propNodeName)) {
        param.type = RuleParamType.parse(propText);

      } else if (StringUtils.equalsIgnoreCase("defaultValue", propNodeName)) {
        param.defaultValue = propText;
      }
    }
    return param;
  }
 public List<Block> parse(
     ComponentDto component, @Nullable String duplicationsData, DbSession session) {
   Map<String, ComponentDto> componentsByKey = newHashMap();
   List<Block> blocks = newArrayList();
   if (duplicationsData != null) {
     try {
       SMInputFactory inputFactory = initStax();
       SMHierarchicCursor root =
           inputFactory.rootElementCursor(new StringReader(duplicationsData));
       root.advance(); // <duplications>
       SMInputCursor cursor = root.childElementCursor("g");
       while (cursor.getNext() != null) {
         List<Duplication> duplications = newArrayList();
         SMInputCursor bCursor = cursor.childElementCursor("b");
         while (bCursor.getNext() != null) {
           String from = bCursor.getAttrValue("s");
           String size = bCursor.getAttrValue("l");
           String componentKey = bCursor.getAttrValue("r");
           if (from != null && size != null && componentKey != null) {
             duplications.add(
                 createDuplication(componentsByKey, from, size, componentKey, session));
           }
         }
         Collections.sort(
             duplications, new DuplicationComparator(component.uuid(), component.projectUuid()));
         blocks.add(new Block(duplications));
       }
       Collections.sort(blocks, new BlockComparator());
     } catch (XMLStreamException e) {
       throw new IllegalStateException("XML is not valid", e);
     }
   }
   return blocks;
 }
Example #8
0
  private void collectRangeMeasures(
      SMInputCursor function,
      Map<String, CoverageMeasuresBuilder> coverageData,
      int conditions,
      int coveredConditions)
      throws XMLStreamException {
    SMInputCursor range =
        function.childElementCursor("ranges").advance().childElementCursor("range");
    CoverageMeasuresBuilder builder = null;
    String lastSourceId = "";

    while (range.getNext() != null) {
      String sourceId = range.getAttrValue("source_id");
      int startLine = Integer.parseInt(range.getAttrValue("start_line"));
      int endLine = Integer.parseInt(range.getAttrValue("end_line"));
      int covered =
          !"no".equalsIgnoreCase(range.getAttrValue("covered")) ? 1 : 0; // value: yes/no/partial

      if (!sourceId.equals(lastSourceId) || builder == null) {
        builder = coverageData.get(sourceId);
        if (builder == null) {
          builder = CoverageMeasuresBuilder.create();
          coverageData.put(sourceId, builder);
        }

        builder.setConditions(startLine - 1, conditions, coveredConditions);
        lastSourceId = sourceId;
      }

      while (startLine <= endLine) {
        builder.setHits(startLine, covered);
        startLine++;
      }
    }
  }
 private void processProperties(SMInputCursor ruleCursor, ActiveRule activeRule)
     throws XMLStreamException {
   SMInputCursor propertyCursor = ruleCursor.childElementCursor(PROPERTY_NODE);
   while (propertyCursor.getNext() != null) {
     String key = propertyCursor.getAttrValue(PROPERTY_NAME_ATTR);
     String value = propertyCursor.getAttrValue(PROPERTY_VALUE_ATTR);
     activeRule.setParameter(key, value);
   }
 }
Example #10
0
 private void collectFunctionMeasures(
     SMInputCursor functions, Map<String, CoverageMeasuresBuilder> coverageData)
     throws XMLStreamException {
   SMInputCursor function = functions.childElementCursor("function");
   while (function.getNext() != null) {
     int blocksCovered = Integer.parseInt(function.getAttrValue("blocks_covered"));
     int blocksNotCovered = Integer.parseInt(function.getAttrValue("blocks_not_covered"));
     collectRangeMeasures(function, coverageData, blocksCovered + blocksNotCovered, blocksCovered);
   }
 }
Example #11
0
  private static void processRule(Rule rule, SMInputCursor ruleC) throws XMLStreamException {
    /* BACKWARD COMPATIBILITY WITH DEPRECATED FORMAT */
    String keyAttribute = ruleC.getAttrValue("key");
    if (StringUtils.isNotBlank(keyAttribute)) {
      rule.setKey(StringUtils.trim(keyAttribute));
    }

    /* BACKWARD COMPATIBILITY WITH DEPRECATED FORMAT */
    String priorityAttribute = ruleC.getAttrValue("priority");
    if (StringUtils.isNotBlank(priorityAttribute)) {
      rule.setSeverity(RulePriority.valueOf(StringUtils.trim(priorityAttribute)));
    }

    List<String> tags = Lists.newArrayList();
    SMInputCursor cursor = ruleC.childElementCursor();

    while (cursor.getNext() != null) {
      String nodeName = cursor.getLocalName();

      if (StringUtils.equalsIgnoreCase("name", nodeName)) {
        rule.setName(StringUtils.trim(cursor.collectDescendantText(false)));

      } else if (StringUtils.equalsIgnoreCase("description", nodeName)) {
        rule.setDescription(StringUtils.trim(cursor.collectDescendantText(false)));

      } else if (StringUtils.equalsIgnoreCase("key", nodeName)) {
        rule.setKey(StringUtils.trim(cursor.collectDescendantText(false)));

      } else if (StringUtils.equalsIgnoreCase("configKey", nodeName)) {
        rule.setConfigKey(StringUtils.trim(cursor.collectDescendantText(false)));

      } else if (StringUtils.equalsIgnoreCase("priority", nodeName)) {
        rule.setSeverity(
            RulePriority.valueOf(StringUtils.trim(cursor.collectDescendantText(false))));

      } else if (StringUtils.equalsIgnoreCase("cardinality", nodeName)) {
        rule.setCardinality(
            Cardinality.valueOf(StringUtils.trim(cursor.collectDescendantText(false))));

      } else if (StringUtils.equalsIgnoreCase("status", nodeName)) {
        rule.setStatus(StringUtils.trim(cursor.collectDescendantText(false)));

      } else if (StringUtils.equalsIgnoreCase("param", nodeName)) {
        processParameter(rule, cursor);

      } else if (StringUtils.equalsIgnoreCase("tag", nodeName)) {
        tags.add(StringUtils.trim(cursor.collectDescendantText(false)));
      }
    }
    if (Strings.isNullOrEmpty(rule.getKey())) {
      throw new SonarException("Node <key> is missing in <rule>");
    }
    rule.setTags(tags.toArray(new String[tags.size()]));
  }
Example #12
0
 private void collectSourceFileMeasures(
     SMInputCursor sourceFiles, Map<String, CoverageMeasuresBuilder> coverageData)
     throws XMLStreamException {
   SMInputCursor sourceFile = sourceFiles.childElementCursor("source_file");
   while (sourceFile.getNext() != null) {
     String id = sourceFile.getAttrValue("id");
     String normalPath = CxxUtils.normalizePath(sourceFile.getAttrValue("path"));
     CoverageMeasuresBuilder builder = coverageData.remove(id);
     if (normalPath != null) {
       coverageData.put(normalPath, builder); // replace id with path
     }
   }
 }
Example #13
0
 private void handleModuleItems(
     SMInputCursor module, Map<String, CoverageMeasuresBuilder> coverageData)
     throws XMLStreamException {
   SMInputCursor child = module.childElementCursor();
   while (child.getNext() != null) {
     String name = child.getLocalName();
     if ("functions".equalsIgnoreCase(name)) {
       collectFunctionMeasures(child, coverageData);
     } else if ("source_files".equalsIgnoreCase(name)) {
       collectSourceFileMeasures(child, coverageData);
     }
   }
 }
Example #14
0
  private ValgrindStack parseStackTag(SMInputCursor child)
      throws javax.xml.stream.XMLStreamException {
    ValgrindStack stack = new ValgrindStack();
    SMInputCursor frameCursor = child.childElementCursor("frame");
    while (frameCursor.getNext() != null) {

      SMInputCursor frameChild = frameCursor.childElementCursor();

      String ip = null;
      String obj = null;
      String fn = null;
      String dir = null;
      String file = null;
      String line = null;

      while (frameChild.getNext() != null) {
        String tagName = frameChild.getLocalName();

        if ("ip".equalsIgnoreCase(tagName)) {
          ip = frameChild.getElemStringValue();
        } else if ("obj".equalsIgnoreCase(tagName)) {
          obj = frameChild.getElemStringValue();
        } else if ("fn".equalsIgnoreCase(tagName)) {
          fn = frameChild.getElemStringValue();
        } else if ("dir".equalsIgnoreCase(tagName)) {
          dir = frameChild.getElemStringValue();
        } else if ("file".equalsIgnoreCase(tagName)) {
          file = frameChild.getElemStringValue();
        } else if ("line".equalsIgnoreCase(tagName)) {
          line = frameChild.getElemStringValue();
        }
      }
      stack.addFrame(new ValgrindFrame(ip, obj, fn, dir, file, line));
    }

    return stack;
  }
  private static void collectFileData(SMInputCursor clazz, CoverageMeasuresBuilder builder)
      throws XMLStreamException {
    SMInputCursor line = clazz.childElementCursor("lines").advance().childElementCursor("line");
    while (line.getNext() != null) {
      int lineId = Integer.parseInt(line.getAttrValue("number"));
      try {
        builder.setHits(lineId, (int) parseNumber(line.getAttrValue("hits"), ENGLISH));
      } catch (ParseException e) {
        throw new XmlParserException(e);
      }

      String isBranch = line.getAttrValue("branch");
      String text = line.getAttrValue("condition-coverage");
      if (StringUtils.equals(isBranch, "true") && StringUtils.isNotBlank(text)) {
        String[] conditions = StringUtils.split(StringUtils.substringBetween(text, "(", ")"), "/");
        builder.setConditions(
            lineId, Integer.parseInt(conditions[1]), Integer.parseInt(conditions[0]));
      }
    }
  }
  private static void processParameters(SMInputCursor propsCursor, Map<String, String> parameters)
      throws XMLStreamException {
    while (propsCursor.getNext() != null) {
      SMInputCursor propCursor = propsCursor.childElementCursor();
      String key = null;
      String value = null;
      while (propCursor.getNext() != null) {
        String nodeName = propCursor.getLocalName();
        if (StringUtils.equals("key", nodeName)) {
          key = StringUtils.trim(propCursor.collectDescendantText(false));

        } else if (StringUtils.equals("value", nodeName)) {
          value = StringUtils.trim(propCursor.collectDescendantText(false));
        }
      }
      if (key != null) {
        parameters.put(key, value);
      }
    }
  }
Example #17
0
  private static void processParameter(Rule rule, SMInputCursor ruleC) throws XMLStreamException {
    RuleParam param = rule.createParameter();

    String keyAttribute = ruleC.getAttrValue("key");
    if (StringUtils.isNotBlank(keyAttribute)) {
      /* BACKWARD COMPATIBILITY WITH DEPRECATED FORMAT */
      param.setKey(StringUtils.trim(keyAttribute));
    }

    String typeAttribute = ruleC.getAttrValue("type");
    if (StringUtils.isNotBlank(typeAttribute)) {
      /* BACKWARD COMPATIBILITY WITH DEPRECATED FORMAT */
      param.setType(type(StringUtils.trim(typeAttribute)));
    }

    SMInputCursor paramC = ruleC.childElementCursor();
    while (paramC.getNext() != null) {
      String propNodeName = paramC.getLocalName();
      String propText = StringUtils.trim(paramC.collectDescendantText(false));
      if (StringUtils.equalsIgnoreCase("key", propNodeName)) {
        param.setKey(propText);

      } else if (StringUtils.equalsIgnoreCase("description", propNodeName)) {
        param.setDescription(propText);

      } else if (StringUtils.equalsIgnoreCase("type", propNodeName)) {
        param.setType(type(propText));

      } else if (StringUtils.equalsIgnoreCase("defaultValue", propNodeName)) {
        param.setDefaultValue(propText);
      }
    }
    if (Strings.isNullOrEmpty(param.getKey())) {
      throw new SonarException("Node <key> is missing in <param>");
    }
  }
  private void processRule(RulesDefinition.NewExtendedRepository repo, SMInputCursor ruleC)
      throws XMLStreamException {
    String key = null;
    String name = null;
    String description = null;
    String internalKey = null;
    String severity = Severity.defaultSeverity();
    String status = null;
    Cardinality cardinality = Cardinality.SINGLE;
    List<ParamStruct> params = new ArrayList<>();
    List<String> tags = new ArrayList<>();

    /* BACKWARD COMPATIBILITY WITH VERY OLD FORMAT */
    String keyAttribute = ruleC.getAttrValue("key");
    if (StringUtils.isNotBlank(keyAttribute)) {
      key = StringUtils.trim(keyAttribute);
    }
    String priorityAttribute = ruleC.getAttrValue("priority");
    if (StringUtils.isNotBlank(priorityAttribute)) {
      severity = StringUtils.trim(priorityAttribute);
    }

    SMInputCursor cursor = ruleC.childElementCursor();
    while (cursor.getNext() != null) {
      String nodeName = cursor.getLocalName();

      if (StringUtils.equalsIgnoreCase("name", nodeName)) {
        name = StringUtils.trim(cursor.collectDescendantText(false));

      } else if (StringUtils.equalsIgnoreCase("description", nodeName)) {
        description = StringUtils.trim(cursor.collectDescendantText(false));

      } else if (StringUtils.equalsIgnoreCase("key", nodeName)) {
        key = StringUtils.trim(cursor.collectDescendantText(false));

      } else if (StringUtils.equalsIgnoreCase("configKey", nodeName)) {
        // deprecated field, replaced by internalKey
        internalKey = StringUtils.trim(cursor.collectDescendantText(false));

      } else if (StringUtils.equalsIgnoreCase("internalKey", nodeName)) {
        internalKey = StringUtils.trim(cursor.collectDescendantText(false));

      } else if (StringUtils.equalsIgnoreCase("priority", nodeName)) {
        // deprecated field, replaced by severity
        severity = StringUtils.trim(cursor.collectDescendantText(false));

      } else if (StringUtils.equalsIgnoreCase("severity", nodeName)) {
        severity = StringUtils.trim(cursor.collectDescendantText(false));

      } else if (StringUtils.equalsIgnoreCase("cardinality", nodeName)) {
        cardinality = Cardinality.valueOf(StringUtils.trim(cursor.collectDescendantText(false)));

      } else if (StringUtils.equalsIgnoreCase("status", nodeName)) {
        status = StringUtils.trim(cursor.collectDescendantText(false));

      } else if (StringUtils.equalsIgnoreCase("param", nodeName)) {
        params.add(processParameter(cursor));

      } else if (StringUtils.equalsIgnoreCase("tag", nodeName)) {
        tags.add(StringUtils.trim(cursor.collectDescendantText(false)));
      }
    }
    RulesDefinition.NewRule rule =
        repo.createRule(key)
            .setHtmlDescription(description)
            .setSeverity(severity)
            .setName(name)
            .setInternalKey(internalKey)
            .setTags(tags.toArray(new String[tags.size()]))
            .setTemplate(cardinality == Cardinality.MULTIPLE);
    if (status != null) {
      rule.setStatus(RuleStatus.valueOf(status));
    }
    for (ParamStruct param : params) {
      rule.createParam(param.key)
          .setDefaultValue(param.defaultValue)
          .setType(param.type)
          .setDescription(param.description);
    }
  }