Search in sources :

Example 1 with FindBugs2

use of edu.umd.cs.findbugs.FindBugs2 in project gradle by gradle.

the class FindBugsExecuter method runFindbugs.

@Override
public FindBugsResult runFindbugs(FindBugsSpec spec) throws IOException, InterruptedException {
    final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        final List<String> args = spec.getArguments();
        String[] strArray = args.toArray(new String[0]);
        Thread.currentThread().setContextClassLoader(FindBugs2.class.getClassLoader());
        FindBugs2 findBugs2 = new FindBugs2();
        TextUICommandLine commandLine = new TextUICommandLine();
        FindBugs.processCommandLine(commandLine, strArray, findBugs2);
        findBugs2.execute();
        return createFindbugsResult(findBugs2);
    } finally {
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }
}
Also used : FindBugs2(edu.umd.cs.findbugs.FindBugs2) TextUICommandLine(edu.umd.cs.findbugs.TextUICommandLine)

Example 2 with FindBugs2

use of edu.umd.cs.findbugs.FindBugs2 in project spotbugs by spotbugs.

the class FindBugsWorker method work.

/**
 * Run FindBugs on the given collection of resources from same project
 * (note: This is currently not thread-safe)
 *
 * @param resources
 *            files or directories which should be on the project classpath.
 *            All resources must belong to the same project, and no one of
 *            the elements can contain another one. Ergo, if the list
 *            contains a project itself, then it must have only one element.
 * @throws CoreException
 */
public void work(List<WorkItem> resources) throws CoreException {
    if (resources == null || resources.isEmpty()) {
        if (DEBUG) {
            FindbugsPlugin.getDefault().logInfo("No resources to analyse for project " + project);
        }
        return;
    }
    if (DEBUG) {
        System.out.println(resources);
    }
    st = new StopTimer();
    st.newPoint("initPlugins");
    // make sure it's initialized
    FindbugsPlugin.applyCustomDetectors(false);
    st.newPoint("clearMarkers");
    // clear markers
    clearMarkers(resources);
    st.newPoint("configureOutputFiles");
    final Project findBugsProject = new Project();
    findBugsProject.setProjectName(javaProject.getElementName());
    final Reporter bugReporter = new Reporter(javaProject, findBugsProject, monitor);
    if (FindBugsConsole.getConsole() != null) {
        bugReporter.setReportingStream(FindBugsConsole.getConsole().newOutputStream());
    }
    bugReporter.setPriorityThreshold(userPrefs.getUserDetectorThreshold());
    FindBugs.setHome(FindbugsPlugin.getFindBugsEnginePluginLocation());
    Map<IPath, IPath> outLocations = createOutputLocations();
    // collect all related class/jar/war etc files for analysis
    collectClassFiles(resources, outLocations, findBugsProject);
    // attach source directories (can be used by some detectors, see
    // SwitchFallthrough)
    configureSourceDirectories(findBugsProject, outLocations);
    if (findBugsProject.getFileCount() == 0) {
        if (DEBUG) {
            FindbugsPlugin.getDefault().logInfo("No resources to analyse for project " + project);
        }
        return;
    }
    st.newPoint("createAuxClasspath");
    String[] classPathEntries = createAuxClasspath();
    // add to findbugs classpath
    for (String entry : classPathEntries) {
        findBugsProject.addAuxClasspathEntry(entry);
    }
    st.newPoint("configureProps");
    IPreferenceStore store = FindbugsPlugin.getPluginPreferences(project);
    boolean cacheClassData = store.getBoolean(FindBugsConstants.KEY_CACHE_CLASS_DATA);
    final FindBugs2 findBugs = new FindBugs2Eclipse(project, cacheClassData, bugReporter);
    findBugs.setNoClassOk(true);
    findBugs.setProject(findBugsProject);
    findBugs.setBugReporter(bugReporter);
    findBugs.setProgressCallback(bugReporter);
    findBugs.setDetectorFactoryCollection(DetectorFactoryCollection.instance());
    // configure detectors.
    userPrefs.setIncludeFilterFiles(relativeToAbsolute(userPrefs.getIncludeFilterFiles()));
    userPrefs.setExcludeFilterFiles(relativeToAbsolute(userPrefs.getExcludeFilterFiles()));
    userPrefs.setExcludeBugsFiles(relativeToAbsolute(userPrefs.getExcludeBugsFiles()));
    findBugs.setUserPreferences(userPrefs);
    // configure extended preferences
    findBugs.setAnalysisFeatureSettings(userPrefs.getAnalysisFeatureSettings());
    findBugs.setMergeSimilarWarnings(false);
    if (cacheClassData) {
        FindBugs2Eclipse.checkClassPathChanges(findBugs.getProject().getAuxClasspathEntryList(), project);
    }
    st.newPoint("runFindBugs");
    if (DEBUG) {
        FindbugsPlugin.log("Running SpotBugs");
    }
    runFindBugs(findBugs);
    if (DEBUG) {
        FindbugsPlugin.log("Done running SpotBugs");
    }
    // Merge new results into existing results
    // if the argument is project, then it's not incremental
    boolean incremental = !(resources.get(0) instanceof IProject);
    updateBugCollection(findBugsProject, bugReporter, incremental);
    st.newPoint("done");
    st = null;
    monitor.done();
}
Also used : IProject(org.eclipse.core.resources.IProject) Project(edu.umd.cs.findbugs.Project) IJavaProject(org.eclipse.jdt.core.IJavaProject) IPath(org.eclipse.core.runtime.IPath) FindBugs2(edu.umd.cs.findbugs.FindBugs2) Reporter(de.tobject.findbugs.reporter.Reporter) StopTimer(de.tobject.findbugs.util.Util.StopTimer) IPreferenceStore(org.eclipse.jface.preference.IPreferenceStore) IProject(org.eclipse.core.resources.IProject)

