org.sonar.squidbridge.indexer.QueryByType Java Examples

The following examples show how to use org.sonar.squidbridge.indexer.QueryByType. 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: NodeAstScanner.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Helper method for testing checks without having to deploy them on a Sonar instance.
 */
public static SourceFile scanSingleFile(File file, Collection<FlowCheck> nodeChecks,
    List<SquidAstVisitor<Grammar>> metrics) {
  if (!file.isFile()) {
    throw new IllegalArgumentException("File '" + file + "' not found.");
  }

  AstScanner<Grammar> scanner = create(new FlowConfiguration(Charsets.UTF_8), nodeChecks,
      metrics);
  scanner.scanFile(file);
  Collection<SourceCode> sources = scanner.getIndex().search(new QueryByType(SourceFile.class));
  if (sources.size() != 1) {
    throw new IllegalStateException(
        "Only one SourceFile was expected whereas " + sources.size() + " has been returned.");
  }
  return (SourceFile) sources.iterator().next();
}
 
Example #2
Source File: LuaSquidSensor.java    From sonar-lua with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void execute(SensorContext context) {
  FileSystem fileSystem = context.fileSystem();
  FilePredicates predicates = fileSystem.predicates();
  List<SquidAstVisitor<LexerlessGrammar>> visitors = new ArrayList<>(checks.all());
  visitors.add(new FileLinesVisitor(fileLinesContextFactory, fileSystem));
  LuaConfiguration configuration = new LuaConfiguration(fileSystem.encoding());

  scanner = LuaAstScanner.create(configuration, visitors);

  Iterable<java.io.File> files = fileSystem.files(
    predicates.and(
      predicates.hasType(InputFile.Type.MAIN),
      predicates.hasLanguage(Lua.KEY),
      inputFile -> !inputFile.absolutePath().endsWith("mxml")
    ));
  scanner.scanFiles(ImmutableList.copyOf(files));

  Collection<SourceCode> squidSourceFiles = scanner.getIndex().search(new QueryByType(SourceFile.class));
  save(context, squidSourceFiles);
}
 
Example #3
Source File: ApexSquidSensor.java    From enforce-sonarqube-plugin with MIT License 5 votes vote down vote up
/**
 * Analyzes files for a given project.
 *
 * @param project current project.
 * @param context sensor context.
 */
@Override
public void analyse(Project project, SensorContext context) {
    this.context = context;

    List<SquidAstVisitor<Grammar>> visitors = Lists.newArrayList(checks.all());
    scanner = ApexAstScanner.create(createConfiguration(),
            visitors.toArray(new SquidAstVisitor[visitors.size()]));
    scanner.scanFiles(Lists.newArrayList(fileSystem.files(filePredicate)));

    Collection<SourceCode> squidSourceFiles = scanner.getIndex()
            .search(new QueryByType(SourceFile.class));
    save(squidSourceFiles);
}
 
Example #4
Source File: ApexSquidSensor.java    From enforce-sonarqube-plugin with MIT License 5 votes vote down vote up
/**
 * Saves a measure with the limits of the function.
 *
 * @param sonarFile input file.
 * @param squidFile source file.
 */
private void saveFunctionsComplexityDistribution(InputFile 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);
    squidFunctionsInFile.forEach(squidFunction ->
        complexityDistribution.add(squidFunction.getDouble(ApexMetric.COMPLEXITY))
    );
    context.saveMeasure(sonarFile, buildMeasure(complexityDistribution));
}
 
Example #5
Source File: ApexAstScanner.java    From enforce-sonarqube-plugin with MIT License 5 votes vote down vote up
/**
 * Returns a source file from file and visitors.
 *
 * @param file source file.
 * @param visitors list of visitors.
 * @return a source.
 * @exception IllegalArgumentException when file is not found.
 * @exception IllegalStateException when there is more than one sourceFile.
 */
public static SourceFile scanFile(File file, SquidAstVisitor<Grammar>... visitors) {
    if (!file.isFile()) {
        throw new IllegalArgumentException(String.format(FILE_NOT_FOUND, file));
    }
    AstScanner<Grammar> scanner = create(new ApexConfiguration(Charsets.UTF_8), visitors);
    scanner.scanFile(file);
    Collection<SourceCode> sources = scanner.getIndex().search(new QueryByType(SourceFile.class));
    if (sources.size() != 1) {
        throw new IllegalStateException(String.format(ONE_SOURCE_FILE, sources.size()));
    }
    return (SourceFile) sources.iterator().next();
}
 
Example #6
Source File: FlowAstScanner.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Helper method for testing checks without having to deploy them on a Sonar instance.
 */
public static SourceFile scanSingleFile(File file, List<FlowCheck> flowChecks,
    List<SquidAstVisitor<Grammar>> metrics) {
  if (!file.isFile()) {
    throw new IllegalArgumentException("File '" + file + "' not found.");
  }

  AstScanner<Grammar> scanner = create(new FlowConfiguration(Charsets.UTF_8), flowChecks,
      metrics);
  scanner.scanFile(file);
  Collection<SourceCode> sources = scanner.getIndex().search(new QueryByType(SourceFile.class));
  if (sources.size() != 1) {
    throw new IllegalStateException(
        "Only one SourceFile was expected whereas " + sources.size() + " has been returned.");
  }
  for (SourceCode squidSourceFile : sources) {
    logger.debug("+++Checking Dependencies +++");
    @SuppressWarnings("unchecked")
    ArrayList<String> dependencies = (ArrayList<String>) squidSourceFile
        .getData(FlowMetric.DEPENDENCIES);
    if (dependencies != null) {
      for (String dependency : dependencies) {
        logger.debug("+++Dependency: " + dependency);
      }
    }
  }
  return (SourceFile) sources.iterator().next();
}
 
