Java Code Examples for org.sonar.api.batch.fs.InputFile

The following examples show how to use org.sonar.api.batch.fs.InputFile. 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
Source Project: sonar-p3c-pmd   Source File: PmdViolationRecorder.java    License: MIT License 6 votes vote down vote up
public void saveViolation(RuleViolation pmdViolation) {
  InputFile inputFile = findResourceFor(pmdViolation);
  if (inputFile == null) {
    // Save violations only for existing resources
    return;
  }

  Issuable issuable = perspectives.as(Issuable.class, inputFile);

  Rule rule = findRuleFor(pmdViolation);
  if (issuable == null || rule == null) {
    // Save violations only for enabled rules
    return;
  }

  IssueBuilder issueBuilder = issuable.newIssueBuilder()
    .ruleKey(rule.ruleKey())
    .message(pmdViolation.getDescription())
    .line(pmdViolation.getBeginLine());
  issuable.addIssue(issueBuilder.build());
}
 
Example 2
private void addHighlighting(final NewHighlighting newHighlightning, final Token token, final InputFile file,
		final TextRange range) {
	try {
		if (token.getType() == TSqlParser.COMMENT || token.getType() == TSqlParser.LINE_COMMENT) {
			newHighlightning.highlight(range, TypeOfText.COMMENT);
		}

		if (token.getType() == TSqlParser.STRING) {
			newHighlightning.highlight(range, TypeOfText.STRING);
		}

		if (this.keywordsProvider.isKeyword(TSqlParser.VOCABULARY.getSymbolicName(token.getType()))) {
			newHighlightning.highlight(range, TypeOfText.KEYWORD);
		}
	} catch (final Throwable e) {
		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug(format("Unexpected error adding highlighting on file %s", file.absolutePath()), e);
		}
	}
}
 
Example 3
Source Project: sonar-p3c-pmd   Source File: PmdExecutorTest.java    License: MIT License 6 votes vote down vote up
@Test
public void should_execute_pmd_on_source_files_and_test_files() throws Exception {
  InputFile srcFile = file("src/Class.java", Type.MAIN);
  InputFile tstFile = file("test/ClassTest.java", Type.TEST);
  setupPmdRuleSet(PmdConstants.REPOSITORY_KEY, "simple.xml");
  setupPmdRuleSet(PmdConstants.TEST_REPOSITORY_KEY, "junit.xml");
  fileSystem.add(srcFile);
  fileSystem.add(tstFile);

  Report report = pmdExecutor.execute();

  assertThat(report).isNotNull();

  // setting java source version to the default value
  settings.removeProperty(PmdConstants.JAVA_SOURCE_VERSION);
  report = pmdExecutor.execute();

  assertThat(report).isNotNull();
}
 
Example 4
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 5
Source Project: sonar-esql-plugin   Source File: TraceSensorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void init() throws FileNotFoundException {
	settings = new MapSettings();
	settings.setProperty("sonar.esql.trace.reportPaths", "TraceSensorTest/trace.txt");
	context = SensorContextTester.create(moduleBaseDir);
	context.setSettings(settings);

	InputFile inputFile1 = inputFile("file1.esql", Type.MAIN);
	InputFile inputFile2 = inputFile("file2.esql", Type.MAIN);
	InputFile inputFile3 = inputFile("file3.esql", Type.MAIN);
	// inputFile("tests/file1.esql", Type.TEST);

	linesOfCode = new HashMap<>();
	linesOfCode.put(inputFile1, ImmutableSet.of(1, 2, 3, 4));
	linesOfCode.put(inputFile2, null);
	linesOfCode.put(inputFile3, ImmutableSet.of(1, 2, 3, 4));

	sensor = new TraceSensor();

}
 
