当前位置: 首页>>代码示例>>Java>>正文


Java SensorContext类代码示例

本文整理汇总了Java中org.sonar.api.batch.sensor.SensorContext的典型用法代码示例。如果您正苦于以下问题:Java SensorContext类的具体用法?Java SensorContext怎么用?Java SensorContext使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


SensorContext类属于org.sonar.api.batch.sensor包,在下文中一共展示了SensorContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: analyseFiles

import org.sonar.api.batch.sensor.SensorContext; //导入依赖的package包/类
@VisibleForTesting
protected void analyseFiles(
        SensorContext context,
        List<TreeVisitor> treeVisitors,
        Iterable<InputFile> inputFiles,
        ProgressReport progressReport) {
    boolean success = false;
    try {
        for (InputFile inputFile : inputFiles) {
            if (context.isCancelled()) {
                throw new CancellationException("Analysis interrupted because the SensorContext is in cancelled state");
            }
            analyseFile(context, inputFile, treeVisitors);
            progressReport.nextFile();
        }
        success = true;
    } catch (CancellationException e) {  //NOSONAR
        // do not propagate the exception
        LOG.debug(e.toString());
    } finally {
        stopProgressReport(progressReport, success);
    }
}
 
开发者ID:antowski,项目名称:sonar-onec,代码行数:24,代码来源:OneCSensor.java

示例2: scanModel

import org.sonar.api.batch.sensor.SensorContext; //导入依赖的package包/类
@Override
public void scanModel(final SensorContext context, final ActiveRule rule, final Model<Location> model) {
	final Integer maximum = Integer.valueOf(rule.param(PARAM_MAXIMUM));

	for (final Package<Location> packageToCheck : model.getPackages()) {
		final int afferentCoupling = packageToCheck.getUsedByPackages().size();

		LOGGER.debug("Package {}: afferent={}", packageToCheck.getName(), afferentCoupling);

		if (afferentCoupling > maximum) {
			final Set<Class<Location>> classes = selectClassesWithAfferentUsage(packageToCheck.getClasses());

			registerIssue(context, settings, rule, packageToCheck, classes,
					"Reduce number of packages that use this package (allowed: " + maximum + ", actual: "
							+ afferentCoupling + ")");
		}
	}
}
 
开发者ID:willemsrb,项目名称:sonar-packageanalyzer-plugin,代码行数:19,代码来源:AfferentCouplingRule.java

示例3: scanModel

import org.sonar.api.batch.sensor.SensorContext; //导入依赖的package包/类
@Override
public void scanModel(final SensorContext context, final ActiveRule rule, final Model<Location> model) {
	final Integer maximum = Integer.valueOf(rule.param(PARAM_MAXIMUM));

	for (final Package<Location> packageToCheck : model.getPackages()) {
		final int efferentCoupling = packageToCheck.getPackageUsages().size();

		LOGGER.debug("Package {}: efferent={}", packageToCheck.getName(), efferentCoupling);

		if (efferentCoupling > maximum) {
			final Set<Class<Location>> classes = selectClassesWithEfferentUsage(packageToCheck.getClasses());

			registerIssue(context, settings, rule, packageToCheck, classes,
					"Reduce number of packages used by this package (allowed: " + maximum + ", actual: "
							+ efferentCoupling + ")");
		}
	}
}
 
开发者ID:willemsrb,项目名称:sonar-packageanalyzer-plugin,代码行数:19,代码来源:EfferentCouplingRule.java

示例4: scanModel