Example 3 with FindBugs2

use of edu.umd.cs.findbugs.FindBugs2 in project spotbugs by spotbugs.

the class BugLoader method createEngine.

/**
 * Create the IFindBugsEngine that will be used to analyze the application.
 *
 * @param p
 *            the Project
 * @param pcb
 *            the PrintCallBack
 * @return the IFindBugsEngine
 */
private static IFindBugsEngine createEngine(@Nonnull Project p, BugReporter pcb) {
    FindBugs2 engine = new FindBugs2();
    engine.setBugReporter(pcb);
    engine.setProject(p);
    engine.setDetectorFactoryCollection(DetectorFactoryCollection.instance());
    // 
    // Honor -effort option if one was given on the command line.
    // 
    engine.setAnalysisFeatureSettings(Driver.getAnalysisSettingList());
    return engine;
}
Also used : FindBugs2(edu.umd.cs.findbugs.FindBugs2)

Example 4 with FindBugs2

use of edu.umd.cs.findbugs.FindBugs2 in project spotbugs by spotbugs.

the class AnalysisRunner method run.

@Nonnull
public BugCollectionBugReporter run(Consumer<IFindBugsEngine> engineCustomization, Path... files) {
    DetectorFactoryCollection.resetInstance(new DetectorFactoryCollection());
    try (FindBugs2 engine = new FindBugs2();
        Project project = createProject(files)) {
        engine.setProject(project);
        final DetectorFactoryCollection detectorFactoryCollection = DetectorFactoryCollection.instance();
        engine.setDetectorFactoryCollection(detectorFactoryCollection);
        BugCollectionBugReporter bugReporter = new BugCollectionBugReporter(project);
        bugReporter.setPriorityThreshold(Priorities.LOW_PRIORITY);
        bugReporter.setRankThreshold(BugRanker.VISIBLE_RANK_MAX);
        engine.setBugReporter(bugReporter);
        final UserPreferences preferences = UserPreferences.createDefaultUserPreferences();
        preferences.getFilterSettings().clearAllCategories();
        preferences.enableAllDetectors(true);
        engine.setUserPreferences(preferences);
        engineCustomization.accept(engine);
        try {
            engine.execute();
        } catch (final IOException | InterruptedException e) {
            throw new AssertionError("Analysis failed with exception", e);
        }
        if (!bugReporter.getQueuedErrors().isEmpty()) {
            bugReporter.reportQueuedErrors();
            throw new AssertionError("Analysis failed with exception. Check stderr for detail.");
        }
        return bugReporter;
    }
}
Also used : UserPreferences(edu.umd.cs.findbugs.config.UserPreferences) Project(edu.umd.cs.findbugs.Project) FindBugs2(edu.umd.cs.findbugs.FindBugs2) IOException(java.io.IOException) DetectorFactoryCollection(edu.umd.cs.findbugs.DetectorFactoryCollection) BugCollectionBugReporter(edu.umd.cs.findbugs.BugCollectionBugReporter) Nonnull(javax.annotation.Nonnull)

