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 Project: super-cloudops   Author: wl4g   File: SpotbugsAnalyzerEngine.java    License: 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 #2
Source Project: super-cloudops   Author: wl4g   File: SpotbugsGuiTests.java    License: 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 #3
Source Project: spotbugs   Author: spotbugs   File: AnalysisRunner.java    License: 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 #4
Source Project: spotbugs   Author: spotbugs   File: FindBugsWorker.java    License: 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 #5
Source Project: spotbugs   Author: spotbugs   File: WorkItem.java    License: 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 #6
Source Project: spotbugs   Author: spotbugs   File: WorkItem.java    License: 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 Project: spotbugs   Author: spotbugs   File: Filter.java    License: 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 #8
Source Project: spotbugs   Author: spotbugs   File: UnionResults.java    License: 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 #9
Source Project: spotbugs   Author: spotbugs   File: BugLoader.java    License: 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 #10
Source Project: spotbugs   Author: spotbugs   File: BugLoader.java    License: 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 #11
Source Project: spotbugs   Author: spotbugs   File: AnalyzingDialog.java    License: 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 #12
Source Project: spotbugs   Author: spotbugs   File: AnalyzingDialog.java    License: 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 #13
Source Project: spotbugs   Author: spotbugs   File: MainFrame.java    License: 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 #14
Source Project: spotbugs   Author: spotbugs   File: NewProjectWizard.java    License: 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 #15
Source Project: spotbugs   Author: spotbugs   File: MainFrameLoadSaveHelper.java    License: 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 #16
Source Project: spotbugs   Author: spotbugs   File: MainFrameLoadSaveHelper.java    License: 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 #17
Source Project: spotbugs   Author: spotbugs   File: MergeSummarizeAndView.java    License: 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 #18
Source Project: spotbugs   Author: spotbugs   File: SourceMatcherTest.java    License: 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 #19
Source Project: spotbugs   Author: spotbugs   File: SourceMatcherTest.java    License: 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 #20
Source Project: super-cloudops   Author: wl4g   File: DefaultHtmlBugExporter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void doExport(Project project, BugCollection bugs, File f) throws Exception {
	HTMLBugReporter reporter = new HTMLBugReporter(project, "default.xsl");
	reporter.setIsRelaxed(true);
	reporter.setOutputStream(UTF8.printStream(new FileOutputStream(f)));
	for (BugInstance bug : bugs.getCollection()) {
		try {
			reporter.reportBug(bug);
		} catch (Exception e) {
			e.printStackTrace(); // Print to parent process
		}
	}
	reporter.finish();
}
 
Example #21
Source Project: super-cloudops   Author: wl4g   File: SpotbugsAnalyzerEngine.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create the IFindBugsEngine that will be used to analyze the application.
 * 
 * @param project
 * @param warnWriter
 * @param progress
 * @return
 * @throws InterruptedException
 * @throws IOException
 */
@SuppressWarnings("unchecked")
private <R extends TextUIBugReporter> R doAnalysis(@Nonnull Project project, @Nonnull StringWriter warnWriter,
		@Nonnull FindBugsProgress progress) throws IOException, InterruptedException {
	BugCollectionBugReporter reporter = new BugCollectionBugReporter(project, new PrintWriter(warnWriter, true));
	reporter.setPriorityThreshold(Priorities.LOW_PRIORITY);
	IFindBugsEngine engine = createEngine0(project, reporter);
	engine.setUserPreferences(UserPreferences.createDefaultUserPreferences());
	engine.setProgressCallback(progress);
	engine.setProjectName(project.getProjectName());
	engine.execute(); // Execution.
	return (R) reporter;
}
 
Example #22
Source Project: super-cloudops   Author: wl4g   File: SpotbugsAnalyzerEngine.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create the IFindBugsEngine that will be used to analyze the application.
 *
 * @param p
 *            the Project
 * @param reporter
 *            the PrintCallBack
 * @return the IFindBugsEngine
 */
private IFindBugsEngine createEngine0(@Nonnull Project p, BugReporter reporter) {
	FindBugs2 engine = new FindBugs2();
	engine.setBugReporter(reporter);
	engine.setProject(p);
	engine.setDetectorFactoryCollection(DetectorFactoryCollection.instance());
	//
	// Honor -effort option if one was given on the command line.
	//
	engine.setAnalysisFeatureSettings(Driver.getAnalysisSettingList());
	return engine;
}
 
Example #23
Source Project: spotbugs   Author: spotbugs   File: AnalysisRunner.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Nonnull
public BugCollectionBugReporter run(Path... files) {
    DetectorFactoryCollection.resetInstance(new DetectorFactoryCollection());

    try (FindBugs2 engine = new FindBugs2(); Project project = createProject(files)) {
        engine.setProject(project);

        final DetectorFactoryCollection detectorFactoryCollection = DetectorFactoryCollection.instance();
        engine.setDetectorFactoryCollection(detectorFactoryCollection);

        BugCollectionBugReporter bugReporter = new BugCollectionBugReporter(project);
        bugReporter.setPriorityThreshold(Priorities.LOW_PRIORITY);
        bugReporter.setRankThreshold(BugRanker.VISIBLE_RANK_MAX);

        engine.setBugReporter(bugReporter);
        final UserPreferences preferences = UserPreferences.createDefaultUserPreferences();
        preferences.getFilterSettings().clearAllCategories();
        preferences.enableAllDetectors(true);
        engine.setUserPreferences(preferences);

        try {
            engine.execute();
        } catch (final IOException | InterruptedException e) {
            throw new AssertionError("Analysis failed with exception", e);
        }
        if (!bugReporter.getQueuedErrors().isEmpty()) {
            bugReporter.reportQueuedErrors();
            throw new AssertionError(
                    "Analysis failed with exception. Check stderr for detail.");
        }
        return bugReporter;
    }
}
 
