Helper method for scanning a single file

@param file is the file to be checked
@param cxxConfig the plugin configuration
@param visitors AST checks and visitors to use
@param language for sensor
@return file checked with measures and issues
190021
public static SourceFile scanSingleFileConfig(CxxLanguage language, InputFile file, CxxConfiguration cxxConfig,
    SquidAstVisitor<Grammar>... visitors) {
    if (!file.isFile()) {
      throw new IllegalArgumentException("File '" + file + "' not found.");
    }
    AstScanner<Grammar> scanner = create(language, cxxConfig, visitors);
    scanner.scanFile(file.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();
  }
1177118
public static Document readDocument( File file) throws SAXException, IOException {
		InputStream in = new FileInputStream( file);
		Document result = readDocument( in);
		in.close();
		return result;
	}
15132
private Document parse(File file) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            builder.setEntityResolver(new EntityResolver() {
                @Override
                public InputSource resolveEntity(String publicId, String systemId)
                        throws SAXException, IOException {
                    return new InputSource(new StringReader(""));
                }
            });

            return builder.parse(file);
        } catch (Exception e) {
            throw new TestException(e);
        }
    }
200896
public Verifier newVerifier(File file)
		throws VerifierConfigurationException, SAXException, IOException {

		return compileSchema(file).newVerifier();
    }
278362
private ChmEntry findEntry(String file) {
        for (ChmEntry entry : entries) {
            if (file.equals(entry.getSourcePath())) {
                return entry;
            }
        }

        return null;
    }
351733
public Config parse(File file, Config... overrides) throws IOException {
    if (file == null || file.getPath().trim().length() == 0) {
      throw new MorphlineCompilationException("Missing morphlineFile parameter", null);
    }
    if (!file.exists()) {
      throw new FileNotFoundException("File not found: " + file);
    }
    if (!file.canRead()) {
      throw new IOException("Insufficient permissions to read file: " + file);
    }
    Config config = ConfigFactory.parseFile(file);
    for (Config override : overrides) {
      config = override.withFallback(config);
    }
    
    synchronized (LOCK) {
      ConfigFactory.invalidateCaches();
      config = ConfigFactory.load(config);
      config.checkValid(ConfigFactory.defaultReference()); // eagerly validate aspects of tree config
    }
    return config;
  }
1131898
protected static void visit(VirtualFile file, VirtualFileVisitor visitor) throws IOException {
        if (file == null) {
            throw VFSMessages.MESSAGES.nullArgument("file");
        }
        visitor.visit(file);
    }
865201
public static void watchFile(String file, SimpleHutoolWatcher watcher, boolean shouldFirstExecute) {
        if (shouldFirstExecute) {
            watcher.doSomething();
        }
        SimpleWatcher simpleWatcher = new SimpleWatcher() {
            @Override
            public void onModify(WatchEvent<?> event, Path currentPath) {
                watcher.onModify(event, currentPath);
                watcher.doSomething();
            }
        };
        try (WatchMonitor monitor = WatchMonitor.createAll(file, simpleWatcher)) {
            monitor.start();
        }
    }
