Search in sources :

Example 1 with BugPattern

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

the class MarkerReporter method createMarkerAttributes.

/**
 * @param mp
 * @return attributes map which should be assigned to the given marker. If the map is empty,
 * the marker shouldn't be generated
 */
@Nonnull
private Map<String, Object> createMarkerAttributes(MarkerParameter mp) {
    Map<String, Object> attributes = new HashMap<>(23);
    attributes.put(IMarker.LINE_NUMBER, mp.startLine);
    attributes.put(PRIMARY_LINE, mp.primaryLine);
    attributes.put(BUG_TYPE, mp.bug.getType());
    attributes.put(PATTERN_TYPE, mp.bug.getAbbrev());
    attributes.put(RANK, Integer.valueOf(mp.bug.getBugRank()));
    attributes.put(PRIO_AKA_CONFIDENCE, MarkerConfidence.getConfidence(mp.bug.getPriority()).name());
    long seqNum = mp.bug.getFirstVersion();
    if (seqNum == 0) {
        attributes.put(FIRST_VERSION, "-1");
    } else {
        AppVersion theVersion = collection.getAppVersionFromSequenceNumber(seqNum);
        if (theVersion == null) {
            attributes.put(FIRST_VERSION, "Cannot find AppVersion: seqnum=" + seqNum + "; collection seqnum=" + collection.getSequenceNumber());
        } else {
            attributes.put(FIRST_VERSION, Long.toString(theVersion.getTimestamp()));
        }
    }
    try {
        attributes.put(IMarker.MESSAGE, getMessage(mp));
    } catch (RuntimeException e) {
        FindbugsPlugin.getDefault().logException(e, "Error generating msg for " + mp.bug.getType() + ", attributes: " + attributes);
        attributes.clear();
        return attributes;
    }
    attributes.put(IMarker.SEVERITY, mp.markerSeverity);
    // Set unique id of warning, so we can easily refer back
    // to it later: for example, when the user classifies the warning.
    String uniqueId = mp.bug.getInstanceHash();
    if (uniqueId != null) {
        attributes.put(UNIQUE_ID, uniqueId);
    }
    // Set unique id of the plugin, so we can easily refer back
    // to it later: for example, when the user group markers by plugin.
    DetectorFactory detectorFactory = mp.bug.getDetectorFactory();
    if (detectorFactory != null) {
        String pluginId = detectorFactory.getPlugin().getPluginId();
        if (pluginId != null) {
            attributes.put(DETECTOR_PLUGIN_ID, pluginId);
        }
    } else {
        // Fix for loading bugs from XML: they do not have detector factory set, so we guess one
        BugPattern pattern = mp.bug.getBugPattern();
        Iterator<DetectorFactory> fit = DetectorFactoryCollection.instance().factoryIterator();
        while (fit.hasNext()) {
            DetectorFactory df2 = fit.next();
            if (!df2.isReportingDetector()) {
                continue;
            }
            Set<BugPattern> patterns = df2.getReportedBugPatterns();
            if (patterns.contains(pattern)) {
                String pluginId = df2.getPlugin().getPluginId();
                if (pluginId != null) {
                    attributes.put(DETECTOR_PLUGIN_ID, pluginId);
                    break;
                }
            }
        }
    }
    if (attributes.get(DETECTOR_PLUGIN_ID) == null) {
        attributes.clear();
        return attributes;
    }
    IJavaElement javaElt = mp.resource.getCorespondingJavaElement();
    if (javaElt != null) {
        attributes.put(UNIQUE_JAVA_ID, javaElt.getHandleIdentifier());
    // Eclipse markers model doesn't allow to have markers
    // attached to the (non-resource) part of the resource (like jar
    // entry inside the jar)
    // TODO we should add annotations to opened class file editors to
    // show (missing)
    // markers for single class file inside the jar. Otherwise we will
    // show markers
    // in the bug explorer view but NOT inside the class file editor
    }
    return attributes;
}
Also used : AppVersion(edu.umd.cs.findbugs.AppVersion) IJavaElement(org.eclipse.jdt.core.IJavaElement) HashMap(java.util.HashMap) DetectorFactory(edu.umd.cs.findbugs.DetectorFactory) BugPattern(edu.umd.cs.findbugs.BugPattern) Nonnull(javax.annotation.Nonnull)

Example 2 with BugPattern

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

the class MainFrame method updateSummaryTab.