Example #7
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 #8
Source File: FlowSquidSensor.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
private void getInterfaceFiles(Collection<SourceCode> squidSourceFiles, SensorContext context) {
  // Scan node.ndf files
  AstScanner<Grammar> scanner = NodeAstScanner.create(createConfiguration(), nodeChecks.all(),
      null);
  logger.debug("Scanning Interface Files with " + nodeChecks.all().size() + " checks active");
  FileSystem fs = context.fileSystem();
  Iterable<InputFile> nodeFiles = fs
      .inputFiles(fs.predicates().matchesPathPatterns(FlowLanguage.getNodeFilePatterns()));
  try {
    ArrayList<File> files = new ArrayList<File>();
    nodeFiles.forEach(file -> files.add(file.file()));
    scanner.scanFiles(files);
  } catch (Exception e) {
    if (config.getBoolean(FlowLanguageProperties.FAIL_ON_SCANERROR).get()) {
      throw e;
    } else {
      logger.error("** * Exception while scanning file, skipping.", e);
    }
  }
  Collection<SourceCode> nodeSources = scanner.getIndex()
      .search(new QueryByType(SourceFile.class));
  logger.debug("*NODE* nodes found:" + nodeSources.size() + " *");
  for (SourceCode squidSourceFile : squidSourceFiles) {
    for (SourceCode nodeSource : nodeSources) {
      if ((new File(nodeSource.getKey())).getParent()
          .equals((new File(squidSourceFile.getKey())).getParent())) {
        squidSourceFile.addChild(nodeSource);
        String relativePath = pathResolver.relativePath(fileSystem.baseDir(),
            new java.io.File(nodeSource.getKey()));
        InputFile inputFile = fileSystem
            .inputFile(fileSystem.predicates().hasRelativePath(relativePath));
        saveViolations(context, inputFile, (SourceFile) nodeSource);
      }

    }
  }
}
 
Example #9
Source File: FlowSquidSensor.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void saveClassComplexity(SensorContext context, AstScanner<Grammar> flowScanner,
    InputFile inputFile, SourceFile squidFile) {
  Collection<SourceCode> classes = flowScanner.getIndex().search(new QueryByParent(squidFile),
      new QueryByType(SourceClass.class));
  Integer complexityInClasses = 0;
  for (SourceCode squidClass : classes) {
    int classComplexity = squidClass.getInt(FlowMetric.INVOKES);
    complexityInClasses += classComplexity;
  }
  context.<Integer>newMeasure().on(inputFile).forMetric(CoreMetrics.COMPLEXITY_IN_CLASSES)
      .withValue(complexityInClasses).save();
}
 
Example #10
Source File: LuaAstScanner.java    From sonar-lua with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Helper method for testing checks without having to deploy them on a Sonar instance.
 */
public static SourceFile scanSingleFile(File file, SquidAstVisitor<LexerlessGrammar>... visitors) {
  if (!file.isFile()) {
    throw new IllegalArgumentException("File '" + file + "' not found.");
  }

  AstScanner<LexerlessGrammar> scanner = create(new LuaConfiguration(Charsets.UTF_8), Arrays.asList(visitors));
  scanner.scanFile(file);
  Collection<SourceCode> sources = scanner.getIndex().search(new QueryByType(SourceFile.class));
  if (sources.size() != 1) {
    throw new IllegalStateException("Only one SourceFile was expected whereas " + sources.size() + " has been returned.");
  }
  return (SourceFile) sources.iterator().next();
}
 
Example #11
Source File: LuaAstScannerTest.java    From sonar-lua with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void files() {
  AstScanner<LexerlessGrammar> scanner = LuaAstScanner.create(new LuaConfiguration(Charsets.UTF_8), Collections.emptyList());
  scanner.scanFiles(ImmutableList.of(new File("src/test/resources/metrics/comments.lua"),
    new File("src/test/resources/metrics/lines.lua")));
  SourceProject project = (SourceProject) scanner.getIndex().search(new QueryByType(SourceProject.class)).iterator().next();
  assertThat(project.getInt(LuaMetric.FILES)).isEqualTo(2);
}
 
Example #12
Source File: LuaSquidSensor.java    From sonar-lua with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void saveClassComplexity(SensorContext context, InputFile inputFile, SourceFile squidFile) {
  Collection<SourceCode> classes = scanner.getIndex().search(new QueryByParent(squidFile), new QueryByType(SourceClass.class));
  int complexityInClasses = 0;
  for (SourceCode squidClass : classes) {
    int classComplexity = squidClass.getInt(LuaMetric.COMPLEXITY);
    complexityInClasses += classComplexity;
  }
  context.<Integer>newMeasure()
    .on(inputFile)
    .forMetric(CoreMetrics.COMPLEXITY_IN_CLASSES)
    .withValue(complexityInClasses)
    .save();
}
 
Example #13
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();
}
 
Example #14
Source File: ApexAstScannerTest.java    From enforce-sonarqube-plugin with MIT License 4 votes vote down vote up
private SourceProject buildProject(AstScanner<Grammar> scanner) {
    return (SourceProject) scanner.getIndex().search(new QueryByType(SourceProject.class)).iterator().next();
}