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 #2
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 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;
  }
 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 #5
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 #6
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 #7
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
     }
   }
 }
  @Override
  public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
    SMInputFactory inputFactory = initStax();
    RulesProfile profile = RulesProfile.create();

    try {
      SMHierarchicCursor rootC = inputFactory.rootElementCursor(reader);
      rootC.advance(); // <ruleset>
      SMInputCursor ruleCursor = rootC.childElementCursor(RULE_NODE);
      while (ruleCursor.getNext() != null) {
        String ruleKey = ruleCursor.getAttrValue(RULE_CLASS_ATTR);
        Rule rule = ruleFinder.findByKey(CodeNarcConstants.REPOSITORY_KEY, ruleKey);
        if (rule == null) {
          messages.addWarningText("CodeNarc rule '" + ruleKey + "' not found");
        } else {
          ActiveRule activeRule = profile.activateRule(rule, null);
          processProperties(ruleCursor, activeRule);
        }
      }

    } catch (XMLStreamException e) {
      messages.addErrorText("XML is not valid: " + e.getMessage());
    }
    return profile;
  }
  /** @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;
  }
 private void createViolation(SMInputCursor violationsCursor, Rule currentRule)
     throws XMLStreamException {
   org.sonar.api.resources.File sonarFile =
       org.sonar.api.resources.File.fromIOFile(
           new File(violationsCursor.getAttrValue("Source")), project);
   if (context.isIndexed(sonarFile, false)) {
     Violation violation = Violation.create(currentRule, sonarFile);
     String lineNumber = violationsCursor.getAttrValue("LineNumber");
     if (lineNumber != null) {
       violation.setLineId(Integer.parseInt(lineNumber));
     }
     violation.setMessage(violationsCursor.collectDescendantText().trim());
     violation.setSeverity(currentRule.getSeverity());
     context.saveViolation(violation);
   } else {
     LOG.debug("Violation could not be saved, associated resource not indexed " + sonarFile);
   }
 }
  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 void parseStyleCopViolationsBloc(SMInputCursor violationsCursor)
     throws XMLStreamException {
   // Cursor in on <Violations>
   StringBuffer configKey = new StringBuffer();
   RuleQuery ruleQuery = RuleQuery.create().withRepositoryKey(StyleCopConstants.REPOSITORY_KEY);
   while (violationsCursor.getNext() != null) {
     configKey.setLength(0);
     configKey.append(violationsCursor.getAttrValue("RuleNamespace"));
     configKey.append("#");
     configKey.append(violationsCursor.getAttrValue("Rule"));
     Rule currentRule = ruleFinder.find(ruleQuery.withConfigKey(configKey.toString()));
     if (currentRule != null) {
       createViolation(violationsCursor, currentRule);
     } else {
       LOG.warn(
           "Could not find the following rule in the StyleCop rule repository: "
               + configKey.toString());
     }
   }
 }
  private CoverageFileData collectCoverageData(SMInputCursor fileCursor) {
    try {
      String fileName = fileCursor.getAttrValue("name");

      InputFile sourceFile = delphiProjectHelper.findFileInDirectories(fileName);

      int totalLines = 0;
      int coveredLines = 0;

      CoverageFileData data = new CoverageFileData(sourceFile);
      SMInputCursor lineCursor = fileCursor.descendantElementCursor("line");
      while (lineCursor.getNext() != null) {
        if (!lineCursor.asEvent().isStartElement()) {
          continue;
        }
        String lineNumber = lineCursor.getAttrValue("number");
        boolean isCovered = Boolean.valueOf(lineCursor.getAttrValue("covered"));
        data.getLineHitsBuilder().add(lineNumber, isCovered ? 1 : 0);
        coveredLines += isCovered ? 1 : 0;
        ++totalLines;
      }

      data.setTotalLines(totalLines);
      data.setUncoveredLines(totalLines - coveredLines);
      DelphiUtils.LOG.debug(
          "Coverage ("
              + fileName
              + "): "
              + coveredLines
              + "/"
              + totalLines
              + "("
              + data.getCoverage()
              + "%)");
      return data;
    } catch (Exception e) {
      throw new RuntimeException("Failure trying collect coverage data.", e);
    }
  }
 private static void collectFileMeasures(
     SMInputCursor clazz, Map<String, CoverageMeasuresBuilder> builderByFilename)
     throws XMLStreamException {
   while (clazz.getNext() != null) {
     String fileName = clazz.getAttrValue("filename");
     CoverageMeasuresBuilder builder = builderByFilename.get(fileName);
     if (builder == null) {
       builder = CoverageMeasuresBuilder.create();
       builderByFilename.put(fileName, builder);
     }
     collectFileData(clazz, builder);
   }
 }
Example #15
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>");
    }
  }
 /**
  * @param fileName
  * @param violationNodeCursor
  * @return
  * @throws XMLStreamException
  */
 private PhpCodeSnifferViolation getViolation(String fileName, SMInputCursor violationNodeCursor)
     throws XMLStreamException {
   PhpCodeSnifferViolation violation = new PhpCodeSnifferViolation();
   violation.setRuleKey(violationNodeCursor.getAttrValue(RULE_KEY_ATTRIBUTE_NAME));
   violation.setRuleName(violationNodeCursor.getAttrValue(RULE_NAME_ATTRIBUTE_NAME));
   violation.setType(violationNodeCursor.getAttrValue(PRIORITY_ATTRIBUTE_NAME));
   violation.setLongMessage(violationNodeCursor.getAttrValue(MESSAGE_ATTRIBUTE_NAME));
   violation.setLine(
       Integer.parseInt(violationNodeCursor.getAttrValue(LINE_NUMBER_ATTRIBUTE_NAME)));
   violation.setComlumn(
       Integer.parseInt(violationNodeCursor.getAttrValue(COLUMN_NUMBER_ATTRIBUTE_NAME)));
   violation.setFileName(fileName);
   violation.setSourcePath(fileName);
   return violation;
 }
  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);
    }
  }