3 * Copyright (C) 2009-2024 SonarSource SA
4 * mailto:info AT sonarsource DOT com
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 3 of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 package org.sonar.scanner.externalissue.sarif;
22 import java.util.List;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26 import org.sonar.api.batch.sensor.issue.NewExternalIssue;
27 import org.sonar.api.batch.sensor.rule.NewAdHocRule;
28 import org.sonar.api.scanner.ScannerSide;
29 import org.sonar.sarif.pojo.Run;
30 import org.sonar.sarif.pojo.SarifSchema210;
31 import org.sonar.scanner.externalissue.sarif.RunMapper.RunMapperResult;
33 import static java.util.Objects.requireNonNull;
36 public class DefaultSarif210Importer implements Sarif210Importer {
37 private static final Logger LOG = LoggerFactory.getLogger(DefaultSarif210Importer.class);
39 private final RunMapper runMapper;
41 DefaultSarif210Importer(RunMapper runMapper) {
42 this.runMapper = runMapper;
46 public SarifImportResults importSarif(SarifSchema210 sarif210) {
47 int successFullyImportedIssues = 0;
48 int successFullyImportedRuns = 0;
51 List<Run> runs = requireNonNull(sarif210.getRuns(), "The runs section of the Sarif report is null");
52 for (Run run : runs) {
53 RunMapperResult runMapperResult = tryMapRun(run);
54 if (runMapperResult.isSuccess()) {
55 List<NewAdHocRule> newAdHocRules = runMapperResult.getNewAdHocRules();
56 newAdHocRules.forEach(NewAdHocRule::save);
58 List<NewExternalIssue> newExternalIssues = runMapperResult.getNewExternalIssues();
59 successFullyImportedRuns += 1;
60 successFullyImportedIssues += newExternalIssues.size();
61 newExternalIssues.forEach(NewExternalIssue::save);
66 return SarifImportResults.builder()
67 .successFullyImportedIssues(successFullyImportedIssues)
68 .successFullyImportedRuns(successFullyImportedRuns)
69 .failedRuns(failedRuns)
73 private RunMapperResult tryMapRun(Run run) {
75 return runMapper.mapRun(run);
76 } catch (Exception exception) {
77 LOG.warn("Failed to import a sarif run, error: {}", exception.getMessage());
78 return new RunMapperResult().success(false);