⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 findbugs.java

📁 一个查找java程序里bug的程序的源代码,该程序本身也是java写的,对提高java编程水平很有用
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
			super.reportMissingClass(ex);		}	}	private static class CategoryFilteringBugReporter extends DelegatingBugReporter {		private Set<String> categorySet;		public CategoryFilteringBugReporter(BugReporter realBugReporter, Set<String> categorySet) {			super(realBugReporter);			this.categorySet = categorySet;		}		public void reportBug(BugInstance bugInstance) {			BugPattern bugPattern = bugInstance.getBugPattern();			String category = bugPattern.getCategory();			if (categorySet.contains(category))				getRealBugReporter().reportBug(bugInstance);		}	}	/**	 * Handling callback for choose() method,	 * used to implement the -chooseVisitors and -choosePlugins options.	 */	private interface Chooser {		/**		 * Choose a detector, plugin, etc.		 *		 * @param enable whether or not the item should be enabled		 * @param what   the item		 */		public void choose(boolean enable, String what);	}	private static final int PRINTING_REPORTER = 0;	private static final int SORTING_REPORTER = 1;	private static final int XML_REPORTER = 2;	private static final int EMACS_REPORTER = 3;	private static final int HTML_REPORTER = 4;	private static final int XDOCS_REPORTER = 5;	/**	 * Helper class to parse the command line and create	 * the FindBugs engine object.	 */	private static class FindBugsCommandLine extends CommandLine {		private int bugReporterType = PRINTING_REPORTER;		private boolean xmlWithMessages = false;		private String stylesheet = null;		private Project project = new Project();		private boolean quiet = false;		private ClassScreener classScreener = new ClassScreener();		private String filterFile = null;		private boolean include = false;		private boolean setExitCode = false;		private int priorityThreshold = Detector.NORMAL_PRIORITY;		private PrintStream outputStream = null;		private Set<String> bugCategorySet = null;		public FindBugsCommandLine() {			addOption("-home", "home directory", "specify FindBugs home directory");			addOption("-pluginList", "jar1[" + File.pathSeparator + "jar2...]",			        "specify list of plugin Jar files to load");			addSwitch("-showPlugins", "show list of available plugins");			addSwitch("-quiet", "suppress error messages");			addSwitch("-experimental", "report all warnings including experimental bug patterns");			addSwitch("-low", "report all warnings");			addSwitch("-medium", "report only medium and high priority warnings [default]");			addSwitch("-high", "report only high priority warnings");			addSwitch("-sortByClass", "sort warnings by class");			addSwitchWithOptionalExtraPart("-xml", "withMessages",				"XML output (optionally with messages)");			addSwitch("-xdocs", "xdoc XML output to use with Apache Maven");			addSwitchWithOptionalExtraPart("-html", "stylesheet",				"Generate HTML output (default stylesheet is default.xsl)");			addSwitch("-emacs", "Use emacs reporting format");			addOption("-outputFile", "filename", "Save output in named file");			addOption("-visitors", "v1[,v2...]", "run only named visitors");			addOption("-omitVisitors", "v1[,v2...]", "omit named visitors");			addOption("-chooseVisitors", "+v1,-v2,...", "selectively enable/disable detectors");			addOption("-choosePlugins", "+p1,-p2,...", "selectively enable/disable plugins");			addSwitch("-adjustExperimental", "lower the priority of Bug Patterns that are experimental");			addOption("-adjustPriority", "v1=(raise|lower)[,...]",					"raise/lower priority of warnings for given visitor(s)");			addOption("-bugCategories", "cat1[,cat2...]", "only report bugs in given categories");			addOption("-onlyAnalyze", "classes/packages", "only analyze given classes and packages");			addOption("-exclude", "filter file", "exclude bugs matching given filter");			addOption("-include", "filter file", "include only bugs matching given filter");			addOption("-auxclasspath", "classpath", "set aux classpath for analysis");			addOption("-sourcepath", "source path", "set source path for analyzed classes");			addOption("-project", "project", "analyze given project");			addSwitch("-exitcode", "set exit code of process");		}		public Project getProject() {			return project;		}		public boolean setExitCode() {			return setExitCode;		}		public boolean quiet() {			return quiet;		}		protected void handleOption(String option, String optionExtraPart) {			if (option.equals("-showPlugins")) {				System.out.println("Available plugins:");				int count = 0;				for (Iterator<Plugin> i = DetectorFactoryCollection.instance().pluginIterator(); i.hasNext(); ) {					Plugin plugin = i.next();					System.out.println("  " + plugin.getPluginId() + " (default: " +						(plugin.isEnabled() ? "enabled" : "disabled") + ")");					if (plugin.getShortDescription() != null)						System.out.println("    Description: " + plugin.getShortDescription());					if (plugin.getProvider() != null)						System.out.println("    Provider: " + plugin.getProvider());					if (plugin.getWebsite() != null)						System.out.println("    Website: " + plugin.getWebsite());					++count;				}				if (count == 0) {					System.out.println("  No plugins are available (FindBugs installed incorrectly?)");				}				System.exit(0);			} else if (option.equals("-experimental"))				priorityThreshold = Detector.EXP_PRIORITY;			else if (option.equals("-low"))				priorityThreshold = Detector.LOW_PRIORITY;			else if (option.equals("-medium"))				priorityThreshold = Detector.NORMAL_PRIORITY;			else if (option.equals("-high"))				priorityThreshold = Detector.HIGH_PRIORITY;			else if (option.equals("-adjustExperimental"))				BugInstance.setAdjustExperimental(true);			else if (option.equals("-sortByClass"))				bugReporterType = SORTING_REPORTER;			else if (option.equals("-xml")) {				bugReporterType = XML_REPORTER;				if (!optionExtraPart.equals("")) {					if (optionExtraPart.equals("withMessages"))						xmlWithMessages = true;					else						throw new IllegalArgumentException("Unknown option: -xml:" + optionExtraPart);				}			} else if (option.equals("-emacs"))				bugReporterType = EMACS_REPORTER;			else if (option.equals("-html")) {				bugReporterType = HTML_REPORTER;				if (!optionExtraPart.equals("")) {					stylesheet = optionExtraPart;				} else {					stylesheet = "default.xsl";				}			} else if (option.equals("-xdocs"))				bugReporterType = XDOCS_REPORTER;			else if (option.equals("-quiet"))				quiet = true;			else if (option.equals("-exitcode"))				setExitCode = true;			else				throw new IllegalStateException();		}		protected void handleOptionWithArgument(String option, String argument) throws IOException {			if (option.equals("-home")) {				FindBugs.setHome(argument);			} else if (option.equals("-pluginList")) {				String pluginListStr = argument;				ArrayList<File> pluginList = new ArrayList<File>();				StringTokenizer tok = new StringTokenizer(pluginListStr, File.pathSeparator);				while (tok.hasMoreTokens()) {					pluginList.add(new File(tok.nextToken()));				}				DetectorFactoryCollection.setPluginList((File[]) pluginList.toArray(new File[pluginList.size()]));			} else if (option.equals("-outputFile")) {				String outputFile = argument;				try {					outputStream = new PrintStream(new BufferedOutputStream(new FileOutputStream(outputFile)));				} catch (IOException e) {					System.err.println("Couldn't open " + outputFile + " for output: " + e.toString());					System.exit(1);				}			} else if (option.equals("-visitors") || option.equals("-omitVisitors")) {				boolean omit = option.equals("-omitVisitors");				if (!omit) {					// Selecting detectors explicitly, so start out by					// disabling all of them.  The selected ones will					// be re-enabled.					DetectorFactoryCollection.instance().disableAll();				}				// Explicitly enable or disable the selected detectors.				StringTokenizer tok = new StringTokenizer(argument, ",");				while (tok.hasMoreTokens()) {					String visitorName = tok.nextToken();					DetectorFactory factory = DetectorFactoryCollection.instance().getFactory(visitorName);					if (factory == null)						throw new IllegalArgumentException("Unknown detector: " + visitorName);					factory.setEnabled(!omit);				}			} else if (option.equals("-chooseVisitors")) {				// This is like -visitors and -omitVisitors, but				// you can selectively enable and disable detectors,				// starting from the default set (or whatever set				// happens to be in effect).				choose(argument, "Detector choices", new Chooser() {					public void choose(boolean enabled, String what) {						DetectorFactory factory = DetectorFactoryCollection.instance()							.getFactory(what);						if (factory == null)							throw new IllegalArgumentException("Unknown detector: " + what);						factory.setEnabled(enabled);					}				});			} else if (option.equals("-choosePlugins")) {				// Selectively enable/disable plugins				choose(argument, "Plugin choices", new Chooser() {					public void choose(boolean enabled, String what) {						Plugin plugin = DetectorFactoryCollection.instance().getPluginById(what);						if (plugin == null)							throw new IllegalArgumentException("Unknown plugin: " + what);						plugin.setEnabled(enabled);					}				});			} else if (option.equals("-adjustPriority")) {				// Selectively raise or lower the priority of warnings				// produced by specified detectors.								StringTokenizer tok = new StringTokenizer(argument, ",");				while (tok.hasMoreTokens()) {					String token = tok.nextToken();					int eq = token.indexOf('=');					if (eq < 0)						throw new IllegalArgumentException("Illegal priority adjustment: " + token);					String visitorName = token.substring(0, eq);					DetectorFactory factory = DetectorFactoryCollection.instance()						.getFactory(visitorName);					if (factory == null)						throw new IllegalArgumentException("Unknown detector: " + visitorName);										String adjustment = token.substring(eq + 1);					if (!(adjustment.equals("raise") || adjustment.equals("lower")))						throw new IllegalArgumentException("Illegal priority adjustment value: " +								adjustment);										// Recall that lower values are higher priorities					factory.setPriorityAdjustment(adjustment.equals("raise") ? -1 : +1);				}			} else if (option.equals("-bugCategories")) {				this.bugCategorySet = handleBugCategories(argument);			} else if (option.equals("-onlyAnalyze")) {				// The argument is a comma-separated list of classes and packages				// to select to analyze.  (If a list item ends with ".*",				// it specifies a package, otherwise it's a class.)				StringTokenizer tok = new StringTokenizer(argument, ",");				while (tok.hasMoreTokens()) {					String item = tok.nextToken();					if (item.endsWith(".-"))						classScreener.addAllowedPrefix(item.substring(0, item.length() - 1));					else if (item.endsWith(".*"))						classScreener.addAllowedPackage(item.substring(0, item.length() - 1));					else						classScreener.addAllowedClass(item);				}			} else if (option.equals("-exclude") || option.equals("-include")) {				filterFile = argument;				include = option.equals("-include");			} else if (option.equals("-auxclasspath")) {				StringTokenizer tok = new StringTokenizer(argument, File.pathSeparator);				while (tok.hasMoreTokens())					project.addAuxClasspathEntry(tok.nextToken());			} else if (option.equals("-sourcepath")) {				StringTokenizer tok = new StringTokenizer(argument, File.pathSeparator);				while (tok.hasMoreTokens())					project.addSourceDir(new File(tok.nextToken()).getAbsolutePath());			} else if (option.equals("-project")) {				String projectFile = argument;				// Convert project file to be an absolute path				projectFile = new File(projectFile).getAbsolutePath();				try {					project = new Project();					project.read(projectFile);				} catch (IOException e) {					System.err.println("Error opening " + projectFile);					e.printStackTrace(System.err);					throw e;				}			}		}		/**		 * Common handling code for -chooseVisitors and -choosePlugins options.		 *		 * @param argument the list of visitors or plugins to be chosen		 * @param desc     String describing what is being chosen		 * @param chooser  callback object to selectively choose list members		 */		private void choose(String argument, String desc, Chooser chooser) {			StringTokenizer tok = new StringTokenizer(argument, ",");			while (tok.hasMoreTokens()) {				String what = tok.nextToken();				if (!what.startsWith("+") && !what.startsWith("-"))					throw new IllegalArgumentException(desc + " must start with " +						"\"+\" or \"-\" (saw " + what + ")");				boolean enabled = what.startsWith("+");				chooser.choose(enabled, what.substring(1));			}		}		public FindBugs createEngine() throws IOException, FilterException {			TextUIBugReporter textuiBugReporter = null;			switch (bugReporterType) {			case PRINTING_REPORTER:				textuiBugReporter = new PrintingBugReporter();				break;			case SORTING_REPORTER:				textuiBugReporter = new SortingBugReporter();				break;			case XML_REPORTER:				{					XMLBugReporter xmlBugReporter = new XMLBugReporter(project);					xmlBugReporter.setAddMessages(xmlWithMessages);					textuiBugReporter = xmlBugReporter;				}				break;			case EMACS_REPORTER:				textuiBugReporter = new EmacsBugReporter();				break;			case HTML_REPORTER:				textuiBugReporter = new HTMLBugReporter(project, stylesheet);				break;			case XDOCS_REPORTER:				textuiBugReporter = new XDocsBugReporter(project);				break;			default:				throw new IllegalStateException();			}			if (quiet)				textuiBugReporter.setErrorVerbosity(BugReporter.SILENT);			textuiBugReporter.setPriorityThreshold(priorityThreshold);			if (outputStream != null)				textuiBugReporter.setOutputStream(outputStream);			BugReporter bugReporter = textuiBugReporter;			if (bugCategorySet != null) {				bugReporter = new CategoryFilteringBugReporter(bugReporter, bugCategorySet);			}			FindBugs findBugs = new FindBugs(bugReporter, project);			if (filterFile != null)				findBugs.setFilter(filterFile, include);			findBugs.setClassScreener(classScreener);			return findBugs;		}	}	/* ----------------------------------------------------------------------	 * Member variables	 * ---------------------------------------------------------------------- */	static final boolean DEBUG = Boolean.getBoolean("findbugs.debug");	/**	 * FindBugs home directory.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -