Java Code Examples for org.sonar.api.batch.sensor.SensorContext

The following examples show how to use org.sonar.api.batch.sensor.SensorContext. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Override
public void execute(SensorContext sensorContext) {
    if (Boolean.parseBoolean(system2.envVariable("GITLAB_CI"))) {
        Optional.ofNullable(system2.envVariable("CI_API_V4_URL")).ifPresent(v -> sensorContext
                .addContextProperty(GitlabServerPullRequestDecorator.PULLREQUEST_GITLAB_INSTANCE_URL, v));
        Optional.ofNullable(system2.envVariable("CI_PROJECT_PATH")).ifPresent(v -> sensorContext
                .addContextProperty(GitlabServerPullRequestDecorator.PULLREQUEST_GITLAB_PROJECT_ID, v));
        Optional.ofNullable(system2.envVariable("CI_MERGE_REQUEST_PROJECT_URL")).ifPresent(v -> sensorContext
                .addContextProperty(GitlabServerPullRequestDecorator.PULLREQUEST_GITLAB_PROJECT_URL, v));
        Optional.ofNullable(system2.envVariable("CI_PIPELINE_ID")).ifPresent(v -> sensorContext
                .addContextProperty(GitlabServerPullRequestDecorator.PULLREQUEST_GITLAB_PIPELINE_ID, v));
    }

    Optional.ofNullable(system2.property(GitlabServerPullRequestDecorator.PULLREQUEST_GITLAB_INSTANCE_URL)).ifPresent(
            v -> sensorContext.addContextProperty(GitlabServerPullRequestDecorator.PULLREQUEST_GITLAB_INSTANCE_URL, v));
    Optional.ofNullable(system2.property(GitlabServerPullRequestDecorator.PULLREQUEST_GITLAB_PROJECT_ID)).ifPresent(
            v -> sensorContext.addContextProperty(GitlabServerPullRequestDecorator.PULLREQUEST_GITLAB_PROJECT_ID, v));
    Optional.ofNullable(system2.property(GitlabServerPullRequestDecorator.PULLREQUEST_GITLAB_PROJECT_URL)).ifPresent(
            v -> sensorContext.addContextProperty(GitlabServerPullRequestDecorator.PULLREQUEST_GITLAB_PROJECT_URL, v));
    Optional.ofNullable(system2.property(GitlabServerPullRequestDecorator.PULLREQUEST_GITLAB_PIPELINE_ID)).ifPresent(
            v -> sensorContext.addContextProperty(GitlabServerPullRequestDecorator.PULLREQUEST_GITLAB_PIPELINE_ID, v));
}
 
Example 2
Source Project: sonar-clojure   Source File: LeinNvdSensor.java    License: MIT License 6 votes vote down vote up
@Override
public void execute(SensorContext context) {

    if (!isPluginDisabled(context, PLUGIN_NAME, DISABLED_PROPERTY, DISABLED_PROPERTY_DEFAULT)) {
        LOG.info("Running Lein NVD");
        String reportPath = context.config().get(NvdProperties.REPORT_LOCATION_PROPERTY).orElse(REPORT_LOCATION_DEFAULT);

        long timeOut = context.config().getLong(SENSORS_TIMEOUT_PROPERTY)
                .orElse(Long.valueOf(SENSORS_TIMEOUT_PROPERTY_DEFAULT));
        this.commandRunner.run(timeOut, LEIN_COMMAND, LEIN_ARGUMENTS);

        Optional<String> vulnerabilityContext = readFromFileSystem(reportPath);
        if (vulnerabilityContext.isPresent()) {
            List<Vulnerability> vulnerabilities = LeinNvdParser.parseJson(vulnerabilityContext.get());
            saveVulnerabilities(vulnerabilities, context);
        } else {
            LOG.warn("Lein NVD dependency report does not exists. Is Lein NVD installed as a plugin?");
        }
    }
}
 
Example 3
Source Project: sonar-clojure   Source File: LeinNvdSensor.java    License: MIT License 6 votes vote down vote up
private void saveVulnerabilities(List<Vulnerability> vulnerabilities, SensorContext context) {
    Optional<InputFile> fileOptional = getFile("project.clj", context.fileSystem());

    fileOptional.ifPresent(projectFile -> {
        for (Vulnerability v : vulnerabilities) {
            LOG.debug("Processing vulnerability: " +v.toString());
            RuleKey ruleKey = RuleKey.of(ClojureLintRulesDefinition.REPOSITORY_KEY, "nvd-" + v.getSeverity().toLowerCase());
            NewIssue newIssue = context.newIssue().forRule(ruleKey);
            NewIssueLocation primaryLocation = newIssue
                    .newLocation()
                    .on(projectFile)
                    .message(v.getName()
                            + ";" + v.getCwes()
                            + ";" + v.getFileName())
                    .at(projectFile.selectLine(1));
            newIssue.at(primaryLocation);
            newIssue.save();
        }
    });
}
 
