edu.umd.cs.findbugs.SourceLineAnnotation Java Examples

The following examples show how to use edu.umd.cs.findbugs.SourceLineAnnotation. 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
Source File: PreferZeroLengthArrays.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void visit(Code obj) {
    found.clear();
    // Solution to sourceforge bug 1765925; returning null is the
    // convention used by java.io.File.listFiles()
    if ("listFiles".equals(getMethodName())) {
        return;
    }
    String returnType = getMethodSig().substring(getMethodSig().indexOf(')') + 1);
    if (returnType.startsWith("[")) {
        nullOnTOS = false;
        super.visit(obj);
        if (!found.isEmpty()) {
            BugInstance bug = new BugInstance(this, "PZLA_PREFER_ZERO_LENGTH_ARRAYS", LOW_PRIORITY).addClassAndMethod(this);
            for (SourceLineAnnotation s : found) {
                bug.add(s);
            }
            bugReporter.reportBug(bug);
            found.clear();
        }
    }
}
 
Example #2
Source File: SwitchFallthrough.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void foundSwitchNoDefault(SourceLineAnnotation s) {
    LineNumberTable table = getCode().getLineNumberTable();

    if (table != null) {
        int startLine = s.getStartLine();
        int prev = Integer.MIN_VALUE;
        for (LineNumber ln : table.getLineNumberTable()) {
            int thisLineNumber = ln.getLineNumber();
            if (thisLineNumber < startLine && thisLineNumber > prev && ln.getStartPC() < s.getStartBytecode()) {
                prev = thisLineNumber;
            }
        }
        int diff = startLine - prev;
        if (diff > 5) {
            return;
        }

        bugAccumulator.accumulateBug(new BugInstance(this, "SF_SWITCH_NO_DEFAULT", NORMAL_PRIORITY).addClassAndMethod(this),
                s);
    }

}
 
Example #3
Source File: SourceSearcher.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public boolean findSource0(SourceLineAnnotation srcLine) {
    if (srcLine == null) {
        return false;
    }
    String cName = srcLine.getClassName();
    if (sourceFound.contains(cName)) {
        return true;
    }
    if (sourceNotFound.contains(cName)) {
        return false;
    }

    try {
        InputStream in = sourceFinder.openSource(srcLine);
        in.close();
        sourceFound.add(cName);
        return true;
    } catch (IOException e1) {
        sourceNotFound.add(cName);
        return false;
    }
}
 
Example #4
Source File: FindDeadLocalStores.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * If feature is enabled, suppress warnings where there is at least one live
 * store on the line where the warning would be reported.
 *
 * @param accumulator
 *            BugAccumulator containing warnings for method
 * @param liveStoreSourceLineSet
 *            bitset of lines where at least one live store was seen
 */
private void suppressWarningsIfOneLiveStoreOnLine(BugAccumulator accumulator, BitSet liveStoreSourceLineSet) {
    if (!SUPPRESS_IF_AT_LEAST_ONE_LIVE_STORE_ON_LINE) {
        return;
    }

    // Eliminate any accumulated warnings for instructions
    // that (due to inlining) *can* be live stores.
    entryLoop: for (Iterator<? extends BugInstance> i = accumulator.uniqueBugs().iterator(); i.hasNext();) {

        for (SourceLineAnnotation annotation : accumulator.locations(i.next())) {
            if (liveStoreSourceLineSet.get(annotation.getStartLine())) {
                // This instruction can be a live store; don't report
                // it as a warning.
                i.remove();
                continue entryLoop;
            }
        }
    }
}
 
Example #5
Source File: MainFrameComponentFactory.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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 #6
Source File: PreferZeroLengthArrays.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void sawOpcode(int seen) {

    switch (seen) {
    case Const.ACONST_NULL:
        nullOnTOS = true;
        return;
    case Const.ARETURN:
        if (nullOnTOS) {
            SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(getClassContext(), this,
                    getPC());
            if (sourceLineAnnotation != null) {
                found.add(sourceLineAnnotation);
            }
        }
        break;
    default:
        break;
    }
    nullOnTOS = false;
}
 
