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

The following examples show how to use org.sonar.api.batch.sensor.SensorContext. 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
Source File: SimpleCovSensor.java    From sonar-ruby-plugin with 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 #2
Source File: LeinNvdSensor.java    From sonar-clojure with 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 File: ClojureSensor.java    From sonar-clojure with 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 #4
Source File: LeinNvdSensor.java    From sonar-clojure with 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 #5
Source File: KibitSensor.java    From sonar-clojure with 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 #6
Source File: ScannerPullRequestPropertySensor.java    From sonarqube-community-branch-plugin with GNU General Public License v3.0 6 votes vote down vote up
@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 #7
Source File: TsCoverageSensorImpl.java    From SonarTsPlugin with 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 #8
Source File: EsqlSensor.java    From sonar-esql-plugin with 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 #9
Source File: EsqlSensor.java    From sonar-esql-plugin with 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 #10
Source File: EsqlSensor.java    From sonar-esql-plugin with 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 #11
Source File: EsqlSensor.java    From sonar-esql-plugin with 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 #12
Source File: CoberturaSensor.java    From sonar-lua with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #13
Source File: LOCSensorImpl.java    From SonarTsPlugin with 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 #14
Source File: CheckstyleExecutor.java    From sonar-checkstyle with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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 File: MetricsSaver.java    From AEM-Rules-for-SonarQube with 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 #16
Source File: PathResolver.java    From sonar-ruby-plugin with 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 #17
Source File: RubocopSensor.java    From sonar-ruby-plugin with 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 #18
Source File: RubocopSensor.java    From sonar-ruby-plugin with 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 #19
Source File: ValidateLicensesTest.java    From sonarqube-licensecheck with Apache License 2.0 5 votes vote down vote up
@Test
public void licenseUnknown()
{
    SensorContext context = createContext();
    NewIssue issue = new DefaultIssue(mock(DefaultInputProject.class), mock(SensorStorage.class));
    when(context.newIssue()).thenReturn(issue);

    validateLicenses.validateLicenses(deps(new Dependency("thing", "1.0", "Mamamia")), context);

    verify(context).newIssue();
    assertThat(issue.toString(), containsString(LicenseCheckMetrics.LICENSE_CHECK_UNLISTED_KEY));
}
 