Example 6
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 7
Source Project: sonar-clojure   Source File: AbstractSensor.java    License: MIT License 6 votes vote down vote up
protected void saveIssue(Issue issue, SensorContext context) {
    try {
        Optional<InputFile> fileOptional = getFile(issue.getFilePath(), context.fileSystem());

        if (fileOptional.isPresent()) {
            InputFile file = fileOptional.get();
            RuleKey ruleKey = RuleKey.of(ClojureLintRulesDefinition.REPOSITORY_KEY, issue.getExternalRuleId().trim());

            NewIssue newIssue = context.newIssue().forRule(ruleKey);

            NewIssueLocation primaryLocation = newIssue
                    .newLocation()
                    .on(file)
                    .message(issue.getDescription().trim());

            primaryLocation.at(file.selectLine(issue.getLine()));

            newIssue.at(primaryLocation);
            newIssue.save();
        } else {
            LOG.warn("Not able to find a file with path '{}'", issue.getFilePath());
        }
    } catch (Exception e) {
        LOG.error("Can not save the issue due to: " + e.getMessage());
    }
}
 
Example 8
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 9
Source Project: sonar-ansible   Source File: AbstractAnsibleSensor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Saves the found issues in SonarQube
 *
 * @param context the context
 * @param inputFile the file where the issue was found
 * @param line the line where the issue was found
 * @param ruleId the Id of the rule that raised the issue
 * @param message a message describing the issue
 */
protected void saveIssue(SensorContext context, InputFile inputFile, int line, String ruleId, String message) {
    RuleKey ruleKey = getRuleKey(context, ruleId);

    // Old rules (ansible-lint < 3.5) had id ANSIBLE... but now it is E... so we may need to add the heading E back
    if (ruleKey == null) {
        ruleKey = getRuleKey(context, "E" + ruleId);
    }

    if (ruleKey == null) {
        LOGGER.debug("Rule " + ruleId + " ignored, not found in repository");
        return;
    }

    NewIssue newIssue = context.newIssue().forRule(ruleKey);
    NewIssueLocation location = newIssue.newLocation()
            .on(inputFile)
            .message(message)
            .at(inputFile.selectLine(line));
    newIssue.at(location).save();
    LOGGER.debug("Issue {} saved for {}", ruleId, inputFile.filename());
}
 
Example 10
Source Project: sonar-ansible   Source File: AbstractAnsibleSensorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteWithAnsibleLintErrorOutput() throws IOException {
    InputFile playbook1 = Utils.getInputFile("playbooks/playbook1.yml");
    InputFile playbook2 = Utils.getInputFile("playbooks/playbook2.yml");
    InputFile playbook3 = Utils.getInputFile("playbooks/playbook3.yml");
    context.fileSystem().add(playbook1).add(playbook2).add(playbook3);

    if (System.getProperty("os.name").toLowerCase().contains("windows")) {
        context.settings().appendProperty(AnsibleSettings.ANSIBLE_LINT_PATH_KEY,
                new File(getClass().getResource("/scripts/ansible-lint2.cmd").getFile()).getAbsolutePath());
    } else {
        String path = new File(getClass().getResource("/scripts/ansible-lint2.sh").getFile()).getAbsolutePath();
        context.settings().appendProperty(AnsibleSettings.ANSIBLE_LINT_PATH_KEY, path);
        setShellRights(path);
    }

    sensor.executeWithAnsibleLint(context, null);
    assertEquals(3, sensor.scannedFiles.size());
    assertTrue(sensor.scannedFiles.contains(playbook1));
    assertTrue(sensor.scannedFiles.contains(playbook2));
    assertTrue(sensor.scannedFiles.contains(playbook3));
    assertEquals(0, context.allIssues().size());

    assertEquals(3, logTester.logs(LoggerLevel.WARN).size());
    logTester.logs(LoggerLevel.WARN).stream().forEach(log -> assertTrue(log.startsWith("Errors happened during analysis:")));
}
 
Example 11
Source Project: sonar-ansible   Source File: AbstractAnsibleSensorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteWithAnsibleLintIOException() throws IOException, InterruptedException {
    InputFile playbook1 = Utils.getInputFile("playbooks/playbook1.yml");
    InputFile playbook2 = Utils.getInputFile("playbooks/playbook2.yml");
    InputFile playbook3 = Utils.getInputFile("playbooks/playbook3.yml");
    context.fileSystem().add(playbook1).add(playbook2).add(playbook3);

    MySensor theSensor = spy(sensor);
    doThrow(new IOException("Boom!")).when(theSensor).executeCommand(any(), any(), any());

    theSensor.executeWithAnsibleLint(context, Arrays.asList("foo", "bar"));
    assertEquals(1, theSensor.scannedFiles.size());
    assertTrue(theSensor.scannedFiles.contains(playbook1));

    Collection<Issue> issues = context.allIssues();
    assertEquals(0, issues.size());
}
 