Example 4
Source Project: sonar-clojure   Source File: KibitSensor.java    License: MIT License 6 votes vote down vote up
@Override
public void execute(SensorContext context) {
    if (!isPluginDisabled(context, PLUGIN_NAME, KibitProperties.DISABLED_PROPERTY, KibitProperties.DISABLED_PROPERTY_DEFAULT)) {
        LOG.info("Running Kibit");
        long timeOut = context.config().getLong(SENSORS_TIMEOUT_PROPERTY)
                .orElse(Long.valueOf(SENSORS_TIMEOUT_PROPERTY_DEFAULT));

        CommandStreamConsumer stdOut = this.commandRunner.run(timeOut, LEIN_COMMAND, KIBIT_COMMAND);

        List<Issue> issues = KibitIssueParser.parse(stdOut);
        LOG.info("Saving issues");
        for (Issue issue : issues) {
            saveIssue(issue, context);
        }

    }
}
 
Example 5
Source Project: sonar-clojure   Source File: ClojureSensor.java    License: MIT License 6 votes vote down vote up
@Override
public void execute(SensorContext context) {
    LOG.info("Running ClojureSensor");
    FilePredicates predicates = context.fileSystem().predicates();
    FilePredicate clojure = predicates.hasLanguage(Clojure.KEY);
    FilePredicate main = predicates.hasType(InputFile.Type.MAIN);

    //TODO This is inaccurate. We need to properly count the lines of code, excluding spaces, comments, etc.
    //TODO This is here to make sure analysis data will show up in the Sonar UI.
    Iterable<InputFile> sources = context.fileSystem().inputFiles(predicates.and(clojure, main));

    for (InputFile source : sources) {
        LOG.info(source.toString());
        context.<Integer>newMeasure().withValue(source.lines()).forMetric(NCLOC).on(source).save();
    }
}
 
Example 6
Source Project: sonar-esql-plugin   Source File: EsqlSensor.java    License: Apache License 2.0 6 votes vote down vote up
private void scanFile(SensorContext sensorContext, InputFile inputFile, List<TreeVisitor> visitors, ProgramTree programTree) {
    LOG.debug("scanning file " + inputFile.filename());
    EsqlVisitorContext context = new EsqlVisitorContext(programTree, inputFile, sensorContext.config());

    List<Issue> fileIssues = new ArrayList<>();

    for (TreeVisitor visitor : visitors) {
        if (visitor instanceof EsqlCheck) {
            fileIssues.addAll(((EsqlCheck) visitor).scanFile(context));
        } else {
            visitor.scanTree(context);
        }
    }

    saveFileIssues(sensorContext, fileIssues, inputFile);
    highlightSymbols(inputFile, context, sensorContext);
}
 
Example 7
Source Project: sonar-esql-plugin   Source File: EsqlSensor.java    License: Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
protected void analyseFiles(
        SensorContext context, List<TreeVisitor> treeVisitors, Iterable<InputFile> inputFiles,
        ProgressReport progressReport
) {
    boolean success = false;
    try {
        for (InputFile inputFile : inputFiles) {
            // check for cancellation of the analysis (by SonarQube or SonarLint). See SONARJS-761.
            if (context.isCancelled()) {
                throw new CancellationException("Analysis interrupted because the SensorContext is in cancelled state");
            }
            analyse(context, inputFile, treeVisitors);
            progressReport.nextFile();
        }
        success = true;
    } catch (CancellationException e) {
        // do not propagate the exception
        LOG.debug("Error while file analysis in code coverage" + e.toString(), e);
    } finally {
        stopProgressReport(progressReport, success);
    }
}
 
Example 8
@Override
public void execute(SensorContext context) {
  String reportPath = context.settings().getString(LuaPlugin.COBERTURA_REPORT_PATH);

  if (reportPath != null) {
    File xmlFile = getIOFile(context.fileSystem(), reportPath);

    if (xmlFile.exists()) {
      LOGGER.info("Analyzing Cobertura report: " + reportPath);
      CoberturaReportParser.parseReport(xmlFile, context);
    } else {
      LOGGER.info("Cobertura xml report not found: " + reportPath);
    }
  } else {
    LOGGER.info("No Cobertura report provided (see '" + LuaPlugin.COBERTURA_REPORT_PATH + "' property)");
  }
}
 