Example #7
Source File: SourceCodeDisplay.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * @param src
 * @param sourceAnnotation
 */
private void highlight(JavaSourceDocument src, SourceLineAnnotation sourceAnnotation, Color color) {

    int startLine = sourceAnnotation.getStartLine();
    if (startLine == -1) {
        return;
    }
    String sourceFile = sourceAnnotation.getSourcePath();
    String sourceFile2 = src.getSourceFile().getFullFileName();
    if (!java.io.File.separator.equals(String.valueOf(SourceLineAnnotation.CANONICAL_PACKAGE_SEPARATOR))) {
        sourceFile2 = sourceFile2.replace(java.io.File.separatorChar, SourceLineAnnotation.CANONICAL_PACKAGE_SEPARATOR);
    }
    if (!sourceFile2.endsWith(sourceFile)) {
        return;
    }
    src.getHighlightInformation().setHighlight(startLine, sourceAnnotation.getEndLine(), color);
}
 
Example #8
Source File: SourceMatcherTest.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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));
}
 
Example #9
Source File: SourceMatcherTest.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testRealPathMatchWithRegexpAndAnalysisContext() 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));

    // setup test analysis context
    AnalysisContext.setCurrentAnalysisContext(new AnalysisContext(testProject));

    // regexp match source folder with analysis context
    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));
}
 
Example #10
Source File: FindBugsParser.java    From analysis-model with MIT License 6 votes vote down vote up
private void setAffectedLines(final BugInstance warning, final IssueBuilder builder,
        final LineRange primary) {
    Iterator<BugAnnotation> annotationIterator = warning.annotationIterator();
    LineRangeList lineRanges = new LineRangeList();
    while (annotationIterator.hasNext()) {
        BugAnnotation bugAnnotation = annotationIterator.next();
        if (bugAnnotation instanceof SourceLineAnnotation) {
            SourceLineAnnotation annotation = (SourceLineAnnotation) bugAnnotation;
            LineRange lineRange = new LineRange(annotation.getStartLine(), annotation.getEndLine());
            if (!lineRanges.contains(lineRange) && !primary.equals(lineRange)) {
                lineRanges.add(lineRange);
            }
        }
    }
    builder.setLineRanges(lineRanges);
}
 
Example #11
Source File: MarkerUtil.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static void completeInnerClassInfo(String qualifiedClassName, String innerName, @Nonnull IType type, BugInstance bug)
        throws JavaModelException {
    int lineNbr = findChildSourceLine(type, innerName, bug);
    if (lineNbr > 0) {
        String sourceFileStr = getSourceFileHint(type, qualifiedClassName);
        if (sourceFileStr != null && sourceFileStr.length() > 0) {
            bug.addSourceLine(new SourceLineAnnotation(qualifiedClassName, sourceFileStr, lineNbr, lineNbr, 0, 0));
            if (Reporter.DEBUG) {
                System.out.println("1. Fixed start line to: " + lineNbr + " on " + qualifiedClassName + "$" + innerName);
            }
        }
    }
}
 
Example #12
Source File: SynchronizationOnSharedBuiltinConstant.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void accumulateBug() {
    if (pendingBug == null) {
        return;
    }
    bugAccumulator.accumulateBug(pendingBug, SourceLineAnnotation.fromVisitedInstruction(this, monitorEnterPC));
    pendingBug = null;
}
 