private void updateSummaryTab(BugLeafNode node) {
    final BugInstance bug = node.getBug();
    SwingUtilities.invokeLater(() -> {
        summaryTopPanel.removeAll();
        summaryTopPanel.add(mainFrameComponentFactory.bugSummaryComponent(bug.getAbridgedMessage(), bug));
        for (BugAnnotation b : bug.getAnnotationsForMessage(true)) {
            summaryTopPanel.add(mainFrameComponentFactory.bugSummaryComponent(b, bug));
        }
        BugPattern bugPattern = bug.getBugPattern();
        String detailText = bugPattern.getDetailText() + "<br><p> <b>Bug kind and pattern: " + bugPattern.getAbbrev() + " - " + bugPattern.getType();
        String txt = bugPattern.getDetailHTML(detailText);
        summaryHtmlArea.setText(txt);
        summaryTopPanel.add(Box.createVerticalGlue());
        summaryTopPanel.revalidate();
        SwingUtilities.invokeLater(() -> summaryHtmlScrollPane.getVerticalScrollBar().setValue(summaryHtmlScrollPane.getVerticalScrollBar().getMinimum()));
    });
}
Also used : BugInstance(edu.umd.cs.findbugs.BugInstance) BugPattern(edu.umd.cs.findbugs.BugPattern) BugAnnotation(edu.umd.cs.findbugs.BugAnnotation)

Example 3 with BugPattern

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

the class SarifBugReporterTest method testSourceLocation.

@Test
public void testSourceLocation() throws IOException {
    Path tmpDir = Files.createTempDirectory("spotbugs");
    new File(tmpDir.toFile(), "SampleClass.java").createNewFile();
    SourceFinder sourceFinder = reporter.getProject().getSourceFinder();
    sourceFinder.setSourceBaseList(Collections.singleton(tmpDir.toString()));
    BugPattern bugPattern = new BugPattern("TYPE", "abbrev", "category", false, "shortDescription", "longDescription", "detailText", "https://example.com/help.html", 0);
    DetectorFactoryCollection.instance().registerBugPattern(bugPattern);
    reporter.reportBug(new BugInstance(bugPattern.getType(), bugPattern.getPriorityAdjustment()).addInt(10).addClass("SampleClass"));
    reporter.finish();
    String json = writer.toString();
    JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);
    JsonObject run = jsonObject.getAsJsonArray("runs").get(0).getAsJsonObject();
    JsonObject originalUriBaseIds = run.getAsJsonObject("originalUriBaseIds");
    String uriBaseId = takeFirstKey(originalUriBaseIds).get();
    assertThat(URI.create(originalUriBaseIds.getAsJsonObject(uriBaseId).get("uri").getAsString()), is(tmpDir.toUri()));
    JsonArray results = run.getAsJsonArray("results");
    assertThat(results.size(), is(1));
    JsonObject result = results.get(0).getAsJsonObject();
    JsonObject artifactLocation = result.getAsJsonArray("locations").get(0).getAsJsonObject().getAsJsonObject("physicalLocation").getAsJsonObject("artifactLocation");
    String relativeUri = artifactLocation.get("uri").getAsString();
    assertThat("relative URI that can be resolved by the uriBase", relativeUri, is("SampleClass.java"));
    assertThat(artifactLocation.get("uriBaseId").getAsString(), is(uriBaseId));
}
Also used : Path(java.nio.file.Path) JsonArray(com.google.gson.JsonArray) SourceFinder(edu.umd.cs.findbugs.ba.SourceFinder) BugInstance(edu.umd.cs.findbugs.BugInstance) JsonObject(com.google.gson.JsonObject) Gson(com.google.gson.Gson) BugPattern(edu.umd.cs.findbugs.BugPattern) File(java.io.File) Test(org.junit.Test)

Example 4 with BugPattern

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

the class SarifBugReporterTest method testRuleWithArguments.