Example #24
Source Project: spotbugs   Author: spotbugs   File: Reporter.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param project
 *            the project whose classes are being analyzed for bugs
 * @param monitor
 *            progress monitor
 */
public Reporter(IJavaProject project, Project findBugsProject, IProgressMonitor monitor) {
    super();
    if (DEBUG) {
        printToStream("Eclipse FindBugs plugin REPORTER debugging enabled");
    }
    this.monitor = new ThrottledProgressMonitor(monitor, System::currentTimeMillis);
    this.project = project;
    // TODO we do not need to sort bugs, so we can optimize performance and
    // use just a list here
    this.bugCollection = new SortedBugCollection(getProjectStats(), findBugsProject);
}
 
Example #25
Source Project: spotbugs   Author: spotbugs   File: WorkItem.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
private void addJavaElementPath(Project fbProject) {
    if (javaElt != null) {
        IPath path = getPath();
        if (path != null) {
            fbProject.addFile(path.toOSString());
        }
    }
}
 
Example #26
Source Project: spotbugs   Author: spotbugs   File: WorkItem.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * @return false if no classes was added
 */
private static boolean addClassesForFolder(IFolder folder, Map<IPath, IPath> outLocations, Project fbProject) {
    IPath path = folder.getLocation();
    IPath srcRoot = getMatchingSourceRoot(path, outLocations);
    if (srcRoot == null) {
        return false;
    }
    IPath outputRoot = outLocations.get(srcRoot);
    int firstSegments = path.matchingFirstSegments(srcRoot);
    // add relative path to the output path
    IPath out = outputRoot.append(path.removeFirstSegments(firstSegments));
    File directory = out.toFile();
    return fbProject.addFile(directory.getAbsolutePath());
    // TODO child directories too. Should add preference???
}
 
Example #27
Source Project: spotbugs   Author: spotbugs   File: FindbugsPlugin.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
private static SortedBugCollection createDefaultEmptyBugCollection(IProject project) throws CoreException {
    SortedBugCollection bugCollection = new SortedBugCollection();
    Project fbProject = bugCollection.getProject();

    UserPreferences userPrefs = getUserPreferences(project);

    cacheBugCollectionAndProject(project, bugCollection, fbProject);
    return bugCollection;
}
 
Example #28
Source Project: spotbugs   Author: spotbugs   File: ObfuscateBugs.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    FindBugs.setNoAnalysis();
    CommandLine commandLine = new CommandLine();

    int argCount = commandLine.parse(args, 0, 2, "Usage: " + ObfuscateBugs.class.getName() + " [options] [<xml results>] ");

    SortedBugCollection bugCollection = new SortedBugCollection();
    if (argCount < args.length) {
        bugCollection.readXML(args[argCount++]);
    } else {
        bugCollection.readXML(System.in);
    }

    SortedBugCollection results = bugCollection.createEmptyCollectionWithMetadata();
    Project project = results.getProject();
    project.getSourceDirList().clear();
    project.getFileList().clear();
    project.getAuxClasspathEntryList().clear();

    results.getProjectStats().getPackageStats().clear();
    results.clearMissingClasses();
    results.clearErrors();

    for (BugInstance bug : bugCollection) {
        results.add(Obfuscate.obfuscate(bug), false);
    }

    if (argCount == args.length) {
        results.writeXML(System.out);
    } else {
        results.writeXML(args[argCount++]);

    }

}
 
Example #29
Source Project: spotbugs   Author: spotbugs   File: AnalysisContext.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public AnalysisContext(@Nonnull Project project) {
    requireNonNull(project);
    this.project = project;
    this.boolPropertySet = new BitSet();
    this.lookupFailureCallback = new DelegatingRepositoryLookupFailureCallback();
    skippedDueToInvokeDynamic = new HashSet<>();
    equalsKindSummary = new EqualsKindSummary();
    unreadFieldsData = new UnreadFieldsData();
    suppressionMatcher = new SuppressionMatcher();
    bridgeTo = new IdentityHashMap<>();
    bridgeFrom = new IdentityHashMap<>();
}
 
Example #30
Source Project: spotbugs   Author: spotbugs   File: BugLoader.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Create the IFindBugsEngine that will be used to analyze the application.
 *
 * @param p
 *            the Project
 * @param pcb
 *            the PrintCallBack
 * @return the IFindBugsEngine
 */
private static IFindBugsEngine createEngine(@Nonnull Project p, BugReporter pcb) {
    FindBugs2 engine = new FindBugs2();
    engine.setBugReporter(pcb);
    engine.setProject(p);

    engine.setDetectorFactoryCollection(DetectorFactoryCollection.instance());

    //
    // Honor -effort option if one was given on the command line.
    //
    engine.setAnalysisFeatureSettings(Driver.getAnalysisSettingList());

    return engine;
}