Exemplo n.º 1
0
  @Test
  public void shouldReuseReport() throws Exception {
    Project project = createProject();
    FindbugsExecutor executor = mock(FindbugsExecutor.class);
    SensorContext context = mock(SensorContext.class);
    Configuration conf = mock(Configuration.class);
    File xmlFile =
        new File(getClass().getResource("/org/sonar/plugins/findbugs/findbugsReport.xml").toURI());
    when(conf.getString(CoreProperties.FINDBUGS_REPORT_PATH)).thenReturn(xmlFile.getAbsolutePath());
    when(project.getConfiguration()).thenReturn(conf);
    when(context.getResource(any(Resource.class))).thenReturn(new JavaFile("org.sonar.MyClass"));

    FindbugsSensor analyser =
        new FindbugsSensor(createRulesProfileWithActiveRules(), new FakeRuleFinder(), executor);
    analyser.analyse(project, context);

    verify(executor, never()).execute();
    verify(context, times(2)).saveViolation(any(Violation.class));

    Violation wanted =
        Violation.create((Rule) null, new JavaFile("org.sonar.commons.ZipUtils"))
            .setMessage(
                "Empty zip file entry created in org.sonar.commons.ZipUtils._zip(String, File, ZipOutputStream)")
            .setLineId(107);
    verify(context).saveViolation(argThat(new IsViolation(wanted)));

    wanted =
        Violation.create((Rule) null, new JavaFile("org.sonar.commons.resources.MeasuresDao"))
            .setMessage(
                "The class org.sonar.commons.resources.MeasuresDao$1 could be refactored into a named _static_ inner class")
            .setLineId(56);
    verify(context).saveViolation(argThat(new IsViolation(wanted)));
  }
Exemplo n.º 2
0
 private void deleteDeprecatedEvents(Project project, SensorContext context) {
   String version = project.getAnalysisVersion();
   for (Iterator<Event> it = context.getEvents(project).iterator(); it.hasNext(); ) {
     Event event = it.next();
     if (event.isVersionCategory() && version.equals(event.getName())) {
       it.remove();
       context.deleteEvent(event);
     }
   }
 }
Exemplo n.º 3
0
  @Override
  public void scanFile(JavaFileScannerContext context) {
    sonarFile = fs.inputFile(fs.predicates().is(context.getFile()));
    classTrees.clear();
    methods = 0;
    complexityInMethods = 0;
    accessors = 0;
    classes = 0;
    PublicApiChecker publicApiChecker = PublicApiChecker.newInstanceWithAccessorsHandledAsMethods();
    if (separateAccessorsFromMethods) {
      publicApiChecker = PublicApiChecker.newInstanceWithAccessorsSeparatedFromMethods();
    }
    publicApiChecker.scan(context.getTree());
    methodComplexityDistribution =
        new RangeDistributionBuilder(
            CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION, LIMITS_COMPLEXITY_METHODS);
    CommentLinesVisitor commentLinesVisitor = new CommentLinesVisitor();
    commentLinesVisitor.analyzeCommentLines(context.getTree());
    noSonarFilter.addComponent(
        sensorContext.getResource(sonarFile).getEffectiveKey(), commentLinesVisitor.noSonarLines());
    super.scanFile(context);
    // leave file.
    int fileComplexity = context.getComplexityNodes(context.getTree()).size();
    saveMetricOnFile(CoreMetrics.CLASSES, classes);
    saveMetricOnFile(CoreMetrics.FUNCTIONS, methods);
    saveMetricOnFile(CoreMetrics.ACCESSORS, accessors);
    saveMetricOnFile(CoreMetrics.COMPLEXITY_IN_FUNCTIONS, complexityInMethods);
    saveMetricOnFile(CoreMetrics.COMPLEXITY_IN_CLASSES, fileComplexity);
    saveMetricOnFile(CoreMetrics.COMPLEXITY, fileComplexity);
    saveMetricOnFile(CoreMetrics.PUBLIC_API, publicApiChecker.getPublicApi());
    saveMetricOnFile(
        CoreMetrics.PUBLIC_DOCUMENTED_API_DENSITY,
        publicApiChecker.getDocumentedPublicApiDensity());
    saveMetricOnFile(
        CoreMetrics.PUBLIC_UNDOCUMENTED_API, publicApiChecker.getUndocumentedPublicApi());
    saveMetricOnFile(CoreMetrics.COMMENT_LINES, commentLinesVisitor.commentLinesMetric());
    saveMetricOnFile(
        CoreMetrics.STATEMENTS, new StatementVisitor().numberOfStatements(context.getTree()));
    saveMetricOnFile(CoreMetrics.NCLOC, new LinesOfCodeVisitor().linesOfCode(context.getTree()));

    sensorContext.saveMeasure(
        sonarFile,
        methodComplexityDistribution.build(true).setPersistenceMode(PersistenceMode.MEMORY));

    RangeDistributionBuilder fileComplexityDistribution =
        new RangeDistributionBuilder(
            CoreMetrics.FILE_COMPLEXITY_DISTRIBUTION, LIMITS_COMPLEXITY_FILES);
    sensorContext.saveMeasure(
        sonarFile,
        fileComplexityDistribution
            .add(fileComplexity)
            .build(true)
            .setPersistenceMode(PersistenceMode.MEMORY));
    saveLinesMetric();
  }
