Search in sources :

Example 21 with Project

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

the class Filter method main.

public static void main(String[] args) throws Exception {
    FindBugs.setNoAnalysis();
    DetectorFactoryCollection.instance();
    final FilterCommandLine commandLine = new FilterCommandLine();
    int argCount = commandLine.parse(args, 0, 2, "Usage: " + Filter.class.getName() + " [options] [<orig results> [<new results>]] ");
    SortedBugCollection origCollection = new SortedBugCollection();
    if (argCount == args.length) {
        origCollection.readXML(System.in);
    } else {
        origCollection.readXML(args[argCount++]);
    }
    boolean verbose = argCount < args.length;
    SortedBugCollection resultCollection = origCollection.createEmptyCollectionWithMetadata();
    Project project = resultCollection.getProject();
    int passed = 0;
    int dropped = 0;
    resultCollection.setWithMessages(commandLine.withMessages);
    if (commandLine.hashChangedSpecified) {
        origCollection.computeBugHashes();
    }
    commandLine.adjustFilter(project, resultCollection);
    ProjectStats projectStats = resultCollection.getProjectStats();
    projectStats.clearBugCounts();
    if (commandLine.classPattern != null) {
        projectStats.purgeClassesThatDontMatch(commandLine.classPattern);
    }
    sourceSearcher = new SourceSearcher(project);
    long trimToVersion = -1;
    if (commandLine.trimToVersionAsString != null) {
        Map<String, AppVersion> versions = new HashMap<>();
        SortedMap<Long, AppVersion> timeStamps = new TreeMap<>();
        for (Iterator<AppVersion> i = origCollection.appVersionIterator(); i.hasNext(); ) {
            AppVersion v = i.next();
            versions.put(v.getReleaseName(), v);
            timeStamps.put(v.getTimestamp(), v);
        }
        // add current version to the maps
        AppVersion v = resultCollection.getCurrentAppVersion();
        versions.put(v.getReleaseName(), v);
        timeStamps.put(v.getTimestamp(), v);
        trimToVersion = edu.umd.cs.findbugs.workflow.Filter.FilterCommandLine.getVersionNum(versions, timeStamps, commandLine.trimToVersionAsString, true, v.getSequenceNumber());
        if (trimToVersion < origCollection.getSequenceNumber()) {
            String name = resultCollection.getAppVersionFromSequenceNumber(trimToVersion).getReleaseName();
            long timestamp = resultCollection.getAppVersionFromSequenceNumber(trimToVersion).getTimestamp();
            resultCollection.setReleaseName(name);
            resultCollection.setTimestamp(timestamp);
            resultCollection.trimAppVersions(trimToVersion);
        }
    }
    commandLine.getReady(origCollection);
    for (BugInstance bug : origCollection.getCollection()) {
        if (commandLine.accept(origCollection, bug)) {
            if (trimToVersion >= 0) {
                if (bug.getFirstVersion() > trimToVersion) {
                    dropped++;
                    continue;
                } else if (bug.getLastVersion() >= trimToVersion) {
                    bug.setLastVersion(-1);
                    bug.setRemovedByChangeOfPersistingClass(false);
                }
            }
            resultCollection.add(bug, false);
            passed++;
        } else {
            dropped++;
        }
    }
    if (commandLine.purgeHistorySpecified && commandLine.purgeHistory) {
        resultCollection.clearAppVersions();
        for (BugInstance bug : resultCollection.getCollection()) {
            bug.clearHistory();
        }
    }
    if (verbose) {
        System.out.println(passed + " warnings passed through, " + dropped + " warnings dropped");
    }
    if (commandLine.withSourceSpecified && commandLine.withSource && !commandLine.dontUpdateStats && projectStats.hasClassStats()) {
        for (PackageStats stats : projectStats.getPackageStats()) {
            Iterator<ClassStats> i = stats.getClassStats().iterator();
            while (i.hasNext()) {
                String className = i.next().getName();
                if (sourceSearcher.sourceNotFound.contains(className) || !sourceSearcher.sourceFound.contains(className) && !sourceSearcher.findSource(SourceLineAnnotation.createReallyUnknown(className))) {
                    i.remove();
                }
            }
        }
    }
    projectStats.recomputeFromComponents();
    if (argCount == args.length) {
        assert !verbose;
        resultCollection.writeXML(System.out);
    } else {
        resultCollection.writeXML(args[argCount++]);
    }
}
Also used : ProjectStats(edu.umd.cs.findbugs.ProjectStats) HashMap(java.util.HashMap) SortedBugCollection(edu.umd.cs.findbugs.SortedBugCollection) BugInstance(edu.umd.cs.findbugs.BugInstance) TreeMap(java.util.TreeMap) AppVersion(edu.umd.cs.findbugs.AppVersion) Project(edu.umd.cs.findbugs.Project) PackageStats(edu.umd.cs.findbugs.PackageStats) ClassStats(edu.umd.cs.findbugs.PackageStats.ClassStats)

