コード例 #1
0
 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;
 }
コード例 #2
0
  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);
    }
  }
コード例 #3
0
  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());
          }
        }
      }
    }
  }
コード例 #4
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++;
      }
    }
  }
コード例 #5
0
 private void collectModuleMeasures(
     SMInputCursor module, Map<String, CoverageMeasuresBuilder> coverageData)
     throws XMLStreamException {
   while (module.getNext() != null) {
     handleModuleItems(module, coverageData);
   }
 }
コード例 #6
0
  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;
  }
コード例 #7
0
  public List<Rule> parse(Reader reader) {
    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);
    try {
      SMHierarchicCursor rootC = inputFactory.rootElementCursor(reader);
      rootC.advance(); // <rules>
      List<Rule> rules = new ArrayList<>();

      SMInputCursor rulesC = rootC.childElementCursor("rule");
      while (rulesC.getNext() != null) {
        // <rule>
        Rule rule = Rule.create();
        rules.add(rule);

        processRule(rule, rulesC);
      }
      return rules;

    } catch (XMLStreamException e) {
      throw new SonarException("XML is not valid", e);
    }
  }
コード例 #8
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);
  }
コード例 #9
0
  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;
  }
コード例 #10
0
  @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;
  }
コード例 #11
0
 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);
   }
 }
コード例 #12
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);
   }
 }
  @Override
  public void stream(SMHierarchicCursor rootCursor) throws XMLStreamException {
    rootCursor.advance();
    SMInputCursor fileCursor = rootCursor.descendantElementCursor("srcfile");

    while (fileCursor.getNext() != null) {
      CoverageFileData data = collectCoverageData(fileCursor);
      saveCoverageData(data);
    }
  }
コード例 #14
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()]));
  }
コード例 #15
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);
      }
    }
  }
コード例 #16
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
     }
   }
 }
コード例 #17
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);
     }
   }
 }
コード例 #18
0
 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);
   }
 }
コード例 #19
0
    /** {@inheritDoc} */
    public void stream(SMHierarchicCursor rootCursor) throws javax.xml.stream.XMLStreamException {
      try {
        rootCursor.advance();
      } catch (com.ctc.wstx.exc.WstxEOFException eofExc) {
        throw new EmptyReportException();
      }

      SMInputCursor errorCursor = rootCursor.childElementCursor("error");

      while (errorCursor.getNext() != null) {
        valgrindErrors.add(parseErrorTag(errorCursor));
      }
    }
コード例 #20
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;
  }
コード例 #21
0
ファイル: Model3dIndex.java プロジェクト: vitrofp7/vitro
 /**
  * Creates a new instance of Index Of Model Mappings read from the corresponding file (Used for
  * persistence)
  */
 public static void parseIndexFromFile() {
   // Read file and create the Index
   // check if file exists. If it exists open it and parse it.
   // Else return
   //
   File inFile = new File(Model3dIndex.getIndexPath() + "modelIndex.xml");
   // error state check
   if (inFile.exists()) {
     try {
       Model3dIndex.getListofAllMetaEntries().clear();
       FileReader tmpInReader = new FileReader(inFile);
       WstxInputFactory fin = new WstxInputFactory();
       fin.configureForConvenience();
       fin.setProperty(
           XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.FALSE); // <-- NEEDED TO GET ATTRIBUTES!
       // input
       XMLStreamReader2 sr = (XMLStreamReader2) fin.createXMLStreamReader(tmpInReader);
       SMInputCursor inputRootElement = SMInputFactory.rootElementCursor(sr);
       inputRootElement.getNext();
       SMInputCursor childInElement = inputRootElement.childCursor();
       String myText = "";
       while (childInElement.getNext() != null) {
         if (!childInElement.getCurrEvent().hasText()
             && childInElement
                 .getLocalName()
                 .toLowerCase()
                 .equals(Model3dIndex.getMetaEntryTag().toLowerCase())) {
           Model3dIndex.getListofAllMetaEntries().add(new Model3dIndexEntry(childInElement));
         }
       }
       tmpInReader.close();
     } catch (Exception e) {
       return;
     }
   } else return;
 }