434933
@FFDCIgnore({ AnnotationTargetsVisitor.VisitEnded.class, ArrayIndexOutOfBoundsException.class })
    protected boolean scanClass(String classSourceName,
                                String className,
                                InputStream inputStream,
                                ScanPolicy scanPolicy) {

        Object[] logParms;
        if (tc.isDebugEnabled()) {
            logParms = new Object[] { getHashText(), className, null };
            Tr.debug(tc, MessageFormat.format("[ {0} ] ENTER class [ {1} ]", logParms));
        } else {
            logParms = null;
        }

        AnnotationTargetsVisitor useVisitor = getVisitor();

        useVisitor.i_setClassSourceName(internClassSourceName(classSourceName));

        // For non-seed scans, tell the visitor to only process the
        // class relationship information.  Skip class annotations and
        // and class contents (fields and methods).

        useVisitor.setScanPolicy(scanPolicy);
        useVisitor.setExternalName(className);

        boolean failedScan;

        try {
            // Both IOException and Exception have been seen;
            // in particular ArrayindexOutOfBoundsException for a non-valid class.

            ClassReader classReader = new ClassReader(inputStream); // throws IOException, Exception

            classReader.accept(getVisitor(),
                               (ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG | ClassReader.SKIP_CODE));
            // 'accept' throws IOException, VisitEnded, Exception

            failedScan = false;

            if (logParms != null) {
                logParms[2] = "Success";
            }

        } catch (IOException e) {
            failedScan = true;

            // String eMsg = "[ " + getHashText() + " ] Class [ " + className + " ] Exception creating reader";
            Tr.warning(tc, "ANNO_TARGETS_FAILED_TO_CREATE_READER", className); // CWWKC0049W

        } catch (AnnotationTargetsVisitor.VisitEnded e) {
            // 'VisitEnded' is used both for a normal flow control for
            // skipping detailed scan data (which is not a failed scan)
            // and for other cases, such as duplicate scan requests
            // and name mismatch cases, which are failures.

            failedScan = !e.isDetailCase();

            if (logParms != null) {
                logParms[2] = "Halted: " + e.getEndCase();
            }

        } catch (ArrayIndexOutOfBoundsException e) {
            Tr.info(tc, "ANNO_TARGETS_CORRUPT_CLASS", className, classSourceName);
            failedScan = true;

        } catch (Exception e) {
            // String eMsg = "[ " + getHashText() + " ] Visit failure [ " + className + " ]";
            // CWWKC0044W: An exception occurred while scanning class and annotation data.
            Tr.warning(tc, "ANNO_TARGETS_SCAN_EXCEPTION", e);

            if (logParms != null) {
                logParms[2] = "Exception: " + e.getMessage();
            }

            failedScan = true;
        }

        if (logParms != null) {
            Tr.debug(tc, MessageFormat.format("[ {0} ] RETURN From class [ {1} ]: [ {2} ]", logParms));
        }

        return (!failedScan);
    }
1112671
def scan_file(path)
      @parser.reset
      ast, comments = @parser.parse_with_comments(make_buffer(path))

      results = @call_finder.collect_calls ast do |send_node, method_name|
        send_node_to_key_occurrence(send_node, method_name)
      end

      magic_comments  = comments.select { |comment| comment.text =~ MAGIC_COMMENT_PREFIX }
      comment_to_node = Parser::Source::Comment.associate_locations(ast, magic_comments).tap do |h|
        # transform_values is only available in ActiveSupport 4.2+
        h.each { |k, v| h[k] = v.first }
      end.invert
      results + (magic_comments.flat_map do |comment|
        @parser.reset
        associated_node = comment_to_node[comment]
        @call_finder.collect_calls(
          @parser.parse(make_buffer(path, comment.text.sub(MAGIC_COMMENT_PREFIX, '').split(/\s+(?=t)/).join('; ')))
        ) do |send_node, _method_name|
          # method_name is not available at this stage
          send_node_to_key_occurrence(send_node, nil, location: associated_node || comment.location)
        end
      end)
    rescue Exception => e # rubocop:disable Lint/RescueException
      raise ::I18n::Tasks::CommandError.new(e, "Error scanning #{path}: #{e.message}")
    end
