Java Code Examples for edu.umd.cs.findbugs.BugInstance#getPrimarySourceLineAnnotation()

The following examples show how to use edu.umd.cs.findbugs.BugInstance#getPrimarySourceLineAnnotation() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Creates bug summary component. If obj is a string will create a JLabel
 * with that string as it's text and return it. If obj is an annotation will
 * return a JLabel with the annotation's toString(). If that annotation is a
 * SourceLineAnnotation or has a SourceLineAnnotation connected to it and
 * the source file is available will attach a listener to the label.
 */
public Component bugSummaryComponent(String str, BugInstance bug) {
    JLabel label = new JLabel();
    label.setFont(label.getFont().deriveFont(Driver.getFontSize()));
    label.setFont(label.getFont().deriveFont(Font.PLAIN));
    label.setForeground(Color.BLACK);

    label.setText(str);

    SourceLineAnnotation link = bug.getPrimarySourceLineAnnotation();
    if (link != null) {
        label.addMouseListener(new BugSummaryMouseListener(bug, label, link));
    }

    return label;
}
 
Example 2
@Override
public void doReportBug(BugInstance bugInstance) {
    if(includeCategories.size() > 0 && !includeCategories.contains(bugInstance.getCategoryAbbrev())) {
        return;
    }

    StringBuilder bugDetail = new StringBuilder();
    bugDetail
            .append("\n------------------------------------------------------")
            .append("\nNew Bug Instance: [" + ++bugInstanceCount + "]")
            .append("\n  message=" + bugInstance.getMessage())
            .append("\n  bugType=" + bugInstance.getBugPattern().getType())
            .append("  priority=" + bugInstance.getPriorityString())
            .append("  category=" + bugInstance.getCategoryAbbrev());
    if (bugInstance.getPrimaryClass() != null) {
        bugDetail.append("\n  class=" + bugInstance.getPrimaryClass().getClassName());
    }
    if (bugInstance.getPrimaryMethod() != null) {
        bugDetail.append("  method=" + bugInstance.getPrimaryMethod().getMethodName());
    }
    if (bugInstance.getPrimaryField() != null) {
        bugDetail.append("  field=" + bugInstance.getPrimaryField().getFieldName());
    }
    if (bugInstance.getPrimarySourceLineAnnotation() != null) {
        bugDetail.append("  line=" + bugInstance.getPrimarySourceLineAnnotation().getStartLine());
    }
    bugDetail.append("\n------------------------------------------------------");
    log.info(bugDetail.toString());
    //bugCollection.add(bugInstance);
}
 
Example 3
Source Project: analysis-model   File: FindBugsParser.java    License: MIT License 5 votes vote down vote up
private Report convertBugsToIssues(final Collection<String> sources, final IssueBuilder builder,
        final Map<String, String> hashToMessageMapping, final Map<String, String> categories,
        final SortedBugCollection collection, final Project project) {
    project.addSourceDirs(sources);

    try (SourceFinder sourceFinder = new SourceFinder(project)) {
        if (StringUtils.isNotBlank(project.getProjectName())) {
            builder.setModuleName(project.getProjectName());
        }

        Collection<BugInstance> bugs = collection.getCollection();

        Report report = new Report();
        for (BugInstance warning : bugs) {
            SourceLineAnnotation sourceLine = warning.getPrimarySourceLineAnnotation();

            String message = warning.getMessage();
            String type = warning.getType();
            String category = categories.get(type);
            if (category == null) { // alternately, only if warning.getBugPattern().getType().equals("UNKNOWN")
                category = warning.getBugPattern().getCategory();
            }
            builder.setSeverity(getPriority(warning))
                    .setMessage(createMessage(hashToMessageMapping, warning, message))
                    .setCategory(category)
                    .setType(type)
                    .setLineStart(sourceLine.getStartLine())
                    .setLineEnd(sourceLine.getEndLine())
                    .setFileName(findSourceFile(sourceFinder, sourceLine))
                    .setPackageName(warning.getPrimaryClass().getPackageName())
                    .setFingerprint(warning.getInstanceHash());
            setAffectedLines(warning, builder,
                    new LineRange(sourceLine.getStartLine(), sourceLine.getEndLine()));

            report.add(builder.build());
        }
        return report;
    }
}
 