@Test
public void testRuleWithArguments() {
    // given
    final String EXPECTED_BUG_TYPE = "BUG_TYPE";
    final int EXPECTED_PRIORITY = Priorities.NORMAL_PRIORITY;
    final String EXPECTED_DESCRIPTION = "describing about this bug type...";
    BugPattern bugPattern = new BugPattern(EXPECTED_BUG_TYPE, "abbrev", "category", false, EXPECTED_DESCRIPTION, "describing about this bug type with value {0}...", "detailText", null, 0);
    DetectorFactoryCollection.instance().registerBugPattern(bugPattern);
    // when
    reporter.reportBug(new BugInstance(bugPattern.getType(), bugPattern.getPriorityAdjustment()).addInt(10).addClass("the/target/Class"));
    reporter.finish();
    // then
    String json = writer.toString();
    JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);
    JsonObject run = jsonObject.getAsJsonArray("runs").get(0).getAsJsonObject();
    JsonArray rules = run.getAsJsonObject("tool").getAsJsonObject("driver").getAsJsonArray("rules");
    JsonArray results = run.getAsJsonArray("results");
    assertThat(rules.size(), is(1));
    JsonObject rule = rules.get(0).getAsJsonObject();
    assertThat(rule.get("id").getAsString(), is(bugPattern.getType()));
    String defaultText = rule.getAsJsonObject("messageStrings").getAsJsonObject("default").get("text").getAsString();
    assertThat(defaultText, is("describing about this bug type with value {0}..."));
    assertThat(results.size(), is(1));
    JsonObject result = results.get(0).getAsJsonObject();
    assertThat(result.get("ruleId").getAsString(), is(bugPattern.getType()));
    JsonObject message = result.getAsJsonObject("message");
    assertThat(message.get("id").getAsString(), is("default"));
    assertThat(message.get("text").getAsString(), is(bugPattern.getShortDescription()));
    JsonArray arguments = message.getAsJsonArray("arguments");
    assertThat(arguments.get(0).getAsInt(), is(10));
}
Also used : JsonArray(com.google.gson.JsonArray) BugInstance(edu.umd.cs.findbugs.BugInstance) JsonObject(com.google.gson.JsonObject) Gson(com.google.gson.Gson) BugPattern(edu.umd.cs.findbugs.BugPattern) Test(org.junit.Test)

Example 5 with BugPattern

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

the class PrintBugDescriptions method print.

public void print() throws IOException {
    // Ensure bug patterns are loaded
    DetectorFactoryCollection factories = DetectorFactoryCollection.instance();
    // Find all bug patterns reported by at least one non-disabled detector.
    Collection<BugPattern> enabledPatternSet = new HashSet<BugPattern>();
    for (Iterator<DetectorFactory> i = factories.factoryIterator(); i.hasNext(); ) {
        DetectorFactory factory = i.next();
        if (isEnabled(factory)) {
            enabledPatternSet.addAll(factory.getReportedBugPatterns());
        }
    }
    prologue();
    Iterator<BugPattern> i = DetectorFactoryCollection.instance().bugPatternIterator();
    while (i.hasNext()) {
        BugPattern bugPattern = i.next();
        if (!enabledPatternSet.contains(bugPattern)) {
            continue;
        }
        emit(bugPattern);
    }
    epilogue();
}
Also used : DetectorFactory(edu.umd.cs.findbugs.DetectorFactory) BugPattern(edu.umd.cs.findbugs.BugPattern) DetectorFactoryCollection(edu.umd.cs.findbugs.DetectorFactoryCollection) HashSet(java.util.HashSet)

Aggregations

BugPattern (edu.umd.cs.findbugs.BugPattern)24 BugInstance (edu.umd.cs.findbugs.BugInstance)6 Test (org.junit.Test)6 BugCode (edu.umd.cs.findbugs.BugCode)5 Gson (com.google.gson.Gson)4 JsonArray (com.google.gson.JsonArray)4 JsonObject (com.google.gson.JsonObject)4 DetectorFactory (edu.umd.cs.findbugs.DetectorFactory)4 HashSet (java.util.HashSet)3 AbstractFindBugsTest (de.tobject.findbugs.test.AbstractFindBugsTest)2 DetectorFactoryCollection (edu.umd.cs.findbugs.DetectorFactoryCollection)2 PrintStream (java.io.PrintStream)2 TreeSet (java.util.TreeSet)2 Nonnull (javax.annotation.Nonnull)2 FindbugsPlugin (de.tobject.findbugs.FindbugsPlugin)1 BugContentProvider (de.tobject.findbugs.view.explorer.BugContentProvider)1 FilterBugsDialog (de.tobject.findbugs.view.explorer.FilterBugsDialog)1 AppVersion (edu.umd.cs.findbugs.AppVersion)1 BugAnnotation (edu.umd.cs.findbugs.BugAnnotation)1 Plugin (edu.umd.cs.findbugs.Plugin)1