import org.sonar.api.batch.sensor.SensorContext; //导入依赖的package包/类
@Override
public void scanModel(final SensorContext context, final ActiveRule rule, final Model<Location> model) {
	final Integer maximum = Integer.valueOf(rule.param(PARAM_MAXIMUM));

	for (final Package<Location> packageToCheck : model.getPackages()) {
		final int afferentCoupling = packageToCheck.getUsedByPackages().size();
		final int efferentCoupling = packageToCheck.getPackageUsages().size();
		final int totalCoupling = efferentCoupling + afferentCoupling;
		final int instability = totalCoupling == 0 ? 0 : (efferentCoupling * 100) / totalCoupling;

		LOGGER.debug("Package {}: efferent={}, total={}, instability={}", packageToCheck.getName(),
				efferentCoupling, totalCoupling, instability);

		if (instability > maximum) {
			final Set<Class<Location>> classes = EfferentCouplingRule
					.selectClassesWithEfferentUsage(packageToCheck.getClasses());

			registerIssue(context, settings, rule, packageToCheck, classes,
					"Reduce number of packages used by this package to lower instability (allowed: " + maximum
							+ "%, actual: " + instability + "%)");
		}
	}
}
 
开发者ID:willemsrb,项目名称:sonar-packageanalyzer-plugin,代码行数:24,代码来源:InstabilityRule.java

示例5: scanModel

import org.sonar.api.batch.sensor.SensorContext; //导入依赖的package包/类
@Override
public void scanModel(final SensorContext context, final ActiveRule rule, final Model<Location> model) {
	final Integer maximum = Integer.valueOf(rule.param(PARAM_MAXIMUM));

	for (final Package<Location> packageToCheck : model.getPackages()) {
		final Set<Class<Location>> classes = packageToCheck.getClasses().stream().filter(Class::isAbstract)
				.collect(Collectors.toSet());
		final int abstractClasses = classes.size();
		final int totalClasses = packageToCheck.getClasses().size();
		final int abstractness = totalClasses == 0 ? 0 : (abstractClasses * 100 / totalClasses);

		LOGGER.debug("Package {}: abstract={}, total={}, abstractness={}", packageToCheck.getName(),
				abstractClasses, totalClasses, abstractness);

		if (abstractness > maximum) {
			registerIssue(context, settings, rule, packageToCheck, classes,
					"Reduce number of abstract classes in this package (allowed: " + maximum + "%, actual: "
							+ abstractness + "%)");
		}
	}
}
 
开发者ID:willemsrb,项目名称:sonar-packageanalyzer-plugin,代码行数:22,代码来源:AbstractnessRule.java

示例6: execute

import org.sonar.api.batch.sensor.SensorContext; //导入依赖的package包/类
@Override
public void execute(SensorContext context) {
    //check if rule is active
    List<String> rules = Arrays.asList(SURVIVED_MUTANT_RULE_KEY, NO_COVERAGE_MUTANT_RULE_KEY);
    if (rules.stream().anyMatch(this::isRuleActive)) {
        try {
            StrykerEventsDirectory strykerEvents = new StrykerEventsDirectory(settings, fileSystem);
            MutantResultJsonReader reader = new MutantResultJsonReader();
            Optional<String> allMutantTestedEventFileContent = strykerEvents.readOnAllMutantsTestedFile();
            if (allMutantTestedEventFileContent.isPresent()) {
                List<MutantResult> mutantResults = reader.readMutants(allMutantTestedEventFileContent.get());
                createIssues(mutantResults, context);
            } else {
                log.warn("Could not find stryker report, not reporting issues.");
            }
        } catch (IOException e) {
            log.error("Could not read from Stryker event file.", e);
        } catch (RuntimeException runTimeEx) {
            log.error("Something went wrong.", runTimeEx);
        }
    } else {
        log.info("Rules {} were not active, cannot create issues.", rules);
    }
}
 
开发者ID:stryker-mutator,项目名称:sonar-stryker-plugin,代码行数:25,代码来源:StrykerSensor.java

示例7: createIssuesForMutants