Exemplo n.º 4
0
  public void analyse(Project project, SensorContext context) {
    this.project = project;
    this.context = context;

    Collection<SquidAstVisitor<LexerlessGrammar>> squidChecks = annotationCheckFactory.getChecks();
    List<SquidAstVisitor<LexerlessGrammar>> visitors = Lists.newArrayList(squidChecks);
    visitors.add(new FileLinesVisitor(project, fileLinesContextFactory));
    this.scanner =
        FlexAstScanner.create(
            createConfiguration(project), visitors.toArray(new SquidAstVisitor[visitors.size()]));
    Collection<java.io.File> files =
        InputFileUtils.toFiles(project.getFileSystem().mainFiles(Flex.KEY));
    files = ImmutableList.copyOf(Collections2.filter(files, Predicates.not(MXML_FILTER)));
    scanner.scanFiles(files);

    Collection<SourceCode> squidSourceFiles =
        scanner.getIndex().search(new QueryByType(SourceFile.class));
    save(squidSourceFiles);

    Collection<SourceCode> squidPackages =
        scanner.getIndex().search(new QueryByType(FlexSquidPackage.class));
    for (SourceCode pkg : squidPackages) {
      String packageName = pkg.getKey();
      if (!"".equals(packageName)) {
        Directory directory = resourceBridge.findDirectory(packageName);
        context.saveMeasure(directory, CoreMetrics.PACKAGES, 1.0);
      }
    }
  }
Exemplo n.º 5
0
  public void saveDesign(Project sonarProject) {
    Collection<Resource> directories = resourceMapping.directories();
    TimeProfiler profiler = new TimeProfiler(LOG).start("Package design analysis");
    LOG.debug("{} packages to analyze", directories.size());

    IncrementalCyclesAndFESSolver<Resource> cyclesAndFESSolver =
        new IncrementalCyclesAndFESSolver<>(graph, directories);
    LOG.debug("{} cycles", cyclesAndFESSolver.getCycles().size());

    Set<Edge> feedbackEdges = cyclesAndFESSolver.getFeedbackEdgeSet();
    LOG.debug("{} feedback edges", feedbackEdges.size());
    int tangles = cyclesAndFESSolver.getWeightOfFeedbackEdgeSet();

    saveIssues(feedbackEdges);
    saveDependencies();
    savePositiveMeasure(
        sonarProject, CoreMetrics.PACKAGE_CYCLES, cyclesAndFESSolver.getCycles().size());
    savePositiveMeasure(sonarProject, CoreMetrics.PACKAGE_FEEDBACK_EDGES, feedbackEdges.size());
    savePositiveMeasure(sonarProject, CoreMetrics.PACKAGE_TANGLES, tangles);
    savePositiveMeasure(
        sonarProject, CoreMetrics.PACKAGE_EDGES_WEIGHT, getEdgesWeight(directories));

    String dsmJson = serializeDsm(graph, directories, feedbackEdges);
    Measure dsmMeasure =
        new Measure(CoreMetrics.DEPENDENCY_MATRIX, dsmJson)
            .setPersistenceMode(PersistenceMode.DATABASE);
    context.saveMeasure(sonarProject, dsmMeasure);

    profiler.stop();

    for (Resource sonarPackage : directories) {
      onPackage(sonarPackage);
    }
  }