Example 22 with Project

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

the class SarifBugReporterTest method setup.

@Before
public void setup() {
    Project project = new Project();
    reporter = new SarifBugReporter(project);
    writer = new StringWriter();
    reporter.setWriter(new PrintWriter(writer));
    reporter.setPriorityThreshold(Priorities.IGNORE_PRIORITY);
    DetectorFactoryCollection.resetInstance(new DetectorFactoryCollection());
    IAnalysisCache analysisCache = ClassFactory.instance().createAnalysisCache(new ClassPathImpl(), reporter);
    Global.setAnalysisCacheForCurrentThread(analysisCache);
    FindBugs2.registerBuiltInAnalysisEngines(analysisCache);
    AnalysisContext analysisContext = new AnalysisContext(project) {

        public boolean isApplicationClass(@DottedClassName String className) {
            // treat all classes as application class, to report bugs in it
            return true;
        }
    };
    AnalysisContext.setCurrentAnalysisContext(analysisContext);
}
Also used : Project(edu.umd.cs.findbugs.Project) StringWriter(java.io.StringWriter) ClassPathImpl(edu.umd.cs.findbugs.classfile.impl.ClassPathImpl) IAnalysisCache(edu.umd.cs.findbugs.classfile.IAnalysisCache) AnalysisContext(edu.umd.cs.findbugs.ba.AnalysisContext) PrintWriter(java.io.PrintWriter) DetectorFactoryCollection(edu.umd.cs.findbugs.DetectorFactoryCollection) DottedClassName(edu.umd.cs.findbugs.internalAnnotations.DottedClassName) Before(org.junit.Before)

Example 23 with Project

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

the class PreferencesFrame method rebuildPluginCheckboxes.

private void rebuildPluginCheckboxes() {
    Project currentProject = getCurrentProject();
    pluginPanelCenter.removeAll();
    if (currentProject != null) {
        GridBagConstraints g = new GridBagConstraints();
        g.fill = GridBagConstraints.NONE;
        g.insets = new Insets(5, 5, 5, 5);
        g.gridy = 0;
        // g.anchor = GridBagConstraints.WEST;
        // g.gridx = 1;
        // pluginPanelCenter.add(new JLabel("Global Setting"), g);
        g.anchor = GridBagConstraints.CENTER;
        g.gridx = 2;
        pluginPanelCenter.add(new JLabel("Project Setting"), g);
    }
    Collection<Plugin> plugins = Plugin.getAllPlugins();
    int added = 0;
    for (final Plugin plugin : plugins) {
        if (plugin.isCorePlugin()) {
            continue;
        }
        String text = plugin.getShortDescription();
        String id = plugin.getPluginId();
        if (text == null) {
            text = id;
        }
        final URL url = plugin.getPluginLoader().getURL();
        String pluginUrlStr = url.toExternalForm();
        if ("file".equals(url.getProtocol())) {
            try {
                pluginUrlStr = new File(URLDecoder.decode(url.getPath(), "UTF-8")).getAbsolutePath();
            } catch (UnsupportedEncodingException e) {
            }
        }
        text = String.format("<html>%s<br><font style='font-weight:normal;font-style:italic'>%s", text, pluginUrlStr);
        EnabledSettings enabled = isEnabled(currentProject, plugin);
        final JCheckBox checkGlobal = new JCheckBox(text, enabled.global);
        final boolean cannotDisable = plugin.isEnabledByDefault() && plugin.cannotDisable();
        if (cannotDisable) {
            if (!enabled.global) {
                throw new IllegalStateException(plugin.getPluginId() + " is enabled by default and cannot be disabled, but is disabled");
            }
            checkGlobal.setEnabled(false);
        } else {
            checkGlobal.addMouseListener(new MouseAdapter() {

                @Override
                public void mousePressed(MouseEvent e) {
                    if (SwingUtilities.isRightMouseButton(e)) {
                        JPopupMenu menu = new JPopupMenu();
                        JMenuItem item = new JMenuItem("Uninstall " + plugin.getShortDescription() + "...");
                        item.addActionListener(new UninstallClickListener(plugin, url));
                        menu.add(item);
                        menu.show(checkGlobal, e.getX(), e.getY());
                    }
                }
            });
            checkGlobal.addActionListener(e -> pluginEnabledStatus.get(plugin).global = checkGlobal.isSelected());
        }
        checkGlobal.setVerticalTextPosition(SwingConstants.TOP);
        String longText = plugin.getDetailedDescription();
        if (longText != null) {
            checkGlobal.setToolTipText("<html>" + longText + "</html>");
        }
        pluginEnabledStatus.put(plugin, enabled);
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.BOTH;
        gbc.weightx = 1;
        gbc.gridx = 1;
        gbc.insets = new Insets(0, 5, 0, 5);
        gbc.gridy = added + 1;
        gbc.anchor = GridBagConstraints.NORTHWEST;
        pluginPanelCenter.add(checkGlobal, gbc);
        if (currentProject != null && !cannotDisable) {
            final JComboBox<String> combo = new WideComboBox<>(new String[] { "DEFAULT", "DISABLED", "ENABLED" });
            if (enabled.project == null) {
                combo.setSelectedIndex(0);
            } else {
                combo.setSelectedIndex(enabled.project ? 2 : 1);
            }
            combo.setRenderer(new DefaultListCellRenderer() {

                @Override
                public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                    if (index == -1) {
                        if (value.equals("DEFAULT")) {
                            value = "Default";
                        }
                        if (value.equals("DISABLED")) {
                            value = "Disabled";
                        }
                        if (value.equals("ENABLED")) {
                            value = "Enabled";
                        }
                    } else {
                        if (value.equals("DEFAULT")) {
                            value = "Default (use global setting)";
                        }
                        if (value.equals("DISABLED")) {
                            value = "Disabled for this project";
                        }
                        if (value.equals("ENABLED")) {
                            value = "Enabled for this project";
                        }
                    }
                    return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                }
            });
            combo.addActionListener(e -> {
                Boolean[] array = { null, false, true };
                int i = combo.getSelectedIndex();
                if (i < 0 || i > 2) {
                    // ??
                    return;
                }
                pluginEnabledStatus.get(plugin).project = array[i];
            });
            gbc.gridx = 2;
            gbc.fill = GridBagConstraints.NONE;
            gbc.weightx = 0;
            pluginPanelCenter.add(combo, gbc);
        }
        added++;
    }
    if (added == 0) {
        JLabel label = new JLabel("<html>No plugins are loaded.<br> " + "Try installing <u><font color=blue>fb-contrib</font></u> - or write your own<br>" + "plugin for your project's needs!");
        label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        label.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                try {
                    LaunchBrowser.showDocument(new URL("https://sourceforge.net/projects/fb-contrib/"));
                } catch (MalformedURLException e1) {
                    throw new IllegalStateException(e1);
                }
            }
        });
        label.setBorder(new EmptyBorder(10, 10, 10, 10));
        pluginPanelCenter.add(label);
    }
    PreferencesFrame.this.pack();
}
Also used : GridBagConstraints(java.awt.GridBagConstraints) MalformedURLException(java.net.MalformedURLException) Insets(java.awt.Insets) URL(java.net.URL) DefaultListCellRenderer(javax.swing.DefaultListCellRenderer) JMenuItem(javax.swing.JMenuItem) Component(java.awt.Component) JComponent(javax.swing.JComponent) EmptyBorder(javax.swing.border.EmptyBorder) JLabel(javax.swing.JLabel) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JPopupMenu(javax.swing.JPopupMenu) JCheckBox(javax.swing.JCheckBox) Project(edu.umd.cs.findbugs.Project) File(java.io.File) JList(javax.swing.JList) Plugin(edu.umd.cs.findbugs.Plugin)

