Search in sources :

Example 6 with StaxParser

use of org.sonar.cxx.sensors.utils.StaxParser in project sonar-cxx by SonarOpenCommunity.

the class XunitReportParserTest method testFilePaths.

@Test
public void testFilePaths() throws javax.xml.stream.XMLStreamException {
    parserHandler = new XunitReportParser("");
    parser = new StaxParser(parserHandler, false);
    File report = TestUtils.loadResource(pathPrefix + "xunit-result-SAMPLE-inconsistent-case.xml");
    parser.parse(report);
    var actualPaths = parserHandler.getTestFiles().stream().map(TestFile::getFilename).filter(p -> !Strings.isNullOrEmpty(p)).map(s -> Paths.get(s)).collect(Collectors.toList());
    var expectPaths = Stream.of(Paths.get("/test/file.cpp"), Paths.get("/test/File.cpp"), Paths.get("/TEST/file.cpp")).distinct().toArray(n -> new Path[n]);
    assertThat(actualPaths).containsExactlyInAnyOrder(expectPaths);
}
Also used : Stream(java.util.stream.Stream) TreeMap(java.util.TreeMap) Paths(java.nio.file.Paths) TestUtils(org.sonar.cxx.sensors.utils.TestUtils) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Test(org.junit.Test) Strings(org.assertj.core.util.Strings) Path(java.nio.file.Path) Collectors(java.util.stream.Collectors) Assert.assertEquals(org.junit.Assert.assertEquals) File(java.io.File) StaxParser(org.sonar.cxx.sensors.utils.StaxParser) StaxParser(org.sonar.cxx.sensors.utils.StaxParser) File(java.io.File) Test(org.junit.Test)

Example 7 with StaxParser

use of org.sonar.cxx.sensors.utils.StaxParser in project sonar-cxx by SonarOpenCommunity.

the class CxxVeraxxSensor method processReport.

@Override
protected void processReport(File report) {
    try {
        var parser = new StaxParser((SMHierarchicCursor rootCursor) -> {
            try {
                rootCursor.advance();
            } catch (com.ctc.wstx.exc.WstxEOFException e) {
                throw new EmptyReportException("The 'Vera++' report is empty", e);
            }
            SMInputCursor fileCursor = rootCursor.childElementCursor("file");
            while (fileCursor.getNext() != null) {
                String name = fileCursor.getAttrValue("name");
                SMInputCursor errorCursor = fileCursor.childElementCursor("error");
                while (errorCursor.getNext() != null) {
                    if (!"error".equals(name)) {
                        String line = errorCursor.getAttrValue("line");
                        String message = errorCursor.getAttrValue("message");
                        String source = errorCursor.getAttrValue("source");
                        var issue = new CxxReportIssue(source, name, line, null, message);
                        saveUniqueViolation(issue);
                    } else {
                        LOG.debug("Error in file '{}', with message '{}'", name + "(" + errorCursor.getAttrValue("line") + ")", errorCursor.getAttrValue("message"));
                    }
                }
            }
        });
        parser.parse(report);
    } catch (XMLStreamException e) {
        throw new InvalidReportException("The 'Vera++' report is invalid", e);
    }
}
Also used : SMInputCursor(org.codehaus.staxmate.in.SMInputCursor) SMHierarchicCursor(org.codehaus.staxmate.in.SMHierarchicCursor) EmptyReportException(org.sonar.cxx.sensors.utils.EmptyReportException) XMLStreamException(javax.xml.stream.XMLStreamException) StaxParser(org.sonar.cxx.sensors.utils.StaxParser) InvalidReportException(org.sonar.cxx.sensors.utils.InvalidReportException) CxxReportIssue(org.sonar.cxx.utils.CxxReportIssue)

Example 8 with StaxParser

use of org.sonar.cxx.sensors.utils.StaxParser in project sonar-cxx by SonarOpenCommunity.

the class XunitReportParserTest method testParse.

@Test
public void testParse() throws javax.xml.stream.XMLStreamException {
    var ioMap = new TreeMap<String, Integer>();
    // report: number of tests
    ioMap.put("xunit-result-2.xml", 5);
    ioMap.put("xunit-result-SAMPLE_with_fileName.xml", 3);
    ioMap.put("xunit-result-SAMPLE.xml", 3);
    ioMap.put("xunit-result-skippedonly.xml", 1);
    ioMap.put("xunit-result_with_emptyFileName.xml", 3);
    ioMap.put("nested_testsuites.xml", 2);
    ioMap.put("xunit-result-no-testsuite.xml", 0);
    for (var entry : ioMap.entrySet()) {
        parserHandler = new XunitReportParser("");
        parser = new StaxParser(parserHandler, false);
        File report = TestUtils.loadResource(pathPrefix + entry.getKey());
        parser.parse(report);
        long tests = 0;
        for (var testFile : parserHandler.getTestFiles()) {
            tests += testFile.getTests();
        }
        assertEquals((long) entry.getValue(), tests);
    }
}
Also used : StaxParser(org.sonar.cxx.sensors.utils.StaxParser) TreeMap(java.util.TreeMap) File(java.io.File) Test(org.junit.Test)

Example 9 with StaxParser

use of org.sonar.cxx.sensors.utils.StaxParser in project sonar-cxx by SonarOpenCommunity.

the class ValgrindReportParser method parse.

/**
 * Parses given valgrind report
 *
 * @param report full path of XML report
 * @return Set<ValgrindError>
 * @exception XMLStreamException javax.xml.stream.XMLStreamException
 */
public Set<ValgrindError> parse(File report) throws XMLStreamException {
    var streamHandler = new ValgrindReportStreamHandler();
    new StaxParser(streamHandler).parse(report);
    return streamHandler.valgrindErrors;
}
Also used : StaxParser(org.sonar.cxx.sensors.utils.StaxParser)