Exemplo n.º 6
0
 private Collection<Resource> getResourcesForDirectory(Resource sonarPackage) {
   List<Resource> result = Lists.newArrayList();
   for (Resource resource : resourceMapping.files((Directory) sonarPackage)) {
     result.add(context.getResource(resource));
   }
   return result;
 }
Exemplo n.º 7
0
 private void saveDependencies() {
   for (Resource resource : graph.getVertices()) {
     for (Dependency dependency : graph.getOutgoingEdges(resource)) {
       context.saveDependency(dependency);
     }
   }
 }
Exemplo n.º 8
0
 public void analyse(Project project, SensorContext context) {
   if (StringUtils.isBlank(project.getAnalysisVersion())) {
     return;
   }
   deleteDeprecatedEvents(project, context);
   context.createEvent(project, project.getAnalysisVersion(), null, Event.CATEGORY_VERSION, null);
 }
Exemplo n.º 9
0
 private void saveFilesComplexityDistribution(File sonarFile, SourceFile squidFile) {
   RangeDistributionBuilder complexityDistribution =
       new RangeDistributionBuilder(
           CoreMetrics.FILE_COMPLEXITY_DISTRIBUTION, FILES_DISTRIB_BOTTOM_LIMITS);
   complexityDistribution.add(squidFile.getDouble(FlexMetric.COMPLEXITY));
   context.saveMeasure(
       sonarFile, complexityDistribution.build().setPersistenceMode(PersistenceMode.MEMORY));
 }
 private void createViolation(SMInputCursor violationsCursor, Rule currentRule)
     throws XMLStreamException {
   org.sonar.api.resources.File sonarFile =
       org.sonar.api.resources.File.fromIOFile(
           new File(violationsCursor.getAttrValue("Source")), project);
   if (context.isIndexed(sonarFile, false)) {
     Violation violation = Violation.create(currentRule, sonarFile);
     String lineNumber = violationsCursor.getAttrValue("LineNumber");
     if (lineNumber != null) {
       violation.setLineId(Integer.parseInt(lineNumber));
     }
     violation.setMessage(violationsCursor.collectDescendantText().trim());
     violation.setSeverity(currentRule.getSeverity());
     context.saveViolation(violation);
   } else {
     LOG.debug("Violation could not be saved, associated resource not indexed " + sonarFile);
   }
 }
Exemplo n.º 11
0
 protected void saveViolations(DroolsFile resource, SensorContext context, VerifierReport report) {
   List<Violation> violations = new ArrayList<Violation>();
   for (Severity severity : Severity.values()) {
     Collection<VerifierMessageBase> messages = report.getBySeverity(severity);
     for (VerifierMessageBase base : messages) {
       Rule rule = findRule(base);
       // ignore violations from report, if rule not activated in Sonar
       if (rule != null) {
         if (context.getResource(resource) != null) {
           int line = getLineNumber(resource, base);
           Violation violation =
               Violation.create(rule, resource).setLineId(line).setMessage(base.getMessage());
           violations.add(violation);
         }
       }
     }
   }
   context.saveViolations(violations);
 }
Exemplo n.º 12
0
  @Test
  public void shouldIgnoreNotActiveViolations() throws Exception {
    Project project = createProject();
    FindbugsExecutor executor = mock(FindbugsExecutor.class);
    SensorContext context = mock(SensorContext.class);
    Configuration conf = mock(Configuration.class);
    File xmlFile =
        new File(
            getClass()
                .getResource("/org/sonar/plugins/findbugs/findbugsReportWithUnknownRule.xml")
                .toURI());
    when(conf.getString(CoreProperties.FINDBUGS_REPORT_PATH)).thenReturn(xmlFile.getAbsolutePath());
    when(project.getConfiguration()).thenReturn(conf);
    when(context.getResource(any(Resource.class))).thenReturn(new JavaFile("org.sonar.MyClass"));

    FindbugsSensor analyser =
        new FindbugsSensor(createRulesProfileWithActiveRules(), new FakeRuleFinder(), executor);
    analyser.analyse(project, context);

    verify(context, never()).saveViolation(any(Violation.class));
  }
