edu.umd.cs.findbugs.Project Java Examples

The following examples show how to use edu.umd.cs.findbugs.Project. 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: AnalyzingDialog.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static void show(@Nonnull final Project project) {
    AnalysisCallback callback = new AnalysisCallback() {
        @Override
        public void analysisFinished(BugCollection results) {
            MainFrame instance = MainFrame.getInstance();
            assert results.getProject() == project;
            instance.setBugCollection(results);
            try {
                instance.releaseDisplayWait();
            } catch (Exception e) {
                Logger.getLogger(AnalyzingDialog.class.getName()).log(Level.FINE, "", e);
            }
        }

        @Override
        public void analysisInterrupted() {
            MainFrame instance = MainFrame.getInstance();
            instance.updateProjectAndBugCollection(null);
            instance.releaseDisplayWait();
        }
    };
    show(project, callback, false);

}
 
Example #2
Source File: UnionResults.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
static public void merge(HashSet<String> hashes, SortedBugCollection into, SortedBugCollection from) {

        for (BugInstance bugInstance : from.getCollection()) {
            if (hashes == null || hashes.add(bugInstance.getInstanceHash())) {
                into.add(bugInstance);
            }
        }
        ProjectStats stats = into.getProjectStats();
        ProjectStats stats2 = from.getProjectStats();
        stats.addStats(stats2);

        Project project = into.getProject();
        Project project2 = from.getProject();
        project.add(project2);

        for (AnalysisError error : from.getErrors()) {
            into.addError(error);
        }

        return;
    }
 
Example #3
Source File: Filter.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
void adjustFilter(Project project, BugCollection collection) {
    suppressionFilter = project.getSuppressionFilter();

    first = getVersionNum(collection, firstAsString, true);
    maybeMutated = getVersionNum(collection, maybeMutatedAsString, true);
    last = getVersionNum(collection, lastAsString, true);
    before = getVersionNum(collection, beforeAsString, true);
    after = getVersionNum(collection, afterAsString, false);
    present = getVersionNum(collection, presentAsString, true);
    absent = getVersionNum(collection, absentAsString, true);

    if (sloppyUniqueSpecified) {
        uniqueSloppy = new TreeSet<>(new SloppyBugComparator());
    }

    long fixed = getVersionNum(collection, fixedAsString, true);
    if (fixed >= 0) {
        last = fixed - 1; // fixed means last on previous sequence (ok
        // if -1)
    }
}
 
Example #4
Source File: MainFrame.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Changes the title based on curProject and saveFile.
 */
public void updateTitle() {
    Project project = getProject();
    String name = project.getProjectName();
    if ((name == null || "".equals(name.trim())) && saveFile != null) {
        name = saveFile.getAbsolutePath();
    }
    if (name == null) {
        name = "";//Project.UNNAMED_PROJECT;
    }
    String oldTitle = this.getTitle();
    String newTitle = TITLE_START_TXT + ("".equals(name.trim()) ? "" : " - " + name);
    if (oldTitle.equals(newTitle)) {
        return;
    }
    this.setTitle(newTitle);
}
 
Example #5
Source File: NewProjectWizard.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void clearProjectSettings(Project p) {
    // First clear p's old files, otherwise we can't remove a file
    // once an analysis has been performed on it
    int numOldFiles = p.getFileCount();
    for (int x = 0; x < numOldFiles; x++) {
        p.removeFile(0);
    }

    int numOldAuxFiles = p.getNumAuxClasspathEntries();
    for (int x = 0; x < numOldAuxFiles; x++) {
        p.removeAuxClasspathEntry(0);
    }

    int numOldSrc = p.getNumSourceDirs();
    for (int x = 0; x < numOldSrc; x++) {
        p.removeSourceDir(0);
    }
}
 
Example #6
Source File: WorkItem.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static void addClassesForFile(IFile file, Map<IPath, IPath> outLocations, Project fbProject) {
    IPath path = file.getLocation();
    IPath srcRoot = getMatchingSourceRoot(path, outLocations);
    if (srcRoot == null) {
        return;
    }
    IPath outputRoot = outLocations.get(srcRoot);
    int firstSegments = path.matchingFirstSegments(srcRoot);
    // add relative path to the output path
    IPath out = outputRoot.append(path.removeFirstSegments(firstSegments));
    String fileName = path.removeFileExtension().lastSegment();
    String namePattern = fileName + "\\.class|" + fileName + "\\$.*\\.class";
    namePattern = addSecondaryTypesToPattern(file, fileName, namePattern);
    File directory = out.removeLastSegments(1).toFile();

    // add parent folder and regexp for file names
    Pattern classNamesPattern = Pattern.compile(namePattern);
    ResourceUtils.addFiles(fbProject, directory, classNamesPattern);
}
 