Example 9
Source Project: AEM-Rules-for-SonarQube   Source File: MetricsSaver.java    License: Apache License 2.0 6 votes vote down vote up
public static void saveIssues(SensorContext context, HtmlSourceCode sourceCode) {
    InputFile inputFile = sourceCode.inputFile();

    for (HtmlIssue issue : sourceCode.getIssues()) {
        NewIssue newIssue = context.newIssue()
            .forRule(issue.ruleKey())
            .gap(issue.cost());
        Integer line = issue.line();
        NewIssueLocation location = newIssue.newLocation()
            .on(inputFile)
            .message(issue.message());
        if (line != null && line > 0) {
            location.at(inputFile.selectLine(line));
        }
        newIssue.at(location);
        newIssue.save();
    }
}
 
Example 10
Source Project: sonar-ruby-plugin   Source File: PathResolver.java    License: MIT License 6 votes vote down vote up
private String getAbsolutePath(SensorContext context, String toReturn) {
    if (toReturn != null) {
        File candidateFile = new java.io.File(toReturn);
        if (!candidateFile.isAbsolute()) {
            candidateFile = new java.io.File(context.fileSystem().baseDir().getAbsolutePath(), toReturn);
        }

        if (!doesFileExist(candidateFile)) {
            return null;
        }

        return candidateFile.getAbsolutePath();
    }

    return null;
}
 
Example 11
Source Project: sonar-ruby-plugin   Source File: SimpleCovSensor.java    License: MIT License 6 votes vote down vote up
public void execute(SensorContext context) {
    String reportPath = context.settings().getString(RubyPlugin.SIMPLECOV_REPORT_PATH);

    if (isNull(reportPath)) {
        LOG.warn("Report path is not set, unable to generate coverage metrics");
        return;
    }

    SimpleCovParser parser = new SimpleCovParser();

    try {
        Map<String, NewCoverage> fileCoverages = parser.parse(context, new File(reportPath));
        fileCoverages.values().forEach(NewCoverage::save);
    } catch (IOException e) {
        LOG.warn("Unable to generate coverage metrics", e);
    }
}
 
Example 12
Source Project: sonar-ruby-plugin   Source File: RubocopSensor.java    License: MIT License 6 votes vote down vote up
@Override
public void execute(SensorContext sensorContext) {
    RubocopExecutorConfig config = RubocopExecutorConfig.fromSettings(sensorContext, resolver);

    if (!config.useExistingRubocopOutput() && config.getPathToRubocop() == null) {
        LOG.warn("Path to rubocop not defined or not found. Skipping rubocop analysis.");
        return;
    }

    String jsonResults = this.executor.execute(config, findFilesToLint(sensorContext, config));

    Map<String, List<RubocopIssue>> issues = parser.parse(jsonResults);

    if (issues.isEmpty()) {
        LOG.warn("Rubocop returned no result at all");
        return;
    }

    Collection<ActiveRule> allRules = sensorContext.activeRules().findByRepository("rubocop");
    Set<String> ruleNames = allRules.stream().map(rule -> rule.ruleKey().rule()).collect(Collectors.toSet());

    issues.entrySet().forEach(rubyFilesIssues -> generateSonarIssuesFromResults(rubyFilesIssues, sensorContext, ruleNames));
}
 
Example 13
Source Project: sonar-ruby-plugin   Source File: RubocopSensor.java    License: MIT License 6 votes vote down vote up
private void saveNewIssue(RubocopIssue issue, InputFile inputFile, Set<String> ruleNames, SensorContext sensorContext) {
    // Make sure the rule we're violating is one we recognise - if not, we'll
    // fall back to the generic 'rubocop-issue' rule
    String ruleName = issue.getRuleName();
    if (!ruleNames.contains(ruleName)) {
        ruleName = RubyRulesDefinition.RUBY_LINT_UNKNOWN_RULE.key;
    }

    NewIssue newIssue =
        sensorContext
            .newIssue()
            .forRule(RuleKey.of("rubocop", ruleName));

    NewIssueLocation newIssueLocation =
        newIssue
            .newLocation()
            .on(inputFile)
            .message(issue.getFailure())
            .at(inputFile.selectLine(issue.getPosition().getLine()));

    newIssue.at(newIssueLocation);
    newIssue.save();
}
 