Example #20
Source File: FlowSquidSensor.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public void execute(SensorContext context) {
  logger.debug("FlowSquidSensor analysis called");
  AstScanner<Grammar> flowScanner = FlowAstScanner.create(createConfiguration(), flowChecks.all(),
      null);
  logger.debug("Scanning Flow Files with " + flowChecks.all().size() + " checks active");
  FileSystem fs = context.fileSystem();
  Iterable<InputFile> flowFiles = fs
      .inputFiles(fs.predicates().and(fs.predicates().hasLanguage(FlowLanguage.KEY),
          fs.predicates().matchesPathPatterns(FlowLanguage.getFlowFilePatterns())));
  ArrayList<File> files = new ArrayList<File>();
  flowFiles.forEach(file -> files.add(file.file()));
  try {
    flowScanner.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> squidSourceFiles = flowScanner.getIndex()
      .search(new QueryByType(SourceFile.class));
  logger.debug("** Done Scanning");
  // Process sourceFiles
  logger.debug("** Getting Interface Files");
  getInterfaceFiles(squidSourceFiles, context);
  logger.debug("** Setting Top Level Services");
  setTopLevelServices(squidSourceFiles);
  logger.debug("** Saving Source Files");
  save(context, flowScanner, squidSourceFiles);

}
 
Example #21
Source File: CustomAllChecksProvider.java    From sonar-tsql-plugin with GNU General Public License v3.0 5 votes vote down vote up
public CandidateRule[] getChecks(final SensorContext context) {
	final Configuration config = context.config();
	final boolean skipCustomRules = config.getBoolean(Constants.PLUGIN_SKIP_CUSTOM_RULES).orElse(false);
	final String baseDir = context.fileSystem().baseDir().getAbsolutePath();

	final String[] paths = config.getStringArray(Constants.PLUGIN_CUSTOM_RULES_PATH);
	final String rulesPrefix = config.get(Constants.PLUGIN_CUSTOM_RULES_PREFIX).orElse(".customRules");

	final List<SqlRules> rules = new ArrayList<>();

	rules.addAll(provider.getRules(baseDir, rulesPrefix, paths).values());

	if (!skipCustomRules) {
		final SqlRules customRules = pluginChecksProvider.getRules();
		rules.add(customRules);
	}

	for (final SqlRules sqlRules : rules) {
		if (sqlRules.isIsAdhoc()) {
			for (final Rule r : sqlRules.getRule()) {
				context.newAdHocRule().description(r.getDescription()).engineId(sqlRules.getRepoKey())
						.ruleId(r.getKey()).type(RuleType.valueOf(r.getRuleType())).name(r.getName())
						.severity(Severity.valueOf(r.getSeverity())).save();
			}
		}
	}

	final SqlRules[] finalRules = rules.toArray(new SqlRules[0]);

	final CandidateRule[] candidateRules = convert(finalRules);
	LOGGER.info(String.format("Total %s custom rules repositories with total %s checks", rules.size(),
			candidateRules.length));
	return candidateRules;

}
 
Example #22
Source File: EsqlSensor.java    From sonar-esql-plugin with Apache License 2.0 5 votes vote down vote up
public void executeCoverageSensors(SensorContext context) {
 //Removed re-initialization of metriccvisitor as executable lines were empty
   if (metricsVisitor == null) {
	LOG.debug("metricVisitor null");
}

     executeCoverageSensors(context, metricsVisitor.executableLines());
 }
 
Example #23
Source File: GherkinSquidSensor.java    From sonar-gherkin-plugin with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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 #24
Source File: EsqlSensor.java    From sonar-esql-plugin with Apache License 2.0 5 votes vote down vote up
private static void saveLineIssue(SensorContext sensorContext, InputFile inputFile, RuleKey ruleKey, LineIssue issue) {
    NewIssue newIssue = sensorContext.newIssue();

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

    saveIssue(newIssue, primaryLocation, ruleKey, issue);
}
 
Example #25
Source File: ValidateLicensesTest.java    From sonarqube-licensecheck with Apache License 2.0 5 votes vote down vote up
@Test
public void licenseNull()
{
    SensorContext context = createContext();
    NewIssue issue = new DefaultIssue(mock(DefaultInputProject.class), mock(SensorStorage.class));
    when(context.newIssue()).thenReturn(issue);

    validateLicenses.validateLicenses(deps(new Dependency("thing", "1.0", null)), context);

    verify(context).newIssue();
    assertThat(issue.toString(), containsString(LicenseCheckMetrics.LICENSE_CHECK_UNLISTED_KEY));
}
 
Example #26
Source File: ValidateLicensesTest.java    From sonarqube-licensecheck with Apache License 2.0 5 votes vote down vote up
@Test
public void checkSpdxOrAndCombination()
{
    SensorContext context = createContext();

    validateLicenses.validateLicenses(deps(new Dependency("thing", "1.0", "(LGPL OR (Apache-2.0 AND MIT))")),
        context);

    verify(context, never()).newIssue();
}
 
Example #27
Source File: CheckstyleAuditListenerTest.java    From sonar-checkstyle with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Before
public void before() {
    fileSystem = mock(FileSystem.class);
    context = mock(SensorContext.class);
    inputFile = mock(InputFile.class);
    ruleFinder = mock(ActiveRules.class);

    final FilePredicates predicates = mock(FilePredicates.class);
    final FilePredicate filePredicate = mock(FilePredicate.class);
    when(fileSystem.inputFile(any(FilePredicate.class))).thenReturn(inputFile);
    when(fileSystem.predicates()).thenReturn(predicates);
    when(predicates.hasAbsolutePath(anyString())).thenReturn(filePredicate);
}
 
Example #28
Source File: CheckstyleSensorTest.java    From sonar-checkstyle with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void shouldExecuteExecutorWithContext() {
    final SensorContext context = mock(SensorContext.class);
    final CheckstyleExecutor executor = mock(CheckstyleExecutor.class);

    final CheckstyleSensor sensor = new CheckstyleSensor(executor);
    sensor.execute(context);

    verify(executor, times(1)).execute(context);
}
 
Example #29
Source File: ColdFusionSensor.java    From sonar-coldfusion with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(SensorContext context) {
    try {
        analyze(context);
        importResults(context);
        measureProcessor(context);
    } catch (IOException | XMLStreamException e) {
        LOGGER.error("",e);
    }
}
 
Example #30
Source File: LuaSquidSensor.java    From sonar-lua with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void saveFunctionsComplexityDistribution(SensorContext context, InputFile inputFile, SourceFile squidFile) {
  Collection<SourceCode> squidFunctionsInFile = scanner.getIndex().search(new QueryByParent(squidFile), new QueryByType(SourceFunction.class));
  RangeDistributionBuilder complexityDistribution = new RangeDistributionBuilder(FUNCTIONS_DISTRIB_BOTTOM_LIMITS);
  for (SourceCode squidFunction : squidFunctionsInFile) {
    complexityDistribution.add(squidFunction.getDouble(LuaMetric.COMPLEXITY));
  }
  context.<String>newMeasure()
    .on(inputFile)
    .forMetric(CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION)
    .withValue(complexityDistribution.build())
    .save();
}