Example 5 with FindBugs2

use of edu.umd.cs.findbugs.FindBugs2 in project sonar-findbugs by spotbugs.

the class FindbugsExecutor method execute.

public Collection<ReportedBug> execute(boolean useFbContrib, boolean useFindSecBugs) {
    // We keep a handle on the current security manager because FB plays with it and we need to restore it before shutting down the executor
    // service
    SecurityManager currentSecurityManager = System.getSecurityManager();
    ClassLoader initialClassLoader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(FindBugs2.class.getClassLoader());
    // This is a dirty workaround, but unfortunately there is no other way to make Findbugs generate english messages only - see SONARJAVA-380
    Locale initialLocale = Locale.getDefault();
    Locale.setDefault(Locale.ENGLISH);
    OutputStream xmlOutput = null;
    Collection<Plugin> customPlugins = null;
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    try (FindBugs2 engine = new FindBugs2();
        Project project = new Project()) {
        configuration.initializeFindbugsProject(project);
        if (project.getFileCount() == 0) {
            LOG.info("Findbugs analysis skipped for this project.");
            return new ArrayList<>();
        }
        customPlugins = loadFindbugsPlugins(useFbContrib, useFindSecBugs);
        disableUpdateChecksOnEveryPlugin();
        engine.setProject(project);
        XMLBugReporter xmlBugReporter = new XMLBugReporter(project);
        xmlBugReporter.setPriorityThreshold(determinePriorityThreshold());
        xmlBugReporter.setAddMessages(true);
        File xmlReport = configuration.getTargetXMLReport();
        LOG.info("Findbugs output report: " + xmlReport.getAbsolutePath());
        xmlOutput = FileUtils.openOutputStream(xmlReport);
        xmlBugReporter.setOutputStream(new PrintStream(xmlOutput));
        engine.setBugReporter(xmlBugReporter);
        UserPreferences userPreferences = UserPreferences.createDefaultUserPreferences();
        userPreferences.setEffort(configuration.getEffort());
        engine.setUserPreferences(userPreferences);
        engine.addFilter(configuration.saveIncludeConfigXml().getAbsolutePath(), true);
        for (File filterFile : configuration.getExcludesFilters()) {
            if (filterFile.isFile()) {
                LOG.info("Use filter-file: {}", filterFile);
                engine.addFilter(filterFile.getAbsolutePath(), false);
            } else {
                LOG.warn("FindBugs filter-file not found: {}", filterFile);
            }
        }
        engine.setDetectorFactoryCollection(DetectorFactoryCollection.instance());
        engine.setAnalysisFeatureSettings(FindBugs.DEFAULT_EFFORT);
        engine.finishSettings();
        // Load findbugs report location
        List<String> potentialReportPaths = new ArrayList<>();
        potentialReportPaths.addAll(EXISTING_FINDBUGS_REPORT_PATHS);
        String[] paths = config.getStringArray(FindbugsConstants.REPORT_PATHS);
        if (paths != null)
            potentialReportPaths.addAll(Arrays.asList(paths));
        boolean foundExistingReport = false;
        // Look for existing reports relative to subproject directory
        reportPaths: for (String potentialPath : potentialReportPaths) {
            File findbugsReport = new File(fs.baseDir(), potentialPath);
            // File.length() is unspecified for directories
            if (findbugsReport.exists() && !findbugsReport.isDirectory() && findbugsReport.length() > 0) {
                LOG.info("FindBugs report is already generated {}. Reusing the report.", findbugsReport.getAbsolutePath());
                xmlBugReporter.getBugCollection().readXML(new FileReader(findbugsReport));
                foundExistingReport = true;
                break reportPaths;
            }
        }
        if (!foundExistingReport) {
            // Avoid rescanning the project if FindBugs was run already
            executorService.submit(new FindbugsTask(engine)).get(configuration.getTimeout(), TimeUnit.MILLISECONDS);
        }
        return toReportedBugs(xmlBugReporter.getBugCollection());
    } catch (TimeoutException e) {
        throw new IllegalStateException("Can not execute Findbugs with a timeout threshold value of " + configuration.getTimeout() + " milliseconds", e);
    } catch (Exception e) {
        throw new IllegalStateException("Can not execute Findbugs", e);
    } finally {
        // we set back the original security manager BEFORE shutting down the executor service, otherwise there's a problem with Java 5
        System.setSecurityManager(currentSecurityManager);
        resetCustomPluginList(customPlugins);
        executorService.shutdown();
        IOUtils.closeQuietly(xmlOutput);
        Thread.currentThread().setContextClassLoader(initialClassLoader);
        Locale.setDefault(initialLocale);
    }
}
Also used : UserPreferences(edu.umd.cs.findbugs.config.UserPreferences) PrintStream(java.io.PrintStream) FindBugs2(edu.umd.cs.findbugs.FindBugs2) OutputStream(java.io.OutputStream) XMLBugReporter(edu.umd.cs.findbugs.XMLBugReporter) URISyntaxException(java.net.URISyntaxException) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) DuplicatePluginIdException(edu.umd.cs.findbugs.plugins.DuplicatePluginIdException) PluginException(edu.umd.cs.findbugs.PluginException) Project(edu.umd.cs.findbugs.Project) ExecutorService(java.util.concurrent.ExecutorService) FileReader(java.io.FileReader) File(java.io.File) Plugin(edu.umd.cs.findbugs.Plugin) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