Example 14
/**
 * Execute Checkstyle and return the generated XML report.
 * @noinspection TooBroadScope
 */
public void execute(SensorContext context) {
    if (Objects.nonNull(listener)) {
        listener.setContext(context);
    }

    final Locale initialLocale = Locale.getDefault();
    Locale.setDefault(Locale.ENGLISH);
    final ClassLoader initialClassLoader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(PackageNamesLoader.class.getClassLoader());
    try {
        executeWithClassLoader();
    }
    finally {
        Thread.currentThread().setContextClassLoader(initialClassLoader);
        Locale.setDefault(initialLocale);
    }
}
 
Example 15
Source Project: SonarTsPlugin   Source File: LOCSensorImpl.java    License: MIT License 6 votes vote down vote up
@Override
public Map<InputFile, Set<Integer>> execute(SensorContext ctx) {
    HashMap<InputFile, Set<Integer>> toReturn = new HashMap<>();
    
    Iterable<InputFile> affectedFiles = 
            ctx
                .fileSystem()
                .inputFiles(ctx.fileSystem().predicates().hasLanguage(TypeScriptLanguage.LANGUAGE_KEY));
    
    for (InputFile inputFile : affectedFiles) {
        Set<Integer> nonCommentLineNumbers = this.getNonCommentLineNumbers(inputFile);
        toReturn.put(inputFile, nonCommentLineNumbers);
        
        ctx.<Integer>newMeasure().forMetric(CoreMetrics.NCLOC).on(inputFile).withValue(nonCommentLineNumbers.size()).save();
    }
    
    return toReturn;
}
 
Example 16
Source Project: sonar-esql-plugin   Source File: EsqlSensor.java    License: Apache License 2.0 6 votes vote down vote up
private void processRecognitionException(RecognitionException e, SensorContext sensorContext, InputFile inputFile) {
    if (parsingErrorRuleKey != null) {
        NewIssue newIssue = sensorContext.newIssue();

        NewIssueLocation primaryLocation = newIssue.newLocation()
                .message(ParsingErrorCheck.MESSAGE)
                .on(inputFile)
                .at(inputFile.selectLine(e.getLine()));

        newIssue
                .forRule(parsingErrorRuleKey)
                .at(primaryLocation)
                .save();
    }

    sensorContext.newAnalysisError()
            .onFile(inputFile)
            .at(inputFile.newPointer(e.getLine(), 0))
            .message(e.getMessage())
            .save();
}
 
Example 17
Source Project: sonar-esql-plugin   Source File: EsqlSensor.java    License: Apache License 2.0 6 votes vote down vote up
public void execute(SensorContext context) {
    LOG.warn("ESQL sensor execute");
    List<TreeVisitor> treeVisitors = Lists.newArrayList();
    treeVisitors.addAll(getTreeVisitors(context));
    treeVisitors.addAll(checks.visitorChecks());

    for (TreeVisitor check : treeVisitors) {
        if (check instanceof ParsingErrorCheck) {
            parsingErrorRuleKey = checks.ruleKeyFor((EsqlCheck) check);
            break;
        }
    }

    Iterable<InputFile> inputFiles = fileSystem.inputFiles(mainFilePredicate);
    Collection<String> files = StreamSupport.stream(inputFiles.spliterator(), false)
            .map(InputFile::toString)
            .collect(Collectors.toList());

    ProgressReport progressReport = new ProgressReport("Report about progress of ESQL analyzer", TimeUnit.SECONDS.toMillis(10));
    progressReport.start(files);

    analyseFiles(context, treeVisitors, inputFiles, progressReport);

    executeCoverageSensors(context);
}
 
Example 18
Source Project: SonarTsPlugin   Source File: TsCoverageSensorImpl.java    License: MIT License 6 votes vote down vote up
private void saveZeroValue(InputFile inputFile, SensorContext context, Set<Integer> nonCommentLineNumbers) {
      NewCoverage newCoverage = 
              context
              .newCoverage()
              .ofType(CoverageType.UNIT)
              .onFile(inputFile);

      if (nonCommentLineNumbers != null) {
          for (Integer nonCommentLineNumber : nonCommentLineNumbers) {
              newCoverage.lineHits(nonCommentLineNumber, 0);
          }
      }
      else {
          for (int i = 1; i <= inputFile.lines(); i++) {
              newCoverage.lineHits(i, 0);
          }
      }

      newCoverage.save();
}
 