Exemplo n.º 13
0
 private void saveViolations(File sonarFile, SourceFile squidFile) {
   Collection<CheckMessage> messages = squidFile.getCheckMessages();
   if (messages != null) {
     for (CheckMessage message : messages) {
       Violation violation =
           Violation.create(annotationCheckFactory.getActiveRule(message.getCheck()), sonarFile)
               .setLineId(message.getLine())
               .setMessage(message.getText(Locale.ENGLISH));
       context.saveViolation(violation);
     }
   }
 }
Exemplo n.º 14
0
 private int countErrors(SensorContext context, Logger logger) {
   Collection<Measure> measures = context.getMeasures(MeasuresFilters.all());
   int count = 0;
   for (Measure measure : measures) {
     if (isErrorAlert(measure)) {
       logger.error(measure.getAlertText());
       count++;
     } else if (isWarningAlert(measure)) {
       logger.warn(measure.getAlertText());
     }
   }
   return count;
 }
Exemplo n.º 15
0
  private void analyseSingleFile(SensorContext context, String fileName) {
    fileSystem.add(
        new DefaultInputFile(fileName)
            .setAbsolutePath(TestUtils.getResource(fileName).getAbsolutePath())
            .setType(InputFile.Type.MAIN)
            .setLanguage(Php.KEY));

    Resource resource = mock(Resource.class);

    when(resource.getEffectiveKey()).thenReturn("someKey");
    when(context.getResource(any(InputFile.class))).thenReturn(resource);
    sensor.analyse(new Project(""), context);
  }
Exemplo n.º 16
0
 private void saveFunctionsComplexityDistribution(File sonarFile, SourceFile squidFile) {
   Collection<SourceCode> squidFunctionsInFile =
       scanner
           .getIndex()
           .search(new QueryByParent(squidFile), new QueryByType(SourceFunction.class));
   RangeDistributionBuilder complexityDistribution =
       new RangeDistributionBuilder(
           CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION, FUNCTIONS_DISTRIB_BOTTOM_LIMITS);
   for (SourceCode squidFunction : squidFunctionsInFile) {
     complexityDistribution.add(squidFunction.getDouble(FlexMetric.COMPLEXITY));
   }
   context.saveMeasure(
       sonarFile, complexityDistribution.build().setPersistenceMode(PersistenceMode.MEMORY));
 }
  @Test
  public void should_carry_on_after_error() {
    InputFile first = file("source.java");
    InputFile second = file("UNKNOWN.java");
    when(conf.getThreadCount()).thenReturn(1);
    fs.add(first);
    fs.add(second);
    when(context.getResource(any(org.sonar.api.resources.File.class))).thenReturn(file);
    when(blameVersionSelector.detect(file, first, context)).thenThrow(new RuntimeException("BUG"));
    when(blameVersionSelector.detect(file, second, context)).thenReturn(measureUpdate);

    scmActivitySensor.analyse(project, context);

    verify(measureUpdate).execute(timeMachine, context);
  }
Exemplo n.º 18
0
 private static void collectPackageMeasures(SMInputCursor pack, SensorContext context)
     throws XMLStreamException {
   while (pack.getNext() != null) {
     Map<String, CoverageMeasuresBuilder> builderByFilename = Maps.newHashMap();
     collectFileMeasures(pack.descendantElementCursor("class"), builderByFilename);
     for (Map.Entry<String, CoverageMeasuresBuilder> entry : builderByFilename.entrySet()) {
       org.sonar.api.resources.File file = new org.sonar.api.resources.File(entry.getKey());
       if (fileExists(context, file)) {
         for (Measure measure : entry.getValue().createMeasures()) {
           context.saveMeasure(file, measure);
         }
       }
     }
   }
 }