1039163
public TypeDefinitionRegistry parse(File file) throws SchemaProblem {
        try {
            return parse(Files.newBufferedReader(file.toPath(), defaultCharset()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
829382
@Nonnull
    public static String readFile(@Nonnull File file, @Nonnull String charset) throws IOException {
        return readFile(file, Charset.forName(charset));
    }
1068539
public void checkXmlFile(File file) throws IOException, SAXException {
        validator.reset();
        InputSource is = new InputSource(new FileInputStream(file));
        is.setSystemId(file.toURI().toURL().toString());
        checkAsXML(is);
    }
293114
private <F extends FileDescriptor> F scanFile(MavenProjectDirectoryDescriptor projectDescriptor, File file, String path, Scope scope, Scanner scanner) {
        scanner.getContext().push(MavenProjectDirectoryDescriptor.class, projectDescriptor);
        try {
            return scanner.scan(file, path, scope);
        } finally {
            scanner.getContext().pop(MavenProjectDirectoryDescriptor.class);
        }
    }
1256363
private void scanFile(File file) {
        try {
            InplaceFileConverter fc = new InplaceFileConverter(ruleSet, progressListener);
            fc.convert(file);
        } catch (IOException exc) {
            addException(new ConversionException(exc.toString()));
        }
    }
609509
public void traverse(EclipseASTVisitor visitor) {
		if (visitor.isDeferUntilPostDiet() && !isCompleteParse()) return;
		
		switch (getKind()) {
		case COMPILATION_UNIT:
			visitor.visitCompilationUnit(this, (CompilationUnitDeclaration) get());
			ast.traverseChildren(visitor, this);
			visitor.endVisitCompilationUnit(this, (CompilationUnitDeclaration) get());
			break;
		case TYPE:
			visitor.visitType(this, (TypeDeclaration) get());
			ast.traverseChildren(visitor, this);
			visitor.endVisitType(this, (TypeDeclaration) get());
			break;
		case FIELD:
			visitor.visitField(this, (FieldDeclaration) get());
			ast.traverseChildren(visitor, this);
			visitor.endVisitField(this, (FieldDeclaration) get());
			break;
		case INITIALIZER:
			visitor.visitInitializer(this, (Initializer) get());
			ast.traverseChildren(visitor, this);
			visitor.endVisitInitializer(this, (Initializer) get());
			break;
		case METHOD:
			if (get() instanceof Clinit) return;
			visitor.visitMethod(this, (AbstractMethodDeclaration) get());
			ast.traverseChildren(visitor, this);
			visitor.endVisitMethod(this, (AbstractMethodDeclaration) get());
			break;
		case ARGUMENT:
			AbstractMethodDeclaration method = (AbstractMethodDeclaration) up().get();
			visitor.visitMethodArgument(this, (Argument) get(), method);
			ast.traverseChildren(visitor, this);
			visitor.endVisitMethodArgument(this, (Argument) get(), method);
			break;
		case LOCAL:
			visitor.visitLocal(this, (LocalDeclaration) get());
			ast.traverseChildren(visitor, this);
			visitor.endVisitLocal(this, (LocalDeclaration) get());
			break;
		case ANNOTATION:
			switch (up().getKind()) {
			case TYPE:
				visitor.visitAnnotationOnType((TypeDeclaration) up().get(), this, (Annotation) get());
				break;
			case FIELD:
				visitor.visitAnnotationOnField((FieldDeclaration) up().get(), this, (Annotation) get());
				break;
			case METHOD:
				visitor.visitAnnotationOnMethod((AbstractMethodDeclaration) up().get(), this, (Annotation) get());
				break;
			case ARGUMENT:
				visitor.visitAnnotationOnMethodArgument(
						(Argument) parent.get(),
						(AbstractMethodDeclaration) parent.directUp().get(),
						this, (Annotation) get());
				break;
			case LOCAL:
				visitor.visitAnnotationOnLocal((LocalDeclaration) parent.get(), this, (Annotation) get());
				break;
			case TYPE_USE:
				visitor.visitAnnotationOnTypeUse((TypeReference) parent.get(), this, (Annotation) get());
				break;
			default:
				throw new AssertionError("Annotation not expected as child of a " + up().getKind());
			}
			break;
		case TYPE_USE:
			visitor.visitTypeUse(this, (TypeReference) get());
			ast.traverseChildren(visitor, this);
			visitor.endVisitTypeUse(this, (TypeReference) get());
			break;
		case STATEMENT:
			visitor.visitStatement(this, (Statement) get());
			ast.traverseChildren(visitor, this);
			visitor.endVisitStatement(this, (Statement) get());
			break;
		default:
			throw new AssertionError("Unexpected kind during node traversal: " + getKind());
		}
	}
291075
public function scan($file)
    {
        // If no decision is already made about this file
        if (!isset($this->states[$file])) {
            $this->display(' -> Scanning '.$file.'...');
            $this->states[$file] = self::NO_PARSE;
            $entry = $this->metas->get($file);
            $rst = $this->getRST($file);

            if (!$entry || !file_exists($rst) || $entry['ctime'] < filectime($rst)) {
                // File was never seen or changed and thus need to be parsed
                $this->addToParseQueue($file);
            } else {
                // Have a look to the file dependencies to knoww if you need to parse
                // it or not
                $depends = $entry['depends'];

                if (isset($entry['parent'])) {
                    $depends[] = $entry['parent'];
                }

                foreach ($depends as $dependency) {
                    $this->scan($dependency);

                    // If any dependency needs to be parsed, this file needs also to be
                    // parsed
                    if ($this->states[$dependency] == self::PARSE) {
                        $this->addToParseQueue($file);
                    }
                }
            }
        }
    }