Example #13
Source File: AnalysisContext.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Lookup a class's source file
 *
 * @param dottedClassName
 *            the name of the class
 * @return the source file for the class, or
 *         {@link SourceLineAnnotation#UNKNOWN_SOURCE_FILE} if unable to
 *         determine
 */
public final String lookupSourceFile(@Nonnull @DottedClassName String dottedClassName) {
    requireNonNull(dottedClassName, "className is null");
    try {
        XClass xClass = Global.getAnalysisCache().getClassAnalysis(XClass.class,
                DescriptorFactory.createClassDescriptorFromDottedClassName(dottedClassName));
        String name = xClass.getSource();
        if (name == null) {
            return SourceLineAnnotation.UNKNOWN_SOURCE_FILE;
        }
        return name;
    } catch (CheckedAnalysisException e) {
        return SourceLineAnnotation.UNKNOWN_SOURCE_FILE;
    }
}
 
Example #14
Source File: FindUnreleasedLock.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void inspectResult(ClassContext classContext, MethodGen methodGen, CFG cfg,
        Dataflow<ResourceValueFrame, ResourceValueAnalysis<Lock>> dataflow, Lock resource) {

    JavaClass javaClass = classContext.getJavaClass();

    ResourceValueFrame exitFrame = dataflow.getResultFact(cfg.getExit());
    if (DEBUG) {
        System.out.println("Resource value at exit: " + exitFrame);
    }
    int exitStatus = exitFrame.getStatus();

    if (exitStatus == ResourceValueFrame.OPEN || exitStatus == ResourceValueFrame.OPEN_ON_EXCEPTION_PATH) {
        String bugType;
        int priority;
        if (exitStatus == ResourceValueFrame.OPEN) {
            bugType = "UL_UNRELEASED_LOCK";
            priority = HIGH_PRIORITY;
        } else {
            bugType = "UL_UNRELEASED_LOCK_EXCEPTION_PATH";
            priority = NORMAL_PRIORITY;
        }

        String sourceFile = javaClass.getSourceFileName();
        Location location = resource.getLocation();
        InstructionHandle handle = location.getHandle();
        InstructionHandle nextInstruction = handle.getNext();
        if (nextInstruction.getInstruction() instanceof RETURN) {
            return; // don't report as error; intentional
        }
        bugAccumulator.accumulateBug(new BugInstance(this, bugType, priority).addClassAndMethod(methodGen, sourceFile),
                SourceLineAnnotation.fromVisitedInstruction(classContext, methodGen, sourceFile, handle));
    }
}
 
Example #15
Source File: IDivResultCastToDouble.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void sawOpcode(int seen) {

    if (DEBUG) {
        System.out.println("Saw opcode " + Const.getOpcodeName(seen) + " " + pendingIdivCastToDivBugLocation);
    }

    if ((prevOpCode == Const.I2D || prevOpCode == Const.L2D) && seen == Const.INVOKESTATIC && ClassName.isMathClass(getClassConstantOperand())
            && "ceil".equals(getNameConstantOperand())) {
        bugAccumulator
                .accumulateBug(new BugInstance(this, "ICAST_INT_CAST_TO_DOUBLE_PASSED_TO_CEIL", HIGH_PRIORITY)
                        .addClassAndMethod(this), this);
        pendingIdivCastToDivBugLocation = null;
    } else if ((prevOpCode == Const.I2F || prevOpCode == Const.L2F) && seen == Const.INVOKESTATIC
            && ClassName.isMathClass(getClassConstantOperand()) && "round".equals(getNameConstantOperand())) {
        bugAccumulator.accumulateBug(
                new BugInstance(this, "ICAST_INT_CAST_TO_FLOAT_PASSED_TO_ROUND", NORMAL_PRIORITY).addClassAndMethod(this),
                this);
        pendingIdivCastToDivBugLocation = null;
    } else if (pendingIdivCastToDivBugLocation != null) {
        bugAccumulator.accumulateBug(
                new BugInstance(this, "ICAST_IDIV_CAST_TO_DOUBLE", NORMAL_PRIORITY).addClassAndMethod(this),
                pendingIdivCastToDivBugLocation);
        pendingIdivCastToDivBugLocation = null;
    }

    if (prevOpCode == Const.IDIV && (seen == Const.I2D || seen == Const.I2F) || prevOpCode == Const.LDIV && (seen == Const.L2D
            || seen == Const.L2F)) {
        pendingIdivCastToDivBugLocation = SourceLineAnnotation.fromVisitedInstruction(this);
    }
    prevOpCode = seen;
}
 
Example #16
Source File: FindRefComparison.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
WarningWithProperties(BugInstance warning, WarningPropertySet<WarningProperty> propertySet,
        SourceLineAnnotation sourceLine, Location location) {
    this.instance = warning;
    this.propertySet = propertySet;
    this.sourceLine = sourceLine;
    this.location = location;
}
 
Example #17
Source File: FindFloatEquality.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Code obj) {
    found.clear();
    priority = LOW_PRIORITY;

    state = SAW_NOTHING;

    super.visit(obj);
    bugAccumulator.reportAccumulatedBugs();
    if (!found.isEmpty()) {
        BugInstance bug = new BugInstance(this, "FE_FLOATING_POINT_EQUALITY", priority).addClassAndMethod(this);

        boolean first = true;
        for (SourceLineAnnotation s : found) {
            bug.add(s);
            if (first) {
                first = false;
            } else {
                bug.describe(SourceLineAnnotation.ROLE_ANOTHER_INSTANCE);
            }
        }

        bugReporter.reportBug(bug);

        found.clear();
    }
}
 