Example 4
Source Project: sputnik   File: CollectorBugReporter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doReportBug(BugInstance bugInstance) {
    SourceLineAnnotation primarySourceLineAnnotation = bugInstance.getPrimarySourceLineAnnotation();
    int line = primarySourceLineAnnotation.getStartLine();
    if (line < 0) {
        line = 0;
    }
    Violation violation = new Violation(primarySourceLineAnnotation.getClassName(), line, bugInstance.getMessage(),
            convert(bugInstance.getPriority()));
    log.debug("Violation found: {}", violation);
    reviewResult.add(violation);
}
 
Example 5
/**
 * Get the underlying resource (Java class) for given BugInstance.
 *
 * @param bug
 *            the BugInstance
 * @param project
 *            the project
 * @return the IResource representing the Java class
 */
private static @CheckForNull IJavaElement getJavaElement(BugInstance bug, IJavaProject project) throws JavaModelException {

    SourceLineAnnotation primarySourceLineAnnotation = bug.getPrimarySourceLineAnnotation();
    String qualifiedClassName = primarySourceLineAnnotation.getClassName();

    //        if (Reporter.DEBUG) {
    //            System.out.println("Looking up class: " + packageName + ", " + qualifiedClassName);
    //        }

    Matcher m = fullName.matcher(qualifiedClassName);
    IType type;
    String innerName = null;
    if (m.matches() && m.group(2).length() > 0) {

        String outerQualifiedClassName = m.group(1).replace('$', '.');
        innerName = m.group(2).substring(1);
        // second argument is required to find also secondary types
        type = project.findType(outerQualifiedClassName, (IProgressMonitor) null);

        /*
         * code below only points to the first line of inner class even if
         * this is not a class bug but field bug
         */
        if (type != null && !hasLineInfo(primarySourceLineAnnotation)) {
            completeInnerClassInfo(qualifiedClassName, innerName, type, bug);
        }
    } else {
        // second argument is required to find also secondary types
        type = project.findType(qualifiedClassName.replace('$', '.'), (IProgressMonitor) null);

        // for inner classes, some detectors does not properly report source
        // lines:
        // instead of reporting the first line of inner class, they report
        // first line of parent class
        // in this case we will try to fix this here and point to the right
        // start line
        if (type != null && type.isMember()) {
            if (!hasLineInfo(primarySourceLineAnnotation)) {
                completeInnerClassInfo(qualifiedClassName, type.getElementName(), type, bug);
            }
        }
    }

    // reassign it as it may be changed for inner classes
    primarySourceLineAnnotation = bug.getPrimarySourceLineAnnotation();

    /*
     * Eclipse can help us find the line number for fields => we trying to
     * add line info for fields here
     */
    int startLine = primarySourceLineAnnotation.getStartLine();
    // TODO don't use "1", use "0" ?
    if (startLine <= 1 && type != null) {
        FieldAnnotation primaryField = bug.getPrimaryField();
        if (primaryField != null) {
            completeFieldInfo(qualifiedClassName, type, bug, primaryField);
        }
    }

    return type;
}
 
Example 6
FileBugHash(BugCollection bugs) {

        for (PackageStats pStat : bugs.getProjectStats().getPackageStats()) {
            for (ClassStats cStat : pStat.getSortedClassStats()) {
                String path = cStat.getName();
                if (path.indexOf('.') == -1) {
                    path = cStat.getSourceFile();
                } else {
                    path = path.substring(0, path.lastIndexOf('.') + 1).replace('.', '/') + cStat.getSourceFile();
                }
                counts.put(path, 0);
                Integer size = sizes.get(path);
                if (size == null) {
                    size = 0;
                }
                sizes.put(path, size + cStat.size());
            }
        }
        for (BugInstance bug : bugs.getCollection()) {
            SourceLineAnnotation source = bug.getPrimarySourceLineAnnotation();

            String packagePath = source.getPackageName().replace('.', '/');
            String key;
            if (packagePath.length() == 0) {
                key = source.getSourceFile();
            } else {
                key = packagePath + "/" + source.getSourceFile();
            }
            StringBuilder buf = hashes.get(key);
            if (buf == null) {
                buf = new StringBuilder();
                hashes.put(key, buf);
            }
            buf.append(bug.getInstanceKey()).append("-").append(source.getStartLine()).append(".")
                    .append(source.getStartBytecode()).append(" ");
            Integer count = counts.get(key);
            if (count == null) {
                counts.put(key, 1);
            } else {
                counts.put(key, 1 + count);
            }
        }
    }