Example 12
Source Project: sonar-ansible   Source File: AbstractAnsibleSensorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteWithAnsibleLintWinthConf() throws IOException {
    InputFile playbook1 = Utils.getInputFile("playbooks/playbook1.yml");
    context.fileSystem().add(playbook1);

    if (System.getProperty("os.name").toLowerCase().contains("windows")) {
        context.settings().appendProperty(AnsibleSettings.ANSIBLE_LINT_PATH_KEY,
                new File(getClass().getResource("/scripts/echo_as_issue.cmd").getFile()).getAbsolutePath());
    } else {
        String path = new File(getClass().getResource("/scripts/echo_as_issue.sh").getFile()).getAbsolutePath();
        context.settings().appendProperty(AnsibleSettings.ANSIBLE_LINT_PATH_KEY, path);
        setShellRights(path);
    }

    context.settings().appendProperty(AnsibleSettings.ANSIBLE_LINT_CONF_PATH_KEY, "/path/to/ansible-lint.conf");

    sensor.executeWithAnsibleLint(context, null);
    Collection<Issue> issues = context.allIssues();
    assertEquals(1, issues.size());
    assertTrue(issueExists(issues, ruleKey1, playbook1, 2, "-p --nocolor -c /path/to/ansible-lint\\.conf " + Pattern.quote(new File(playbook1.uri()).getAbsolutePath())));
}
 
Example 13
Source Project: sonar-esql-plugin   Source File: EsqlCheckVerifier.java    License: Apache License 2.0 6 votes vote down vote up
static void verify(EsqlCheck check, InputFile file) {
	EsqlVisitorContext context = TestUtils.createContext(file);

	List<TestIssue> expectedIssues = ExpectedIssuesParser.parseExpectedIssues(context);
	Iterator<Issue> actualIssues = getActualIssues(check, context);

	for (TestIssue expected : expectedIssues) {
		if (actualIssues.hasNext()) {
			verifyIssue(expected, actualIssues.next());
		} else {
			throw new AssertionError("Missing issue at line " + expected.line());
		}
	}

	if (actualIssues.hasNext()) {
		Issue issue = actualIssues.next();
		throw new AssertionError("Unexpected issue at line " + line(issue) + ": \"" + message(issue) + "\"");
	}
}
 
Example 14
Source Project: sonar-ansible   Source File: AbstractAnsibleSensorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void init() throws Exception {
    context = Utils.getSensorContext();

    DefaultFileSystem fs = Utils.getFileSystem();
    fs.setWorkDir(temporaryFolder.newFolder("temp").toPath());
    context.setFileSystem(fs);

    ActiveRules activeRules = new ActiveRulesBuilder()
            .create(ruleKey1)
            .activate()
            .create(ruleKey2)
            .activate()
            .create(ruleKey3)
            .activate()
            .build();
    context.setActiveRules(activeRules);

    FileLinesContextFactory fileLinesContextFactory = mock(FileLinesContextFactory.class);
    when(fileLinesContextFactory.createFor(any(InputFile.class))).thenReturn(mock(FileLinesContext.class));

    sensor = new MySensor(fs);
}
 
Example 15
@Test
public void testNoActiveRule() throws IOException {
    SensorContextTester context = Utils.getSensorContext();

    DefaultFileSystem fs = Utils.getFileSystem();
    fs.setWorkDir(temporaryFolder.newFolder("temp").toPath());
    context.setFileSystem(fs);

    FileLinesContextFactory fileLinesContextFactory = mock(FileLinesContextFactory.class);
    when(fileLinesContextFactory.createFor(any(InputFile.class))).thenReturn(mock(FileLinesContext.class));

    InputFile playbook1 = Utils.getInputFile("playbooks/playbook1.yml");
    InputFile playbook2 = Utils.getInputFile("playbooks/playbook2.yml");
    InputFile playbook3 = Utils.getInputFile("playbooks/playbook3.yml");
    context.fileSystem().add(playbook1).add(playbook2).add(playbook3);

    MySensor sensor = new MySensor(fs);

    sensor.executeWithAnsibleLint(context, null);
    assertEquals(1, logTester.logs(LoggerLevel.INFO).size());
    assertEquals("No active rules found for this plugin, skipping.", logTester.logs(LoggerLevel.INFO).get(0));
    assertEquals(0, context.allIssues().size());
}
 