import org.sonar.api.batch.sensor.SensorContext; //导入依赖的package包/类
private void createIssuesForMutants(List<MutantResult> mutantResults, SensorContext context, MutantStatus targetStatus, String ruleKey) throws IOException {
    if (isRuleActive(ruleKey)) {
        int count = 0;
        for (MutantResult mutantResult : mutantResults) {
            if (mutantResult.getStatus() == targetStatus) {
                count++;
                InputFile file = locateSourceFile(mutantResult.getSourceFilePath());

                NewIssue issue = context.newIssue();
                NewIssueLocation location = issue.newLocation()
                        .on(file)
                        .at(mutantResult.getLocation().getRange(file))
                        .message(formatIssueMessage(mutantResult));
                issue.at(location);
                issue.forRule(RuleKey.of(RULE_REPOSITORY_KEY, ruleKey));
                issue.save();
            }
        }
        log.info("Reported {} issue(s) as {}.", count, targetStatus);
    } else {
        log.info("Skip reporting {} mutant(s), because rule {} is inactive", targetStatus, ruleKey);
    }
}
 
开发者ID:stryker-mutator,项目名称:sonar-stryker-plugin,代码行数:24,代码来源:StrykerSensor.java

示例8: execute

import org.sonar.api.batch.sensor.SensorContext; //导入依赖的package包/类
@Override
public void execute(SensorContext context) {
	LOGGER.info("FramaCSensor is running...");
	FileSystem fs = context.fileSystem();
	LOGGER.info("FramaCSensor : file system base dir = " + fs.baseDir());
	FilePredicates p = fs.predicates();
	LOGGER.info("FramaCSensor : file system base dir = " + fs.hasFiles(p.all()));
	
	readPluginSettings(context);
	
	// Only "main" files, but not "tests"
	String[] aMatchingPatterns = matchingPatterns();
	Iterable<InputFile> filesC = fs.inputFiles(fs.predicates().matchesPathPatterns(aMatchingPatterns));
	for (InputFile file : filesC) {
		LOGGER.debug("FramaCSensor : current input file = " + file.absolutePath());

		// Check for report out
		String fileRelativePathNameReportOut = outReportFileName(file);

		// Analyse report out
		analyseReportOut(context, file, fileRelativePathNameReportOut);
	}
	LOGGER.info("FramaCSensor done!");
}
 
开发者ID:lequal,项目名称:sonar-frama-c-plugin,代码行数:25,代码来源:FramaCMetricsSensor.java

示例9: storeCyclomaticMeasures

import org.sonar.api.batch.sensor.SensorContext; //导入依赖的package包/类
/**
 * Store measures from a valid report file into Frama-C Metrics.
 * 
 * @param context Sonar sensor context
 * @param file input code file 
 * @param cyclomaticValueMin minimum
 * @param cyclomaticValueMax maximum
 * @param cyclomaticValueMean mean
 * @param value cyclomatic complexity value
 * 
 * @see ICodeMetrics
 */
private void storeCyclomaticMeasures(SensorContext context, InputFile file, double cyclomaticValueMin,
		double cyclomaticValueMax, double cyclomaticValueMean, double value) {
	// Store module CYCLOMATIC, MEAN, MIN, MAX
	context.<Integer>newMeasure()
	.forMetric(CyclomaticMetrics.CYCLOMATIC)
	.on(file)
	.withValue(Integer.valueOf((int)value))
	.save();
	context.<Integer>newMeasure()
	.forMetric(CyclomaticMetrics.CYCLOMATIC_MAX)
	.on(file)
	.withValue(Integer.valueOf((int)cyclomaticValueMax))
	.save();
	context.<Integer>newMeasure()
	.forMetric(CyclomaticMetrics.CYCLOMATIC_MIN)
	.on(file)
	.withValue(Integer.valueOf((int)cyclomaticValueMin))
	.save();
	context.<Double>newMeasure()
	.forMetric(CyclomaticMetrics.CYCLOMATIC_MEAN)
	.on(file)
	.withValue(Double.valueOf(cyclomaticValueMean))
	.save();
}
 