Example #7
Source File: WorkItem.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void addFilesToProject(Project fbProject, Map<IPath, IPath> outputLocations) {
    IResource res = getCorespondingResource();
    if (res instanceof IProject) {
        for (IPath outDir : outputLocations.values()) {
            fbProject.addFile(outDir.toOSString());
        }
    } else if (res instanceof IFolder) {
        // assumption: this is a source folder.
        boolean added = addClassesForFolder((IFolder) res, outputLocations, fbProject);
        if (!added) {
            // What if this is a class folder???
            addJavaElementPath(fbProject);
        }
    } else if (res instanceof IFile) {
        // ID: 2734173: allow to analyze classes inside archives
        if (Util.isClassFile(res) || Util.isJavaArchive(res)) {
            fbProject.addFile(res.getLocation().toOSString());
        } else if (Util.isJavaFile(res)) {
            addClassesForFile((IFile) res, outputLocations, fbProject);
        }
    } else {
        addJavaElementPath(fbProject);
    }
}
 
Example #8
Source File: MainFrameLoadSaveHelper.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
void loadAnalysis(final File file) {

        Runnable runnable = () -> {
            mainFrame.acquireDisplayWait();
            try {
                Project project = new Project();
                project.setGuiCallback(mainFrame.getGuiCallback());
                project.setCurrentWorkingDirectory(file.getParentFile());
                BugLoader.loadBugs(mainFrame, project, file);
                project.getSourceFinder(); // force source finder to be
                // initialized
                mainFrame.updateBugTree();
            } finally {
                mainFrame.releaseDisplayWait();
            }
        };
        if (EventQueue.isDispatchThread()) {
            new Thread(runnable, "Analysis loading thread").start();
        } else {
            runnable.run();
        }
    }
 
Example #9
Source File: FindBugsWorker.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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();
}
 
Example #10
Source File: MainFrameLoadSaveHelper.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
void loadAnalysis(final URL url) {

        Runnable runnable = () -> {
            mainFrame.acquireDisplayWait();
            try {
                Project project = new Project();
                project.setGuiCallback(mainFrame.getGuiCallback());
                BugLoader.loadBugs(mainFrame, project, url);
                project.getSourceFinder(); // force source finder to be
                // initialized
                mainFrame.updateBugTree();
            } finally {
                mainFrame.releaseDisplayWait();
            }
        };
        if (EventQueue.isDispatchThread()) {
            new Thread(runnable, "Analysis loading thread").start();
        } else {
            runnable.run();
        }
    }
 
Example #11
Source File: MergeSummarizeAndView.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
static public SortedBugCollection union(SortedBugCollection origCollection, SortedBugCollection newCollection) {

        SortedBugCollection result = origCollection.duplicate();

        for (Iterator<BugInstance> i = newCollection.iterator(); i.hasNext();) {
            BugInstance bugInstance = i.next();
            result.add(bugInstance);
        }
        ProjectStats stats = result.getProjectStats();
        ProjectStats stats2 = newCollection.getProjectStats();
        stats.addStats(stats2);

        Project project = result.getProject();
        project.add(newCollection.getProject());

        return result;
    }
 
Example #12
Source File: BugLoader.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Performs an analysis and returns the BugSet created
 *
 * @param p
 *            The Project to run the analysis on
 * @param progressCallback
 *            the progressCallBack is supposed to be supplied by analyzing
 *            dialog, FindBugs supplies progress information while it runs
 *            the analysis
 * @return the bugs found
 * @throws InterruptedException
 * @throws IOException
 */