Exemplo n.º 19
0
  public void analyse(Project project, SensorContext context) {
    List<QProfileWithId> profiles = Lists.newArrayList();
    for (String language : fs.languages()) {
      QProfileWithId qProfile = (QProfileWithId) moduleQProfiles.findByLanguage(language);
      if (qProfile != null) {
        dao.updateUsedColumn(qProfile.id(), true);
        profiles.add(qProfile);
      }
    }
    UsedQProfiles used = UsedQProfiles.fromProfiles(profiles);
    Measure detailsMeasure = new Measure(CoreMetrics.QUALITY_PROFILES, used.toJSON());
    context.saveMeasure(detailsMeasure);

    // For backward compatibility
    if (profiles.size() == 1) {
      QProfileWithId qProfile = profiles.get(0);
      Measure measure =
          new Measure(CoreMetrics.PROFILE, qProfile.name()).setValue((double) qProfile.id());
      Measure measureVersion =
          new Measure(CoreMetrics.PROFILE_VERSION, qProfile.version().doubleValue());
      context.saveMeasure(measure);
      context.saveMeasure(measureVersion);
    }
  }
  @Test
  public void should_ignore_violation_on_unknown_rule() {
    when(projectFileSystem.getTestDirs()).thenReturn(Arrays.asList(new File("/test")));
    when(pmdViolation.getFilename()).thenReturn("/test/source.java");
    when(pmdViolation.getRule()).thenReturn(rule);
    when(rule.getName()).thenReturn("UNKNOWN");
    when(context.getResource(new JavaFile("[default].source")))
        .thenReturn(new JavaFile("[default].source"));

    PmdViolationToRuleViolation pmdViolationToRuleViolation =
        new PmdViolationToRuleViolation(projectFileSystem, ruleFinder);
    Violation violation = pmdViolationToRuleViolation.toViolation(pmdViolation, context);

    assertThat(violation).isNull();
  }
 private void saveCoverageData(CoverageFileData data) {
   if (data == null) {
     return;
   }
   Measure<Double> overallCoverage = new Measure<Double>(CoreMetrics.COVERAGE, data.getCoverage());
   Measure<Double> lineCoverage =
       new Measure<Double>(CoreMetrics.LINE_COVERAGE, data.getCoverage());
   Measure<Double> linesToCover =
       new Measure<Double>(CoreMetrics.LINES_TO_COVER, data.getTotalLines());
   Measure<Double> uncoveredLines =
       new Measure<Double>(CoreMetrics.UNCOVERED_LINES, data.getUncoveredLines());
   Measure<?> lineHits =
       data.getLineHitsBuilder().build().setPersistenceMode(PersistenceMode.DATABASE);
   try {
     context.saveMeasure(data.getResource(), overallCoverage);
     context.saveMeasure(data.getResource(), lineCoverage);
     context.saveMeasure(data.getResource(), linesToCover);
     context.saveMeasure(data.getResource(), uncoveredLines);
     context.saveMeasure(data.getResource(), lineHits);
     DelphiUtils.LOG.debug("Saving coverage to: " + data.getResource().absolutePath());
   } catch (Exception e) {
     DelphiUtils.LOG.error("Error saving coverage measure.", e);
   }
 }
Exemplo n.º 22
0
 private void saveMeasures(File sonarFile, SourceFile squidFile) {
   context.saveMeasure(sonarFile, CoreMetrics.FILES, squidFile.getDouble(FlexMetric.FILES));
   context.saveMeasure(sonarFile, CoreMetrics.LINES, squidFile.getDouble(FlexMetric.LINES));
   context.saveMeasure(
       sonarFile, CoreMetrics.NCLOC, squidFile.getDouble(FlexMetric.LINES_OF_CODE));
   context.saveMeasure(
       sonarFile, CoreMetrics.COMMENT_LINES, squidFile.getDouble(FlexMetric.COMMENT_LINES));
   context.saveMeasure(sonarFile, CoreMetrics.CLASSES, squidFile.getDouble(FlexMetric.CLASSES));
   context.saveMeasure(
       sonarFile, CoreMetrics.FUNCTIONS, squidFile.getDouble(FlexMetric.FUNCTIONS));
   context.saveMeasure(
       sonarFile, CoreMetrics.STATEMENTS, squidFile.getDouble(FlexMetric.STATEMENTS));
   context.saveMeasure(
       sonarFile, CoreMetrics.COMPLEXITY, squidFile.getDouble(FlexMetric.COMPLEXITY));
 }
  @Test
  public void should_execute_measure_update_for_known_files() {
    InputFile source = file("source.java");
    InputFile test = file("UNKNOWN.java");
    when(conf.getThreadCount()).thenReturn(1);
    fs.add(source);
    fs.add(test);
    when(blameVersionSelector.detect(
            any(org.sonar.api.resources.File.class), eq(source), eq(context)))
        .thenReturn(measureUpdate);
    when(context.getResource(any(org.sonar.api.resources.File.class)))
        .thenReturn(file)
        .thenReturn(null);
    scmActivitySensor.analyse(project, context);

    verify(measureUpdate, only()).execute(timeMachine, context);
  }