Example #18
Source File: FindRefComparison.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void handleSuspiciousRefComparison(JavaClass jclass, Method method, MethodGen methodGen,
        List<WarningWithProperties> refComparisonList, Location location, String lhs, ReferenceType lhsType,
        ReferenceType rhsType) {
    XField xf = null;
    if (lhsType instanceof FinalConstant) {
        xf = ((FinalConstant) lhsType).getXField();
    } else if (rhsType instanceof FinalConstant) {
        xf = ((FinalConstant) rhsType).getXField();
    }
    String sourceFile = jclass.getSourceFileName();
    String bugPattern = "RC_REF_COMPARISON";
    int priority = Priorities.HIGH_PRIORITY;
    if ("java.lang.Boolean".equals(lhs)) {
        bugPattern = "RC_REF_COMPARISON_BAD_PRACTICE_BOOLEAN";
        priority = Priorities.NORMAL_PRIORITY;
    } else if (xf != null && xf.isStatic() && xf.isFinal()) {
        bugPattern = "RC_REF_COMPARISON_BAD_PRACTICE";
        if (xf.isPublic() || !methodGen.isPublic()) {
            priority = Priorities.NORMAL_PRIORITY;
        }
    }
    BugInstance instance = new BugInstance(this, bugPattern, priority).addClassAndMethod(methodGen, sourceFile)
            .addType("L" + lhs.replace('.', '/') + ";").describe(TypeAnnotation.FOUND_ROLE);
    if (xf != null) {
        instance.addField(xf).describe(FieldAnnotation.LOADED_FROM_ROLE);
    } else {
        instance.addSomeSourceForTopTwoStackValues(classContext, method, location);
    }
    SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext, methodGen,
            sourceFile, location.getHandle());

    refComparisonList.add(new WarningWithProperties(instance, new WarningPropertySet<>(),
            sourceLineAnnotation, location));
}
 
Example #19
Source File: SwitchFallthrough.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Code obj) {
    if (DEBUG) {
        System.out.printf("%nVisiting %s%n", getMethodDescriptor());
    }
    reachable = false;
    lastPC = 0;
    biggestJumpTarget = -1;
    found.clear();
    switchHdlr = new SwitchHandler();
    clearAllDeadStores();
    deadStore = null;
    priority = NORMAL_PRIORITY;
    fallthroughDistance = 1000;
    enumType = null;
    super.visit(obj);
    enumType = null;
    if (!found.isEmpty()) {
        if (found.size() >= 4 && priority == NORMAL_PRIORITY) {
            priority = LOW_PRIORITY;
        }
        for (SourceLineAnnotation s : found) {
            bugAccumulator.accumulateBug(new BugInstance(this, "SF_SWITCH_FALLTHROUGH", priority).addClassAndMethod(this), s);
        }
    }

    bugAccumulator.reportAccumulatedBugs();
}
 