public static BugCollection doAnalysis(@Nonnull Project p, FindBugsProgress progressCallback) throws IOException,
        InterruptedException {
    StringWriter stringWriter = new StringWriter();
    BugCollectionBugReporter pcb = new BugCollectionBugReporter(p, new PrintWriter(stringWriter, true));
    pcb.setPriorityThreshold(Priorities.LOW_PRIORITY);
    IFindBugsEngine fb = createEngine(p, pcb);
    fb.setUserPreferences(getUserPreferences());
    fb.setProgressCallback(progressCallback);
    fb.setProjectName(p.getProjectName());

    fb.execute();
    String warnings = stringWriter.toString();
    if (warnings.length() > 0) {
        JTextArea tp = new JTextArea(warnings);
        tp.setEditable(false);
        JScrollPane pane = new JScrollPane(tp);
        pane.setPreferredSize(new Dimension(600, 400));
        JOptionPane.showMessageDialog(MainFrame.getInstance(),
                pane, "Analysis errors",
                JOptionPane.WARNING_MESSAGE);
    }

    return pcb.getBugCollection();
}
 
Example #13
Source File: AnalysisRunner.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@CheckReturnValue
private Project createProject(Path[] files) {
    final Project project = new Project();
    project.setProjectName(getClass().getSimpleName());
    if (PLUGIN_JAR != null) {
        try {
            String pluginId = Plugin.addCustomPlugin(PLUGIN_JAR.toURI()).getPluginId();
            project.setPluginStatusTrinary(pluginId, Boolean.TRUE);
        } catch (PluginException e) {
            throw new AssertionError("Failed to load plugin", e);
        }
    }

    for (Path file : files) {
        project.addFile(file.toAbsolutePath().toString());
    }
    for (Path auxClasspathEntry : auxClasspathEntries) {
        project.addAuxClasspathEntry(auxClasspathEntry.toAbsolutePath().toString());
    }
    return project;
}
 
Example #14
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 #15
Source File: SpotbugsGuiTests.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
public static void customAnalysisTest(String[] args) throws Exception {
	Project project = new Project();
	// java.util.List<String> srcDirs = new java.util.ArrayList<>();
	// srcDirs.add("C:\\Program
	// Files\\java-1.8.0-openjdk-1.8.0.191-1.b12.redhat.windows.x86_64\\jre\\lib");
	// srcDirs.add("C:\\Users\\Administrator\\Desktop\\iam-server-master-bin\\libs");
	// project.addSourceDirs(srcDirs);

	File targetDir = new File("C:\\Users\\Administrator\\Desktop\\iam-server-master-bin\\libs");
	for (File f : targetDir.listFiles()) {
		project.addFile(f.getAbsolutePath());
	}

	BugCollection bugs = BugLoader.doAnalysis(project, new PrintAnalyzingProgress(System.out));
	bugs.writeXML("C:\\Users\\Administrator\\Desktop\\test-bugs.xml");
}
 
Example #16
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 #17
Source File: BugLoader.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static @CheckForNull SortedBugCollection loadBugs(MainFrame mainFrame, Project project, File source) {
    if (!source.isFile() || !source.canRead()) {
        JOptionPane.showMessageDialog(mainFrame, "Unable to read " + source);
        return null;
    }
    SortedBugCollection col = new SortedBugCollection(project);
    try {
        col.readXML(source);
        if (col.hasDeadBugs()) {
            addDeadBugMatcher(col);
        }
    } catch (Exception e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(mainFrame, "Could not read " + source + "; " + e.getMessage());
    }
    MainFrame.getInstance().setProjectAndBugCollectionInSwingThread(project, col);
    return col;
}
 
Example #18
Source File: SpotbugsAnalyzerEngine.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
@Override
public void startAnalysis(String[] args) throws Exception {
	Project project = new Project();
	File targetDir = new File("C:\\Users\\Administrator\\Desktop\\iam-server-master-bin\\libs");
	for (File assetFile : targetDir.listFiles()) {
		project.addFile(assetFile.getAbsolutePath());
	}

	// Create engine.
	StringWriter warnWriter = new StringWriter();
	// Do analyses.
	BugCollectionBugReporter reporter = new SpotbugsAnalyzerEngine().doAnalysis(project, warnWriter,
			new PrintAnalyzingProgress(System.out));
	// Has warnings?
	String warnings = warnWriter.toString();
	if (!warnings.isEmpty()) {
		System.out.print(warnings);
	}

	new DefaultHtmlBugExporter().doExport(project, reporter.getBugCollection(),
			new File(("C:\\Users\\Administrator\\Desktop\\test-bugs.xml")));
}
 