Exemplo n.º 24
0
  private void onPackage(Resource sonarPackage) {
    Collection<Resource> squidFiles = getResourcesForDirectory(sonarPackage);
    if (squidFiles != null && !squidFiles.isEmpty()) {
      IncrementalCyclesAndFESSolver<Resource> cycleDetector =
          new IncrementalCyclesAndFESSolver<>(graph, squidFiles);
      Set<Cycle> cycles = cycleDetector.getCycles();

      MinimumFeedbackEdgeSetSolver solver = new MinimumFeedbackEdgeSetSolver(cycles);
      Set<Edge> feedbackEdges = solver.getEdges();
      int tangles = solver.getWeightOfFeedbackEdgeSet();

      savePositiveMeasure(sonarPackage, CoreMetrics.FILE_CYCLES, cycles.size());
      savePositiveMeasure(sonarPackage, CoreMetrics.FILE_FEEDBACK_EDGES, feedbackEdges.size());
      savePositiveMeasure(sonarPackage, CoreMetrics.FILE_TANGLES, tangles);
      savePositiveMeasure(sonarPackage, CoreMetrics.FILE_EDGES_WEIGHT, getEdgesWeight(squidFiles));
      String dsmJson = serializeDsm(graph, squidFiles, feedbackEdges);
      context.saveMeasure(sonarPackage, new Measure(CoreMetrics.DEPENDENCY_MATRIX, dsmJson));
    }
  }
Exemplo n.º 25
0
  public void analyse(Project project, SensorContext context) {
    DroolsPlugin.configureSourceDir(project);
    Language drools = new Drools(project);
    ProjectFileSystem fileSystem = project.getFileSystem();
    Map<String, DroolsPackage> packageMap = new HashMap<String, DroolsPackage>();
    VerifierBuilder verifierBuilder = VerifierBuilderFactory.newVerifierBuilder();
    for (File file : fileSystem.getSourceFiles(drools)) {
      Verifier verifier = verifierBuilder.newVerifier();
      try {
        DroolsFile resource = DroolsFile.fromIOFile(file, false);
        Source source = analyseSourceCode(file);
        if (source != null) {
          context.saveMeasure(
              resource, CoreMetrics.LINES, (double) source.getMeasure(Metric.LINES));
          context.saveMeasure(
              resource, CoreMetrics.NCLOC, (double) source.getMeasure(Metric.LINES_OF_CODE));
          context.saveMeasure(
              resource,
              CoreMetrics.COMMENT_LINES,
              (double) source.getMeasure(Metric.COMMENT_LINES));
        }
        context.saveMeasure(resource, CoreMetrics.FILES, 1.0);
        context.saveMeasure(
            resource,
            CoreMetrics.CLASSES,
            (double)
                (resource.getPackageDescr().getRules().size()
                    + resource.getPackageDescr().getFunctions().size()));
        packageMap.put(resource.getParent().getKey(), resource.getParent());

        verifier.addResourcesToVerify(new FileSystemResource(file), ResourceType.DRL);
        verifier.fireAnalysis();
        saveViolations(resource, context, verifier.getResult());
      } catch (Throwable e) {
        DroolsPlugin.LOG.error(
            "error while verifier analyzing '" + file.getAbsolutePath() + "'", e);
      } finally {
        verifier.dispose();
      }
    }

    for (DroolsPackage droolsPackage : packageMap.values()) {
      context.saveMeasure(droolsPackage, CoreMetrics.PACKAGES, 1.0);
    }
  }
  @Test
  public void should_convert_pmd_violation_to_sonar_violation() {
    when(projectFileSystem.getSourceDirs()).thenReturn(Arrays.asList(new File("/src")));
    when(pmdViolation.getFilename()).thenReturn("/src/source.java");
    when(pmdViolation.getBeginLine()).thenReturn(42);
    when(pmdViolation.getDescription()).thenReturn("Description");
    when(pmdViolation.getRule()).thenReturn(rule);
    when(rule.getName()).thenReturn("RULE");
    when(context.getResource(new JavaFile("[default].source")))
        .thenReturn(new JavaFile("[default].source"));
    when(ruleFinder.findByKey("pmd", "RULE")).thenReturn(sonarRule);

    PmdViolationToRuleViolation pmdViolationToRuleViolation =
        new PmdViolationToRuleViolation(projectFileSystem, ruleFinder);
    Violation violation = pmdViolationToRuleViolation.toViolation(pmdViolation, context);

    assertThat(violation)
        .is(
            reflectionEqualTo(
                Violation.create(sonarRule, new JavaFile("[default].source"))
                    .setLineId(42)
                    .setMessage("Description")));
  }