开发者ID:lequal,项目名称:sonar-frama-c-plugin,代码行数:37,代码来源:FramaCMetricsSensor.java

示例10: storeLocMeasures

import org.sonar.api.batch.sensor.SensorContext; //导入依赖的package包/类
/**
 * Store measures from a valid report file into Frama-C Metrics.
 * 
 * @param context Sonar sensor context
 * @param file input code file 
 * @param locValueMin minimum
 * @param locValueMax maximum
 * @param locValueMean mean
 * @param value loc complexity value
 * 
 * @see ICodeMetrics
 */
private void storeLocMeasures(SensorContext context, InputFile file, double locValueMin,
		double locValueMax, double locValueMean, double value) {
	// Store module loc, MEAN, MIN, MAX
	context.<Integer>newMeasure()
	.forMetric(CyclomaticMetrics.SLOC)
	.on(file)
	.withValue(Integer.valueOf((int)value))
	.save();
	context.<Integer>newMeasure()
	.forMetric(CyclomaticMetrics.SLOC_MAX)
	.on(file)
	.withValue(Integer.valueOf((int)locValueMax))
	.save();
	context.<Integer>newMeasure()
	.forMetric(CyclomaticMetrics.SLOC_MIN)
	.on(file)
	.withValue(Integer.valueOf((int)locValueMin))
	.save();
	context.<Double>newMeasure()
	.forMetric(CyclomaticMetrics.SLOC_MEAN)
	.on(file)
	.withValue(Double.valueOf(locValueMean))
	.save();
}
 
开发者ID:lequal,项目名称:sonar-frama-c-plugin,代码行数:37,代码来源:FramaCMetricsSensor.java

示例11: parseReportIssues

import org.sonar.api.batch.sensor.SensorContext; //导入依赖的package包/类
private void parseReportIssues(SensorContext context, InputFile file, ReportInterface report) {
	LOGGER.info("Parse and store report issues (doing...)");
	
	// Read all report issues
	ErrorInterface[] errors = report.getErrors();

	// Create issues for this file
	if(errors != null){
		InputFile inputFile = file;
		for (ErrorInterface error : errors) {
			String lineString = error.getLineDescriptor();
			String message = error.getDescription();
			String externalRuleKey = error.getRuleKey();
			saveIssue(context, inputFile, lineString, externalRuleKey , message);
		}
	}
	LOGGER.info("Parse and store report issues (done)");
}
 
开发者ID:lequal,项目名称:sonar-frama-c-plugin,代码行数:19,代码来源:FramaCMetricsSensor.java

示例12: saveIssue

import org.sonar.api.batch.sensor.SensorContext; //导入依赖的package包/类
private void saveIssue(final SensorContext context, final InputFile inputFile, String lineString, final String externalRuleKey, final String message) {
  RuleKey ruleKey = RuleKey.of(FramaCRulesDefinition.getRepositoryKeyForLanguage(), externalRuleKey);

  LOGGER.info("externalRuleKey: "+externalRuleKey);
  LOGGER.info("Repo: "+FramaCRulesDefinition.getRepositoryKeyForLanguage());
  LOGGER.info("RuleKey: "+ruleKey);
  NewIssue newIssue = context.newIssue()
    .forRule(ruleKey);

  NewIssueLocation primaryLocation = newIssue.newLocation()
    .on(inputFile)
    .message(message);
  
  int maxLine = inputFile.lines();
  int iLine = getLineAsInt(lineString, maxLine);
  if (iLine > 0) {
    primaryLocation.at(inputFile.selectLine(iLine));
  }
  newIssue.at(primaryLocation);

  newIssue.save();
}
 
开发者ID:lequal,项目名称:sonar-frama-c-plugin,代码行数:23,代码来源:FramaCMetricsSensor.java

示例13: importResults

