Search in sources :

Example 31 with Project

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

the class FindBugsWorker method loadXml.

/**
 * Load existing FindBugs xml report for the given collection of files.
 *
 * @param fileName
 *            xml file name to load bugs from
 * @throws CoreException
 */
public void loadXml(String fileName) throws CoreException {
    if (fileName == null) {
        return;
    }
    st = new StopTimer();
    // clear markers
    clearMarkers(null);
    final Project findBugsProject = new Project();
    final Reporter bugReporter = new Reporter(javaProject, findBugsProject, monitor);
    bugReporter.setPriorityThreshold(userPrefs.getUserDetectorThreshold());
    reportFromXml(fileName, findBugsProject, bugReporter);
    // Merge new results into existing results.
    updateBugCollection(findBugsProject, bugReporter, false);
    monitor.done();
}
Also used : IProject(org.eclipse.core.resources.IProject) Project(edu.umd.cs.findbugs.Project) IJavaProject(org.eclipse.jdt.core.IJavaProject) Reporter(de.tobject.findbugs.reporter.Reporter) StopTimer(de.tobject.findbugs.util.Util.StopTimer)

Example 32 with Project

use of edu.umd.cs.findbugs.Project 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)

Example 33 with Project

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

the class FindbugsConfigurationTest method should_set_class_files.

@Test
void should_set_class_files() throws IOException {
    File file = new File(temp, "MyClass.class");
    when(javaResourceLocator.classFilesToAnalyze()).thenReturn(ImmutableList.of(file));
    try (Project findbugsProject = new Project()) {
        conf.initializeFindbugsProject(findbugsProject);
        assertThat(findbugsProject.getFileList()).containsOnly(file.getCanonicalPath());
        conf.stop();
    }
}
Also used : Project(edu.umd.cs.findbugs.Project) File(java.io.File) Test(org.junit.jupiter.api.Test)

Example 34 with Project

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

the class FindbugsConfigurationTest method should_analyze_precompiled_jsp.

@Test
void should_analyze_precompiled_jsp() throws IOException {
    setupJspProject(true);
    try (Project project = new Project()) {
        conf.initializeFindbugsProject(project);
        assertThat(project.getFileCount()).isEqualTo(3);
    }
    assertThat(logTester.getLogs(LoggerLevel.WARN)).isNull();
}
Also used : Project(edu.umd.cs.findbugs.Project) Test(org.junit.jupiter.api.Test)

Example 35 with Project

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

the class FindbugsExecutorTest method mockConf.

private FindbugsConfiguration mockConf() throws Exception {
    FindbugsConfiguration conf = mock(FindbugsConfiguration.class);
    doAnswer(invocation -> {
        Project project = invocation.getArgument(0);
        project.addFile(new File("test-resources/classes").getCanonicalPath());
        project.addSourceDirs(Collections.singletonList(new File("test-resources/src").getCanonicalPath()));
        project.setCurrentWorkingDirectory(new File("test-resources"));
        return null;
    }).when(conf).initializeFindbugsProject(any());
    when(conf.saveIncludeConfigXml()).thenReturn(new File("test-resources/findbugs-include.xml"));
    when(conf.getExcludesFilters()).thenReturn(Lists.newArrayList(new File("test-resources/findbugs-exclude.xml"), new File("test-resources/fake-file.xml")));
    when(conf.getEffort()).thenReturn("default");
    when(conf.getTimeout()).thenReturn(FindbugsConstants.TIMEOUT_DEFAULT_VALUE);
    return conf;
}
Also used : Project(edu.umd.cs.findbugs.Project) InputFile(org.sonar.api.batch.fs.InputFile) File(java.io.File)

Aggregations

Project (edu.umd.cs.findbugs.Project)35 SortedBugCollection (edu.umd.cs.findbugs.SortedBugCollection)8 File (java.io.File)8 BugInstance (edu.umd.cs.findbugs.BugInstance)6 AnalysisContext (edu.umd.cs.findbugs.ba.AnalysisContext)4 Test (org.junit.jupiter.api.Test)4 DetectorFactoryCollection (edu.umd.cs.findbugs.DetectorFactoryCollection)3 FindBugs2 (edu.umd.cs.findbugs.FindBugs2)3 Plugin (edu.umd.cs.findbugs.Plugin)3 ProjectStats (edu.umd.cs.findbugs.ProjectStats)3 UserPreferences (edu.umd.cs.findbugs.config.UserPreferences)3 Filter (edu.umd.cs.findbugs.filter.Filter)3 GridBagConstraints (java.awt.GridBagConstraints)3 Insets (java.awt.Insets)3 IOException (java.io.IOException)3 Reporter (de.tobject.findbugs.reporter.Reporter)2 StopTimer (de.tobject.findbugs.util.Util.StopTimer)2 ClassAnnotation (edu.umd.cs.findbugs.ClassAnnotation)2 PackageStats (edu.umd.cs.findbugs.PackageStats)2 PluginException (edu.umd.cs.findbugs.PluginException)2