Example 10 with StaxParser

use of org.sonar.cxx.sensors.utils.StaxParser in project sonar-cxx by SonarOpenCommunity.

the class CppcheckParser method parse.

public void parse(File report) throws javax.xml.stream.XMLStreamException {
    var parser = new StaxParser(new StaxParser.XmlStreamHandler() {

        /**
         * {@inheritDoc}
         */
        @Override
        public void stream(SMHierarchicCursor rootCursor) throws XMLStreamException {
            var parsed = false;
            try {
                rootCursor.advance();
            } catch (com.ctc.wstx.exc.WstxEOFException e) {
                throw new EmptyReportException("The 'Cppcheck V2' report is empty", e);
            }
            try {
                String version = rootCursor.getAttrValue("version");
                if ("2".equals(version)) {
                    SMInputCursor errorsCursor = rootCursor.childElementCursor("errors");
                    if (errorsCursor.getNext() != null) {
                        parsed = true;
                        SMInputCursor errorCursor = errorsCursor.childElementCursor("error");
                        while (errorCursor.getNext() != null) {
                            processErrorTag(errorCursor);
                        }
                    }
                }
            } catch (RuntimeException e) {
                throw new XMLStreamException("parsing failed", e);
            }
            if (!parsed) {
                throw new XMLStreamException();
            }
        }

        private void processErrorTag(SMInputCursor errorCursor) throws XMLStreamException {
            String id = requireAttributeSet(errorCursor.getAttrValue("id"), "Missing mandatory attribute /results/errors/error[@id]");
            String msg = requireAttributeSet(errorCursor.getAttrValue("msg"), "Missing mandatory attribute /results/errors/error[@msg]");
            boolean isInconclusive = "true".equals(errorCursor.getAttrValue("inconclusive"));
            String issueText = createIssueText(msg, isInconclusive);
            CxxReportIssue issue = null;
            SMInputCursor locationCursor = errorCursor.childElementCursor("location");
            while (locationCursor.getNext() != null) {
                String file = locationCursor.getAttrValue("file");
                String line = locationCursor.getAttrValue("line");
                String info = locationCursor.getAttrValue("info");
                if (file != null) {
                    file = file.replace('\\', '/');
                }
                if ("*".equals(file)) {
                    // findings on project level
                    file = null;
                    line = null;
                    info = null;
                }
                final boolean isLocationInProject = isLocationInProject(file);
                if (issue == null) {
                    // the current module) we are not interested in this <error>
                    if (!isLocationInProject) {
                        LOG.debug("Cppcheck issue outside of project, skipping issue: {}:{} {}:{}", file, line, id, msg);
                        return;
                    }
                    issue = new CxxReportIssue(id, file, line, null, issueText);
                    // information about the flow/analysis
                    if (info != null && !msg.equals(info)) {
                        issue.addLocation(file, line, null, info);
                    }
                } else if (info != null) {
                    // info
                    if (isLocationInProject) {
                        issue.addLocation(file, line, null, info);
                    } else {
                        var primaryLocation = issue.getLocations().get(0);
                        String primaryFile = primaryLocation.getFile();
                        String primaryLine = primaryLocation.getLine();
                        var extendedInfo = new StringBuilder(512);
                        extendedInfo.append(makeRelativePath(file, primaryFile)).append(":").append(line).append(" ").append(info);
                        issue.addLocation(primaryFile, primaryLine, null, extendedInfo.toString());
                    }
                }
            }
            // no <location> tags: issue raised on the whole module/project
            if (issue == null) {
                issue = new CxxReportIssue(id, null, null, null, issueText);
            }
            sensor.saveUniqueViolation(issue);
        }

        private String makeRelativePath(String path, String basePath) {
            try {
                return Paths.get(basePath).relativize(Paths.get(path)).toString();
            } catch (IllegalArgumentException e) {
                LOG.warn("Can't create relative path: basePath='{}', path='{}'", basePath, path);
                return path;
            }
        }

        private boolean isLocationInProject(@Nullable String file) {
            // project/module
            return (file == null) || (sensor.getInputFileIfInProject(file) != null);
        }
    });
    parser.parse(report);
}
Also used : EmptyReportException(org.sonar.cxx.sensors.utils.EmptyReportException) StaxParser(org.sonar.cxx.sensors.utils.StaxParser) SMInputCursor(org.codehaus.staxmate.in.SMInputCursor) SMHierarchicCursor(org.codehaus.staxmate.in.SMHierarchicCursor) XMLStreamException(javax.xml.stream.XMLStreamException) CxxReportIssue(org.sonar.cxx.utils.CxxReportIssue)

Aggregations

StaxParser (org.sonar.cxx.sensors.utils.StaxParser)10 XMLStreamException (javax.xml.stream.XMLStreamException)6 SMHierarchicCursor (org.codehaus.staxmate.in.SMHierarchicCursor)6 EmptyReportException (org.sonar.cxx.sensors.utils.EmptyReportException)5 InvalidReportException (org.sonar.cxx.sensors.utils.InvalidReportException)5 File (java.io.File)3 HashMap (java.util.HashMap)3 SMInputCursor (org.codehaus.staxmate.in.SMInputCursor)3 Test (org.junit.Test)3 CxxReportIssue (org.sonar.cxx.utils.CxxReportIssue)3 TreeMap (java.util.TreeMap)2 Path (java.nio.file.Path)1 Paths (java.nio.file.Paths)1 Collectors (java.util.stream.Collectors)1 Stream (java.util.stream.Stream)1 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)1 Strings (org.assertj.core.util.Strings)1 Assert.assertEquals (org.junit.Assert.assertEquals)1 TestUtils (org.sonar.cxx.sensors.utils.TestUtils)1