FindBugs2 (edu.umd.cs.findbugs.FindBugs2)5 Project (edu.umd.cs.findbugs.Project)3 UserPreferences (edu.umd.cs.findbugs.config.UserPreferences)2 IOException (java.io.IOException)2 Reporter (de.tobject.findbugs.reporter.Reporter)1 StopTimer (de.tobject.findbugs.util.Util.StopTimer)1 BugCollectionBugReporter (edu.umd.cs.findbugs.BugCollectionBugReporter)1 DetectorFactoryCollection (edu.umd.cs.findbugs.DetectorFactoryCollection)1 Plugin (edu.umd.cs.findbugs.Plugin)1 PluginException (edu.umd.cs.findbugs.PluginException)1 TextUICommandLine (edu.umd.cs.findbugs.TextUICommandLine)1 XMLBugReporter (edu.umd.cs.findbugs.XMLBugReporter)1 DuplicatePluginIdException (edu.umd.cs.findbugs.plugins.DuplicatePluginIdException)1 File (java.io.File)1 FileReader (java.io.FileReader)1 OutputStream (java.io.OutputStream)1 PrintStream (java.io.PrintStream)1 URISyntaxException (java.net.URISyntaxException)1 ExecutorService (java.util.concurrent.ExecutorService)1 TimeoutException (java.util.concurrent.TimeoutException)1