Example 19
@Override
public void execute(SensorContext sensorContext) {
  List<TreeVisitor> treeVisitors = Lists.newArrayList();
  treeVisitors.addAll(checks.visitorChecks());
  treeVisitors.add(new SyntaxHighlighterVisitor(sensorContext));
  treeVisitors.add(new MetricsVisitor(sensorContext));

  setParsingErrorCheckIfActivated(treeVisitors);

  ProgressReport progressReport = new ProgressReport("Report about progress of Cucumber Gherkin analyzer", TimeUnit.SECONDS.toMillis(10));
  progressReport.start(Lists.newArrayList(fileSystem.files(mainFilePredicate)));

  issueSaver = new IssueSaver(sensorContext, checks);
  List<Issue> issues = new ArrayList<>();

  boolean success = false;
  try {
    for (InputFile inputFile : fileSystem.inputFiles(mainFilePredicate)) {
      issues.addAll(analyzeFile(sensorContext, inputFile, treeVisitors));
      progressReport.nextFile();
    }
    saveSingleFileIssues(issues);
    saveCrossFileIssues();
    success = true;
  } finally {
    stopProgressReport(progressReport, success);
  }
}
 
Example 20
Source Project: sonar-clojure   Source File: CloverageSensor.java    License: MIT License 5 votes vote down vote up
private void saveCoverageForFile(CoverageReport report, SensorContext context) {
    report.getFileEntries().forEach(fileAnalysis -> {
        NewCoverage coverage = context.newCoverage().onFile(fileAnalysis.getFile());
        fileAnalysis.getEntries().forEach(lineAnalysis ->
                coverage.lineHits(lineAnalysis.getLineNumber(), lineAnalysis.getHits()));
        coverage.save();
    });
}
 
Example 21
Source Project: sonar-clojure   Source File: AncientSensor.java    License: MIT License 5 votes vote down vote up
@Override
public void execute(SensorContext context) {
    if (!isPluginDisabled(context, PLUGIN_NAME, DISABLED_PROPERTY, DISABLED_PROPERTY_DEFAULT)) {
        LOG.info("Running Lein Ancient");

        long timeOut = context.config().getLong(SENSORS_TIMEOUT_PROPERTY)
                .orElse(Long.valueOf(SENSORS_TIMEOUT_PROPERTY_DEFAULT));

        CommandStreamConsumer stdOut = this.commandRunner.run(timeOut, LEIN_COMMAND, LEIN_ARGUMENTS);

        List<OutdatedDependency> outdatedDependencies = parse(stdOut.getData());
        LOG.debug("Parsed " + outdatedDependencies.size() + " dependencies");
        saveOutdated(outdatedDependencies, context);
    }
}
 
Example 22
Source Project: sonar-clojure   Source File: AbstractSensor.java    License: MIT License 5 votes vote down vote up
protected boolean isPluginDisabled(SensorContext context, String pluginName, String propertyName, boolean defaultValue) {
    Boolean pluginDisabled = context.config().getBoolean(propertyName).orElse(defaultValue);
    LOG.debug(String.format("Property: %s Value: %s", propertyName, pluginDisabled));
    if (pluginDisabled) {
        LOG.info(pluginName + " disabled");
    }
    return pluginDisabled;
}
 
Example 23
@Override
public void fillContext(SensorContext sensorContext, AntlrContext fillerRequest) {
	final InputFile file = fillerRequest.getFile();
	TsqlIssue[] foundIssues = issuesProvider.getIssues(fillerRequest, this.getNodes());
	filler.fill(sensorContext, file, foundIssues);

}
 
Example 24
private void save(SensorContext context, Collection<SourceCode> squidSourceFiles) {
  FileSystem fileSystem = context.fileSystem();
  for (SourceCode squidSourceFile : squidSourceFiles) {
    SourceFile squidFile = (SourceFile) squidSourceFile;

    InputFile inputFile = fileSystem.inputFile(fileSystem.predicates().hasPath(squidFile.getKey()));

    saveClassComplexity(context, inputFile, squidFile);
    saveMeasures(context, inputFile, squidFile);
    saveFunctionsComplexityDistribution(context, inputFile, squidFile);
    saveFilesComplexityDistribution(context, inputFile, squidFile);
    visitors.add(new LuaTokensVisitor(context, LuaLexer.create(configuration)));
    saveViolations(context, inputFile, squidFile);
  }
}
 