Exemplo n.º 27
0
  public void analyse(Project project, SensorContext context) {
    RulesProfileWrapper profileWrapper = (RulesProfileWrapper) profile;
    for (String languageKey : moduleLanguages.keys()) {
      RulesProfile realProfile = profileWrapper.getProfileByLanguage(languageKey);
      Measure pastProfileMeasure = getPreviousMeasure(project, CoreMetrics.PROFILE);
      if (pastProfileMeasure == null) {
        // first analysis
        return;
      }
      int pastProfileId = pastProfileMeasure.getIntValue();
      Measure pastProfileVersionMeasure = getPreviousMeasure(project, CoreMetrics.PROFILE_VERSION);
      final int pastProfileVersion;
      // first analysis with versions
      if (pastProfileVersionMeasure == null) {
        pastProfileVersion = 1;
      } else {
        pastProfileVersion = pastProfileVersionMeasure.getIntValue();
      }
      String pastProfile =
          formatProfileDescription(pastProfileMeasure.getData(), pastProfileVersion);

      int currentProfileId = realProfile.getId();
      int currentProfileVersion = realProfile.getVersion();
      String currentProfile =
          formatProfileDescription(realProfile.getName(), currentProfileVersion);

      if ((pastProfileId != currentProfileId) || (pastProfileVersion != currentProfileVersion)) {
        // A different profile is used for this project or new version of same profile
        context.createEvent(
            project,
            currentProfile,
            currentProfile + " is used instead of " + pastProfile,
            Event.CATEGORY_PROFILE,
            null);
      }
    }
  }
  public void saveMeasures(final Map<String, List<Measure>> measures) {

    if (measures == null) {
      return;
    }

    for (Map.Entry<String, List<Measure>> entry : measures.entrySet()) {
      final org.sonar.api.resources.File objcfile =
          org.sonar.api.resources.File.fromIOFile(
              new File(project.getFileSystem().getBasedir(), entry.getKey()), project);
      if (fileExists(sensorContext, objcfile)) {
        for (Measure measure : entry.getValue()) {
          try {
            LoggerFactory.getLogger(getClass())
                .debug("Save measure {} for file {}", measure.getMetric().getName(), objcfile);
            sensorContext.saveMeasure(objcfile, measure);
          } catch (Exception e) {
            LoggerFactory.getLogger(getClass())
                .error(" Exception -> {} -> {}", entry.getKey(), measure.getMetric().getName());
          }
        }
      }
    }
  }
Exemplo n.º 29
0
 private void saveMetricOnFile(Metric metric, double value) {
   sensorContext.saveMeasure(sonarFile, new Measure(metric, value));
 }
 private void saveMeasure(SensorContext context, Measure measure) {
   context.saveMeasure(resource, measure.setPersistenceMode(PersistenceMode.DATABASE));
 }