Example 24 with Project

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

the class SourceMatcherTest method testRealPathMatchWithRegexpAndProject.

@Test
public void testRealPathMatchWithRegexpAndProject() throws Exception {
    // add this test class as the bug target
    bug.addClass("SourceMatcherTest", null);
    ClassAnnotation primaryClass = bug.getPrimaryClass();
    // set source file
    primaryClass.setSourceLines(SourceLineAnnotation.createUnknown("SourceMatcherTest", "SourceMatcherTest.java"));
    // setup a testing project with source directory, as of right now the source directory should really exist!!
    Project testProject = new Project();
    String sourceDir = "src/test/java/edu/umd/cs/findbugs/filter";
    testProject.addSourceDirs(Collections.singletonList(sourceDir));
    // add test project to SourceLineAnnotation
    SourceLineAnnotation.generateRelativeSource(new File(sourceDir), testProject);
    // regexp match source folder with project
    SourceMatcher sm = new SourceMatcher("~.*findbugs.*.java");
    assertTrue("The regex matches the source directory of the given java file", sm.match(bug));
    sm = new SourceMatcher("~.*notfound.*.java");
    assertFalse("The regex does not match the source directory of the given java file", sm.match(bug));
}
Also used : Project(edu.umd.cs.findbugs.Project) ClassAnnotation(edu.umd.cs.findbugs.ClassAnnotation) File(java.io.File) Test(org.junit.Test)

Example 25 with Project

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

the class MergeSummarizeAndView method createPreconfiguredBugCollection.

static SortedBugCollection createPreconfiguredBugCollection(List<String> workingDirList, List<String> srcDirList, IGuiCallback guiCallback) {
    Project project = new Project();
    for (String cwd : workingDirList) {
        project.addWorkingDir(cwd);
    }
    project.addSourceDirs(srcDirList);
    project.setGuiCallback(guiCallback);
    return new SortedBugCollection(project);
}
Also used : Project(edu.umd.cs.findbugs.Project) SortedBugCollection(edu.umd.cs.findbugs.SortedBugCollection)

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