Example #19
Source File: AnalyzingDialog.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 *
 * @param project
 *            The Project to analyze
 * @param callback
 *            contains what to do if the analysis is interrupted and what to
 *            do if it finishes normally
 * @param joinThread
 *            Whether or not this constructor should return before the
 *            analysis is complete. If true, the constructor does not return
 *            until the analysis is either finished or interrupted.
 */

public static void show(@Nonnull Project project, AnalysisCallback callback, boolean joinThread) {
    AnalyzingDialog dialog = new AnalyzingDialog(project, callback, joinThread);
    MainFrame.getInstance().acquireDisplayWait();
    try {
        dialog.analysisThread.start();
        if (joinThread) {
            try {
                dialog.analysisThread.join();
            } catch (InterruptedException e) {
            }
        }
    } finally {
        if (joinThread) {
            MainFrame.getInstance().releaseDisplayWait();
        }
    }
}
 
Example #20
Source File: FindBugsExecutor.java    From repositoryminer with Apache License 2.0 5 votes vote down vote up
private Project getProject() throws IOException, IllegalStateException {
	Project findBugsProject = new Project();
	for (String clsPath : analysisClasspath) {
		findBugsProject.addFile(clsPath);
	}
	return findBugsProject;
}
 
Example #21
Source File: MergeSummarizeAndView.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
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);
}
 
Example #22
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 #23
Source File: FindNonShortCircuitTest.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Before
public void setup() {
    PrintingBugReporter bugReporter = new PrintingBugReporter();
    ctx = AnalysisContext.currentAnalysisContext();
    if (ctx == null) {
        AnalysisContext.setCurrentAnalysisContext(new AnalysisContext(new Project()));
    }
    check = new FindNonShortCircuit(bugReporter);
}
 
Example #24
Source File: SpotBugsProcessor.java    From sputnik with Apache License 2.0 5 votes vote down vote up
@NotNull
private Project createProject(@NotNull Review review) {
    Project project = new Project();
    for (String buildDir : BuildDirLocatorFactory.create(config).getBuildDirs(review)) {
        project.addFile(buildDir);
    }
    project.addSourceDirs(review.getSourceDirs());
    return project;
}
 
Example #25
Source File: SourceDirectoryWizard.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * @param args
 *            the command line arguments
 */
public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(() -> {
        final SourceDirectoryWizard dialog = new SourceDirectoryWizard(new JFrame(), true, new Project(),
                null);
        dialog.setVisible(true);
    });
}
 
Example #26
Source File: MainFrame.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
boolean shouldDisplayIssue(BugInstance b) {
    Project project = getProject();
    Filter suppressionFilter = project.getSuppressionFilter();
    if (null == getBugCollection() || suppressionFilter.match(b)) {
        return false;
    }
    return viewFilter.show(b);
}
 
Example #27
Source File: MainFrame.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void openBugCollection(SortedBugCollection bugs) {
    acquireDisplayWait();
    try {
        mainFrameLoadSaveHelper.prepareForFileLoad(null, null);

        Project project = bugs.getProject();
        project.setGuiCallback(guiCallback);
        BugLoader.addDeadBugMatcher(bugs);
        setProjectAndBugCollectionInSwingThread(project, bugs);
    } finally {
        releaseDisplayWait();
    }

}
 
Example #28
Source File: MainFrameMenu.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void enableOrDisableItems(Project curProject, BugCollection bugCollection) {
    boolean haveBugs = bugCollection != null;
    boolean haveCodeToAnalyze = curProject != null && !curProject.getFileList().isEmpty();
    redoAnalysis.setEnabled(haveBugs && haveCodeToAnalyze);
    closeProjectItem.setEnabled(haveBugs);
    saveMenuItem.setEnabled(haveBugs);
    saveAsMenuItem.setEnabled(haveBugs);
    reconfigMenuItem.setEnabled(haveBugs);
    groupByMenuItem.setEnabled(haveBugs);
}
 
Example #29
Source File: BugSaver.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void saveBugs(@WillClose Writer out, BugCollection data, Project p) {

        try {
            data.writeXML(out);
        } catch (IOException e) {
            Debug.println(e);
        }
    }
 
Example #30
Source File: BugSaver.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void saveBugs(File out, BugCollection data, Project p) {
    try {
        saveBugs(UTF8.fileWriter(out), data, p);
        lastPlaceSaved = out.getAbsolutePath();
    } catch (IOException e) {
        JOptionPane.showMessageDialog(null, "An error has occurred in saving your file");
    }
}