Example #20
Source File: DontUseEnum.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(LocalVariable obj) {
    if (isReservedName(obj.getName())) {
        LocalVariableAnnotation var = new LocalVariableAnnotation(obj.getName(), obj.getIndex(), obj.getStartPC());
        SourceLineAnnotation source = SourceLineAnnotation.fromVisitedInstruction(getClassContext(), this, obj.getStartPC());
        BugInstance bug = new BugInstance(this, "NM_FUTURE_KEYWORD_USED_AS_IDENTIFIER", NORMAL_PRIORITY)
                .addClassAndMethod(this).add(var).add(source);
        bugReporter.reportBug(bug);
    }
}
 
Example #21
Source File: FindInconsistentSync2.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static Collection<SourceLineAnnotation> asSourceLineAnnotation(Collection<FieldAccess> c) {
    ArrayList<SourceLineAnnotation> result = new ArrayList<>(c.size());
    for (FieldAccess f : c) {
        result.add(f.asSourceLineAnnotation());
    }
    return result;
}
 
Example #22
Source File: FindNullDeref.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void examineReturnInstruction(Location location) throws DataflowAnalysisException, CFGBuilderException {
    if (DEBUG_NULLRETURN) {
        System.out.println("Checking null return at " + location);
    }

    IsNullValueDataflow invDataflow = classContext.getIsNullValueDataflow(method);
    IsNullValueFrame frame = invDataflow.getFactAtLocation(location);
    ValueNumberFrame vnaFrame = classContext.getValueNumberDataflow(method).getFactAtLocation(location);
    if (!vnaFrame.isValid()) {
        return;
    }
    ValueNumber valueNumber = vnaFrame.getTopValue();
    if (!frame.isValid()) {
        return;
    }
    IsNullValue tos = frame.getTopValue();
    if (tos.isDefinitelyNull()) {
        BugAnnotation variable = ValueNumberSourceInfo.findAnnotationFromValueNumber(method, location, valueNumber, vnaFrame,
                "VALUE_OF");

        String bugPattern = "NP_NONNULL_RETURN_VIOLATION";
        int priority = NORMAL_PRIORITY;
        if (tos.isDefinitelyNull() && !tos.isException()) {
            priority = HIGH_PRIORITY;
        }
        String methodName = method.getName();
        if ("clone".equals(methodName)) {
            bugPattern = "NP_CLONE_COULD_RETURN_NULL";
            priority = NORMAL_PRIORITY;
        } else if ("toString".equals(methodName)) {
            bugPattern = "NP_TOSTRING_COULD_RETURN_NULL";
            priority = NORMAL_PRIORITY;
        }
        BugInstance warning = new BugInstance(this, bugPattern, priority).addClassAndMethod(classContext.getJavaClass(),
                method).addOptionalAnnotation(variable);
        bugAccumulator.accumulateBug(warning, SourceLineAnnotation.fromVisitedInstruction(classContext, method, location));
    }
}
 
Example #23
Source File: SourceSearcher.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public boolean findSource(SourceLineAnnotation srcLine) {
    if (srcLine == null) {
        return false;
    }
    String cName = srcLine.getClassName();
    if (sourceFound.contains(cName)) {
        return true;
    }
    if (sourceNotFound.contains(cName)) {
        return false;
    }

    boolean result = sourceFinder.hasSourceFile(srcLine);
    return result;
}
 
Example #24
Source File: InjectionSink.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Adds lines with tainted source or path for reporting
 * 
 * @param locations collection of locations used to extract lines
 */
public void addLines(Collection<TaintLocation> locations) {
    Objects.requireNonNull(detector, "locations");
    for (TaintLocation location : locations) {
        lines.add(SourceLineAnnotation.fromVisitedInstruction(
            location.getMethodDescriptor(), location.getPosition()));
    }
}
 