コード例 #22
0
 private static void collectPackageMeasures(SMInputCursor pack, SensorContext context)
     throws XMLStreamException {
   while (pack.getNext() != null) {
     Map<String, CoverageMeasuresBuilder> builderByFilename = Maps.newHashMap();
     collectFileMeasures(pack.descendantElementCursor("class"), builderByFilename);
     for (Map.Entry<String, CoverageMeasuresBuilder> entry : builderByFilename.entrySet()) {
       org.sonar.api.resources.File file = new org.sonar.api.resources.File(entry.getKey());
       if (fileExists(context, file)) {
         for (Measure measure : entry.getValue().createMeasures()) {
           context.saveMeasure(file, measure);
         }
       }
     }
   }
 }
コード例 #23
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());
     }
   }
 }
コード例 #24
0
  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]));
      }
    }
  }
コード例 #25
0
  public void load(RulesDefinition.NewExtendedRepository repo, Reader reader) {
    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);
    try {
      SMHierarchicCursor rootC = inputFactory.rootElementCursor(reader);
      rootC.advance(); // <rules>

      SMInputCursor rulesC = rootC.childElementCursor("rule");
      while (rulesC.getNext() != null) {
        // <rule>
        processRule(repo, rulesC);
      }

    } catch (XMLStreamException e) {
      throw new IllegalStateException("XML is not valid", e);
    }
  }
  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);
    }
  }
コード例 #27
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>");
    }
  }
コード例 #28
0
  /**
   * Creates a new instance of Model3dStyleNumericCase
   *
   * @param givenCursor the XML part of the styles file that describes a Style Special Case entry
   */
  public Model3dStyleNumericCase(SMInputCursor givenCursor) {
    this.fromValue = Model3dStyleNumericCase.defaultFromValue;
    this.toValue = Model3dStyleNumericCase.defaultToValue;
    this.iconFilename = Model3dStyleNumericCase.undefinedIconFilename;
    this.color1 = Model3dStyleNumericCase.UNDEFINEDCOLOR1;
    this.smallPrefabFilename = Model3dStyleNumericCase.undefinedPrefabFilename;

    try {
      SMInputCursor childInElement = givenCursor.childCursor();
      while (childInElement.getNext() != null) {
        if (!childInElement.getCurrEvent().hasText()
            && childInElement
                .getLocalName()
                .toLowerCase()
                .equals(this.getValueFromTag().toLowerCase())) {
          SMInputCursor childInElement2 = childInElement.childMixedCursor();
          while (childInElement2.getNext() != null) {
            if (childInElement2.getCurrEvent().hasText()) {
              this.fromValue = childInElement2.getText();
              break;
            }
          }
        } else if (!childInElement.getCurrEvent().hasText()
            && childInElement
                .getLocalName()
                .toLowerCase()
                .equals(this.getValueToTag().toLowerCase())) {
          SMInputCursor childInElement2 = childInElement.childMixedCursor();
          while (childInElement2.getNext() != null) {
            if (childInElement2.getCurrEvent().hasText()) {
              this.toValue = childInElement2.getText();
              break;
            }
          }
        } else if (!childInElement.getCurrEvent().hasText()
            && childInElement
                .getLocalName()
                .toLowerCase()
                .equals(this.getIconTag().toLowerCase())) {
          SMInputCursor childInElement2 = childInElement.childMixedCursor();
          while (childInElement2.getNext() != null) {
            if (childInElement2.getCurrEvent().hasText()) {
              this.iconFilename = childInElement2.getText();
              break;
            }
          }
        } else if (!childInElement.getCurrEvent().hasText()
            && childInElement
                .getLocalName()
                .toLowerCase()
                .equals(this.getColor1Tag().toLowerCase())) {
          SMInputCursor childInElement2 = childInElement.childMixedCursor();
          while (childInElement2.getNext() != null) {
            if (childInElement2.getCurrEvent().hasText()) {
              this.color1 = childInElement2.getText();
              break;
            }
          }
        } else if (!childInElement.getCurrEvent().hasText()
            && childInElement
                .getLocalName()
                .toLowerCase()
                .equals(this.getPrefabTag().toLowerCase())) {
          SMInputCursor childInElement2 = childInElement.childMixedCursor();
          while (childInElement2.getNext() != null) {
            if (childInElement2.getCurrEvent().hasText()) {
              this.smallPrefabFilename = childInElement2.getText();
              break;
            }
          }
        }
      }
    } catch (Exception e) {
      return; // the default (though invalid) values are already set.
    }
  }
コード例 #29
0
  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);
    }
  }