Example 16
Source Project: sonar-ansible   Source File: AnsibleExtraSensorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void init() throws Exception {
    context = Utils.getSensorContext();

    DefaultFileSystem fs = Utils.getFileSystem();
    fs.setWorkDir(temporaryFolder.newFolder("temp").toPath());
    context.setFileSystem(fs);

    ActiveRules activeRules = new ActiveRulesBuilder()
            .create(ruleKey1)
            .activate()
            .create(ruleKey2)
            .activate()
            .build();
    context.setActiveRules(activeRules);

    FileLinesContextFactory fileLinesContextFactory = mock(FileLinesContextFactory.class);
    when(fileLinesContextFactory.createFor(any(InputFile.class))).thenReturn(mock(FileLinesContext.class));

    sensor = new AnsibleExtraSensor(context.fileSystem());
}
 
Example 17
Source Project: sonar-esql-plugin   Source File: EsqlSensor.java    License: Apache License 2.0 6 votes vote down vote up
private static void savePreciseIssue(SensorContext sensorContext, InputFile inputFile, RuleKey ruleKey, PreciseIssue issue) {
    NewIssue newIssue = sensorContext.newIssue();

    newIssue
            .forRule(ruleKey)
            .at(newLocation(inputFile, newIssue, issue.primaryLocation()));

    if (issue.cost() != null) {
        newIssue.gap(issue.cost());
    }

    for (IssueLocation secondary : issue.secondaryLocations()) {
        newIssue.addLocation(newLocation(inputFile, newIssue, secondary));
    }
    newIssue.save();
}
 
Example 18
@Before
public void setUp() throws IOException {
  DefaultFileSystem fileSystem = new DefaultFileSystem(tempFolder.getRoot());
  fileSystem.setEncoding(Charsets.UTF_8);
  file = tempFolder.newFile();
  inputFile = new DefaultInputFile("moduleKey", file.getName())
    .setLanguage("css")
    .setType(InputFile.Type.MAIN);
  fileSystem.add(inputFile);

  sensorContext = SensorContextTester.create(tempFolder.getRoot());
  sensorContext.setFileSystem(fileSystem);

  visitorContext = mock(TreeVisitorContext.class);
  highlighterVisitor = new CssSyntaxHighlighterVisitor(sensorContext);
  when(visitorContext.getFile()).thenReturn(file);
}
 
Example 19
Source Project: AEM-Rules-for-SonarQube   Source File: HtlFilesAnalyzer.java    License: Apache License 2.0 6 votes vote down vote up
public void analyseFiles(SensorContext context, 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");
            }
            analyse(context, inputFile);
            progressReport.nextFile();
        }
        success = true;
    } catch (CancellationException e) {
        // do not propagate the exception
        LOGGER.debug(e.toString());
    } finally {
        stopProgressReport(progressReport, success);
    }
}
 
Example 20
private void setUp(String fileName) {
  File moduleBaseDir = new File("src/test/resources/metrics/");
  context = SensorContextTester.create(moduleBaseDir);

  DefaultInputFile inputFile = new DefaultInputFile("moduleKey", fileName)
    .setModuleBaseDir(moduleBaseDir.toPath())
    .setLanguage("less")
    .setType(InputFile.Type.MAIN);

  context.fileSystem().add(inputFile);
  context.fileSystem().setEncoding(Charsets.UTF_8);

  LessMetricsVisitor metricsVisitor = new LessMetricsVisitor(context, mock(NoSonarFilter.class));

  TreeVisitorContext treeVisitorContext = mock(TreeVisitorContext.class);
  when(treeVisitorContext.getFile()).thenReturn(inputFile.file());
  when(treeVisitorContext.getTopTree()).thenReturn(LessParser.createParser(Charsets.UTF_8).parse(inputFile.file()));

  metricsVisitor.scanTree(treeVisitorContext);
}
 