import org.sonar.api.batch.sensor.SensorContext; //导入依赖的package包/类
public void importResults(SensorContext context, Path protobufReportsDirectory, boolean importIssues) {

    Predicate<InputFile> inputFileFilter;
    if (!config.isReportsComingFromMSBuild()) {
      // Filter was not executed during FS indexing because protobuf reports were not present (MSBuild 12 or old scanner)
      encodingPerFile.init(protobufReportsDirectory);
      inputFileFilter = encodingPerFile::encodingMatch;
    } else {
      // Files with wrong encoding were already skipped
      inputFileFilter = f -> true;
    }

    // Note: the no-sonar "measure" must be imported before issues, otherwise the affected issues won't get excluded!
    parseProtobuf(ProtobufImporters.metricsImporter(context, fileLinesContextFactory, noSonarFilter, inputFileFilter), protobufReportsDirectory, METRICS_OUTPUT_PROTOBUF_NAME);
    if (importIssues) {
      parseProtobuf(ProtobufImporters.issuesImporter(context, repositoryKey, inputFileFilter), protobufReportsDirectory, ISSUES_OUTPUT_PROTOBUF_NAME);
    }
    parseProtobuf(ProtobufImporters.highlightImporter(context, inputFileFilter), protobufReportsDirectory, HIGHLIGHT_OUTPUT_PROTOBUF_NAME);
    parseProtobuf(ProtobufImporters.symbolRefsImporter(context, inputFileFilter), protobufReportsDirectory, SYMBOLREFS_OUTPUT_PROTOBUF_NAME);
    parseProtobuf(ProtobufImporters.cpdTokensImporter(context, inputFileFilter), protobufReportsDirectory, CPDTOKENS_OUTPUT_PROTOBUF_NAME);
  }
 
开发者ID:SonarSource,项目名称:sonar-dotnet-shared-library,代码行数:22,代码来源:AbstractSensor.java

示例14: analyseFile

import org.sonar.api.batch.sensor.SensorContext; //导入依赖的package包/类
private void analyseFile(InputFile inputFile, Charset charset, SensorContext context) {
    log.debug("Analysing file {}", inputFile);
    File file = inputFile.file();
    Map<CounterType, AtomicInteger> lines = countLines(file, charset);

    context.<Integer>newMeasure().on(inputFile)
        .withValue(lines.get(CounterType.CODE).get())
        .forMetric(CoreMetrics.NCLOC).save();

    context.<Integer>newMeasure().on(inputFile)
    .withValue(lines.get(CounterType.COMMENT).get())
    .forMetric(CoreMetrics.COMMENT_LINES).save();

    context.<Integer>newMeasure().on(inputFile)
    .withValue(lines.get(CounterType.CLASS).get())
    .forMetric(CoreMetrics.CLASSES).save();

    context.<Integer>newMeasure().on(inputFile)
    .withValue(lines.get(CounterType.FUNCTION).get())
    .forMetric(CoreMetrics.FUNCTIONS).save();
}
 
开发者ID:sonar-perl,项目名称:sonar-perl,代码行数:22,代码来源:GlobalSensor.java

示例15: execute

import org.sonar.api.batch.sensor.SensorContext; //导入依赖的package包/类
@Override
public void execute(SensorContext context) {

    Optional<String> reportPath = getReportPath(context);
    Optional<File> reportFile = reportPath.map(File::new).filter(File::exists);

    try {
        if (reportFile.isPresent()) {
            List<PerlCriticViolation> violations = parse(reportFile.get());
            new PerlCriticParserExecutor(context).save(violations);
        } else {
            log.info("PerlCritic report file '{}' does not exist. Skipping...", reportPath.orElse(""));
        }
    } catch (IOException e) {
        throw new IllegalStateException("Unable to parse the provided PerlCritic report file", e);
    }
}
 
开发者ID:sonar-perl,项目名称:sonar-perl,代码行数:18,代码来源:PerlCriticIssuesLoaderSensor.java


注:本文中的org.sonar.api.batch.sensor.SensorContext类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。