Example #25
Source File: SourceFinder.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static String getOrGuessSourceFile(SourceLineAnnotation source) {
    if (source.isSourceFileKnown()) {
        return source.getSourceFile();
    }
    String baseClassName = source.getClassName();
    int i = baseClassName.lastIndexOf('.');
    baseClassName = baseClassName.substring(i + 1);
    int j = baseClassName.indexOf('$');
    if (j >= 0) {
        baseClassName = baseClassName.substring(0, j);
    }
    return baseClassName + ".java";
}
 
Example #26
Source File: SourceCodeDisplay.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void run() {
    frame.getSourceCodeTextPane().setEditorKit(src.getEditorKit());
    StyledDocument document = src.getDocument();
    frame.getSourceCodeTextPane().setDocument(document);
    String sourceFile = mySourceLine.getSourceFile();
    if (sourceFile == null || "<Unknown>".equals(sourceFile)) {
        sourceFile = mySourceLine.getSimpleClassName();
    }
    int startLine = mySourceLine.getStartLine();
    int endLine = mySourceLine.getEndLine();
    frame.setSourceTab(sourceFile + " in " + mySourceLine.getPackageName(), myBug);

    int originLine = (startLine + endLine) / 2;
    LinkedList<Integer> otherLines = new LinkedList<>();
    // show(frame.getSourceCodeTextPane(), document,
    // thisSource);
    for (Iterator<BugAnnotation> i = myBug.annotationIterator(); i.hasNext();) {
        BugAnnotation annotation = i.next();
        if (annotation instanceof SourceLineAnnotation) {
            SourceLineAnnotation sourceAnnotation = (SourceLineAnnotation) annotation;
            if (sourceAnnotation != mySourceLine) {
                // show(frame.getSourceCodeTextPane(),
                // document, sourceAnnotation);
                int otherLine = sourceAnnotation.getStartLine();
                if (otherLine > originLine) {
                    otherLine = sourceAnnotation.getEndLine();
                }
                otherLines.add(otherLine);
            }
        }
    }

    if (startLine >= 0 && endLine >= 0) {
        frame.getSourceCodeTextPane().scrollLinesToVisible(startLine, endLine, otherLines);
    }
}
 
Example #27
Source File: SourceMatcherTest.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void match() throws Exception {
    SourceMatcher sm = new SourceMatcher(fileName);

    // no source set: test incomplete data
    assertFalse(sm.match(bug));

    bug.addClass("bla", null);
    assertFalse(sm.match(bug));

    ClassAnnotation primaryClass = bug.getPrimaryClass();
    primaryClass.setSourceLines(SourceLineAnnotation.createUnknown("bla", ""));
    assertFalse(sm.match(bug));

    // set right source file
    primaryClass.setSourceLines(SourceLineAnnotation.createUnknown("bla", fileName));

    // exact match
    assertTrue(sm.match(bug));

    // regexp first part
    sm = new SourceMatcher("~bla.*");
    assertTrue(sm.match(bug));

    sm = new SourceMatcher("~blup.*");
    assertFalse(sm.match(bug));

    // regexp second part
    sm = new SourceMatcher("~.*\\.groovy");
    assertTrue(sm.match(bug));

    sm = new SourceMatcher("~.*\\.java");
    assertFalse(sm.match(bug));
}
 
Example #28
Source File: FindBugsParser.java    From analysis-model with 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 #29
Source File: FindBugsParser.java    From analysis-model with MIT License 5 votes vote down vote up
private String findSourceFile(final SourceFinder sourceFinder, final SourceLineAnnotation sourceLine) {
    try {
        SourceFile sourceFile = sourceFinder.findSourceFile(sourceLine);
        return sourceFile.getFullFileName();
    }
    catch (IOException ignored) {
        return sourceLine.getPackageName().replace(DOT, SLASH) + SLASH + sourceLine.getSourceFile();
    }
}
 
Example #30
Source File: CollectorBugReporter.java    From sputnik with 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);
}