Example 21
private void savePreciseIssue(PreciseIssue issue) {
  NewIssue newIssue = sensorContext.newIssue();
  InputFile primaryFile = Preconditions.checkNotNull(fileSystem.inputFile(fileSystem.predicates().is(issue.primaryLocation().file())));

  newIssue
    .forRule(ruleKey(issue.check()))
    .at(newLocation(primaryFile, newIssue, issue.primaryLocation()));

  if (issue.cost() != null) {
    newIssue.gap(issue.cost());
  }

  InputFile secondaryFile;
  for (IssueLocation secondary : issue.secondaryLocations()) {
    secondaryFile = fileSystem.inputFile(fileSystem.predicates().is(secondary.file()));
    if (secondaryFile == null) {
      secondaryFile = primaryFile;
    }
    newIssue.addLocation(newLocation(secondaryFile, newIssue, secondary));
  }

  newIssue.save();
}
 
Example 22
@Before
public void setUp() throws IOException {
  DefaultFileSystem fileSystem = new DefaultFileSystem(tempFolder.getRoot());
  fileSystem.setEncoding(Charsets.UTF_8);
  file = tempFolder.newFile();
  inputFile = new DefaultInputFile("moduleKey", file.getName())
    .setLanguage("css")
    .setType(InputFile.Type.MAIN);
  fileSystem.add(inputFile);

  sensorContext = SensorContextTester.create(tempFolder.getRoot());
  sensorContext.setFileSystem(fileSystem);

  visitorContext = mock(TreeVisitorContext.class);
  cpdVisitor = new CpdVisitor(sensorContext);
  when(visitorContext.getFile()).thenReturn(file);
}
 
Example 23
Source Project: SonarTsPlugin   Source File: TsCoverageSensorImplTest.java    License: MIT License 6 votes vote down vote up
@Test
public void usesNonCommentLinesSetForLinesToCoverMetrics_IfSettingZeroCoverage() {
    Map<InputFile, Set<Integer>> nonCommentLineNumbersByFile = new HashMap<InputFile, Set<Integer>>();
    HashSet<Integer> nonCommentLineNumbers = new HashSet<Integer>();
    nonCommentLineNumbers.add(1);
    nonCommentLineNumbers.add(3);
    nonCommentLineNumbers.add(5);
    
    nonCommentLineNumbersByFile.put(this.file, nonCommentLineNumbers);
    
    this.sensor.execute(this.context, nonCommentLineNumbersByFile);

    // Expect lines 1, 3 and 5 to have zero coverage...
    assertEquals((Integer) 0, this.context.lineHits(this.file.key(), CoverageType.UNIT, 1));
    assertEquals((Integer) 0, this.context.lineHits(this.file.key(), CoverageType.UNIT, 3));
    assertEquals((Integer) 0, this.context.lineHits(this.file.key(), CoverageType.UNIT, 5));
 
    // and lines 2 and 5 to not have any coverage since they're not counted as code
    // according to our supplied map
    assertNull(this.context.lineHits(this.file.key(), CoverageType.UNIT, 2));
    assertNull(this.context.lineHits(this.file.key(), CoverageType.UNIT, 4));
}
 
Example 24
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 25
private void saveViolations(SensorContext context, InputFile inputFile, SourceFile squidFile) {
  Collection<CheckMessage> messages = squidFile.getCheckMessages();
  if (messages != null) {

    for (CheckMessage message : messages) {
      RuleKey ruleKey = checks.ruleKey((SquidCheck<LexerlessGrammar>) message.getCheck());
      NewIssue newIssue = context.newIssue()
        .forRule(ruleKey)
        .gap(message.getCost());
      Integer line = message.getLine();
      NewIssueLocation location = newIssue.newLocation()
        .on(inputFile)
        .message(message.getText(Locale.ENGLISH));
      if (line != null) {
        location.at(inputFile.selectLine(line));
      }
      newIssue.at(location);
      newIssue.save();
    }
  }
}
 