Example 25
@SuppressWarnings("deprecation")
private void getInterfaceFiles(Collection<SourceCode> squidSourceFiles, SensorContext context) {
  // Scan node.ndf files
  AstScanner<Grammar> scanner = NodeAstScanner.create(createConfiguration(), nodeChecks.all(),
      null);
  logger.debug("Scanning Interface Files with " + nodeChecks.all().size() + " checks active");
  FileSystem fs = context.fileSystem();
  Iterable<InputFile> nodeFiles = fs
      .inputFiles(fs.predicates().matchesPathPatterns(FlowLanguage.getNodeFilePatterns()));
  try {
    ArrayList<File> files = new ArrayList<File>();
    nodeFiles.forEach(file -> files.add(file.file()));
    scanner.scanFiles(files);
  } catch (Exception e) {
    if (config.getBoolean(FlowLanguageProperties.FAIL_ON_SCANERROR).get()) {
      throw e;
    } else {
      logger.error("** * Exception while scanning file, skipping.", e);
    }
  }
  Collection<SourceCode> nodeSources = scanner.getIndex()
      .search(new QueryByType(SourceFile.class));
  logger.debug("*NODE* nodes found:" + nodeSources.size() + " *");
  for (SourceCode squidSourceFile : squidSourceFiles) {
    for (SourceCode nodeSource : nodeSources) {
      if ((new File(nodeSource.getKey())).getParent()
          .equals((new File(squidSourceFile.getKey())).getParent())) {
        squidSourceFile.addChild(nodeSource);
        String relativePath = pathResolver.relativePath(fileSystem.baseDir(),
            new java.io.File(nodeSource.getKey()));
        InputFile inputFile = fileSystem
            .inputFile(fileSystem.predicates().hasRelativePath(relativePath));
        saveViolations(context, inputFile, (SourceFile) nodeSource);
      }

    }
  }
}
 
Example 26
/**
 * Parse a Cobertura xml report and create measures accordingly
 */
public static void parseReport(File xmlFile, final SensorContext context) {
  try {
    StaxParser parser = new StaxParser(rootCursor -> {
      rootCursor.advance();
      collectPackageMeasures(rootCursor.descendantElementCursor("package"), context);
    });
    parser.parse(xmlFile);
  } catch (XMLStreamException e) {
    throw new IllegalStateException(e);
  }
}
 
Example 27
public static FilePredicate createFilePredicate(Configuration configuration, SensorContext sensorContext) {
    FilePredicates predicates = sensorContext.fileSystem().predicates();

    List<FilePredicate> fileExtensions = getFileExtensionsPredicates(predicates, configuration);
    List<FilePredicate> relativePaths = getPathsPredicate(predicates, configuration);

    return predicates.and(
            predicates.hasType(InputFile.Type.MAIN),
            predicates.or(
                    predicates.hasLanguages(Htl.KEY),
                    predicates.or(fileExtensions)
            ),
            predicates.or(relativePaths)
    );
}
 
Example 28
@Override
public void fillContext(SensorContext sensorContext, AntlrContext antrlContext) {

	final InputFile file = antrlContext.getFile();
	synchronized (sensorContext) {
		try {
			sensorContext.<Integer>newMeasure().on(file).forMetric(CoreMetrics.COMPLEXITY).withValue(complexity)
					.save();
		} catch (final Throwable e) {
			LOGGER.warn(format("Unexpected adding complexity measures on file %s", file.absolutePath()), e);
		}
	}

}
 
Example 29
Source Project: sonar-esql-plugin   Source File: EsqlSensor.java    License: Apache License 2.0 5 votes vote down vote up
private static void saveFileIssue(SensorContext sensorContext, InputFile inputFile, RuleKey ruleKey, FileIssue issue) {
    NewIssue newIssue = sensorContext.newIssue();

    NewIssueLocation primaryLocation = newIssue.newLocation()
            .message(issue.message())
            .on(inputFile);

    saveIssue(newIssue, primaryLocation, ruleKey, issue);
}
 
Example 30
private void processRecognitionException(RecognitionException e, SensorContext sensorContext, InputFile inputFile) {
  if (parsingErrorRuleKey != null) {
    NewIssue newIssue = sensorContext.newIssue();

    NewIssueLocation primaryLocation = newIssue.newLocation()
      .message(e.getMessage())
      .on(inputFile)
      .at(inputFile.selectLine(e.getLine()));

    newIssue
      .forRule(parsingErrorRuleKey)
      .at(primaryLocation)
      .save();
  }
}