Example 26
private void saveViolations(SensorContext context, InputFile inputFile, SourceFile squidFile) {
  Collection<CheckMessage> messages = squidFile.getCheckMessages();
  logger.debug("+++Nr of violations found: " + messages.size());
  if (messages != null) {
    for (CheckMessage message : messages) {
      Object c = message.getCheck();
      if (c instanceof FlowCheck) {
        FlowCheck fc = (FlowCheck) c;
        if (squidFile.getInt(FlowMetric.IS_TOP_LEVEL) != 1 && fc.isTopLevelCheck()) {
          logger.debug("+++Ignoring toplevelCheck for file: " + squidFile.getKey());
        } else {
          RuleKey ruleKey;
          if (fc.isNodeCheck()) {
            ruleKey = nodeChecks.ruleKey(fc);
          } else {
            ruleKey = flowChecks.ruleKey(fc);
          }
          FlowIssue.create(context, ruleKey, message.getCost())
              .setPrimaryLocation(inputFile, message).save();
        }
      }
    }
  }
}
 
Example 27
public static AntlrContext createRequestFromStream(final InputFile file, final Charset encoding,
		final CharStream mainStream, InputStream fileInputStream) {
	final SourceLinesProvider linesProvider = new SourceLinesProvider();
	final CharStream charStream = new CaseChangingCharStream(mainStream, true);
	final TSqlLexer lexer = new TSqlLexer(charStream);

	lexer.removeErrorListeners();

	final CommonTokenStream stream = new CommonTokenStream(lexer);

	stream.fill();
	final TSqlParser parser = new TSqlParser(stream);
	parser.removeErrorListeners();
	final ParseTree root = parser.tsql_file();
	final AntlrContext antrlFile = new AntlrContext(file, stream, root,
			linesProvider.getLines(fileInputStream, encoding));
	return antrlFile;
}
 
Example 28
Source Project: sonar-p3c-pmd   Source File: PmdExecutorTest.java    License: MIT License 5 votes vote down vote up
@Test
public void should_dump_ruleset_as_xml() throws Exception {
  InputFile srcFile = file("src/Class.java", Type.MAIN);
  InputFile tstFile = file("test/ClassTest.java", Type.TEST);
  setupPmdRuleSet(PmdConstants.REPOSITORY_KEY, "simple.xml");
  setupPmdRuleSet(PmdConstants.TEST_REPOSITORY_KEY, "junit.xml");
  fileSystem.add(srcFile);
  fileSystem.add(tstFile);

  pmdExecutor.execute();

  verify(pmdConfiguration).dumpXmlRuleSet(PmdConstants.REPOSITORY_KEY, PmdTestUtils.getResourceContent("/org/sonar/plugins/pmd/simple.xml"));
  verify(pmdConfiguration).dumpXmlRuleSet(PmdConstants.TEST_REPOSITORY_KEY, PmdTestUtils.getResourceContent("/org/sonar/plugins/pmd/junit.xml"));
}
 
Example 29
Source Project: sonar-p3c-pmd   Source File: PmdExecutorTest.java    License: MIT License 5 votes vote down vote up
@Test
public void should_ignore_empty_test_dir() throws Exception {
  InputFile srcFile = file("src/Class.java", Type.MAIN);
  doReturn(pmdTemplate).when(pmdExecutor).createPmdTemplate(any(URLClassLoader.class));
  setupPmdRuleSet(PmdConstants.REPOSITORY_KEY, "simple.xml");
  fileSystem.add(srcFile);

  pmdExecutor.execute();

  verify(pmdTemplate).process(eq(srcFile.file()), any(RuleSets.class), any(RuleContext.class));
  verifyNoMoreInteractions(pmdTemplate);
}
 
Example 30
Source Project: sonar-esql-plugin   Source File: TreeCheckTest.java    License: Apache License 2.0 5 votes vote down vote up
public static Collection<CheckMessage> getIssues(String relativePath, EsqlCheck check) {
InputFile file =  TestUtils.createTestInputFile(relativePath);

   EsqlVisitorContext context = TestUtils.createContext(file);
   List<Issue> issues = check.scanFile(context);

   return getCheckMessages(issues);
 }