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

📄 findbugs.java

📁 A static analysis tool to find bugs in Java programs
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
				// MUSTFIX: Evaluate whether this makes a difference				if (false && detector instanceof StatelessDetector) {						try {							detector = (Detector) ((StatelessDetector) detector).clone();						} catch (CloneNotSupportedException e) {							throw new AssertionError(e);						}				}				try {					long start = 0, end;					if (TIMEDEBUG || DEBUG) {						start = System.currentTimeMillis();						if (DEBUG) {							System.out.println("  running " + detector.getClass().getName());						}					}					detector.visitClassContext(classContext);					if (TIMEDEBUG || DEBUG) {						end = System.currentTimeMillis();						long delta = end - start;						entireClassAnalysisStart += delta;						if (delta > TIMEQUANTUM)							System.out.println("TIME: " + detector.getClass().getName() + " " + className + " " + delta);						if (DEBUG) {							String detectorName = detector.getClass().getName();							Long total = detectorTimings.get(detectorName);							if (total == null)								total = (Long)(delta);							else								total = (Long)(total.longValue() + delta);							detectorTimings.put(detectorName, total);						}					}				} catch (AnalysisException e) {					reportRecoverableDetectorException(className, detector, e);				} catch (ArrayIndexOutOfBoundsException e) {					reportRecoverableDetectorException(className, detector, e);				} catch (ClassCastException e) {					reportRecoverableDetectorException(className, detector, e);				}			}		} catch (ClassNotFoundException e) {			// This should never happen unless there are bugs in BCEL.			bugReporter.reportMissingClass(e);			reportRecoverableException(className, e);		} catch (ClassFormatException e) {			reportRecoverableException(className, e);		}		catch (RuntimeException re) {			RuntimeException annotatedEx;			try {				String sep = SystemProperties.getProperty("line.separator");				Constructor<? extends RuntimeException> c = re.getClass().getConstructor(new Class[] { String.class });				String msg = re.getMessage();				msg = sep + "While finding bugs in class: " + className + ((msg == null) ? "" : (sep + msg));				annotatedEx = c.newInstance(new Object[] {msg});				annotatedEx.setStackTrace(re.getStackTrace());			} catch (RuntimeException e) {				throw re;			} catch (Exception e) {				throw re;			}			throw annotatedEx;		}		if (TIMEDEBUG || DEBUG) {			long classSetupTime = System.currentTimeMillis() - entireClassAnalysisStart;			if (classSetupTime > TIMEQUANTUM)				System.out.println("TIME:  setup " + className + " " + classSetupTime); 		}		progressCallback.finishClass();	}	private void reportRecoverableException(String className, Exception e) {		if (DEBUG) {			e.printStackTrace();		}		bugReporter.logError("Exception analyzing " + className, e);	}	private void reportRecoverableDetectorException(String className, Detector detector, Exception e) {		if (DEBUG) {			e.printStackTrace();		}		bugReporter.logError("Exception analyzing " + className +			" using detector " + detector.getClass().getName(), e);	}	/**	 * Call report() on all detectors, to give them a chance to	 * report any accumulated bug reports.	 */	private void reportFinal(Detector[] detectors) throws InterruptedException {		for (Detector detector : detectors) {			if (Thread.interrupted())				throw new InterruptedException();			detector.report();		}	}	/**	 * Parse the data for a class to create a JavaClass object.	 */	private static JavaClass parseClass(String archiveName, InputStream in, String fileName)			throws IOException {		if (DEBUG) System.out.println("About to parse " + fileName + " in " + archiveName);		return parseFromStream(in, fileName);	}	/**	 * Parse the data for a class to create a JavaClass object.	 */	private static JavaClass parseClass(URL url) throws IOException {		if (DEBUG) System.out.println("About to parse " + url.toString());		InputStream in = null;		try {			in = url.openStream();			return parseFromStream(in, url.toString());		} finally {			if (in != null)				in.close();		}	}	/**	 * Parse an input stream to produce a JavaClass object.	 * Makes sure that the input stream is closed no	 * matter what.	 */	private static JavaClass parseFromStream(InputStream in, String fileName) throws IOException {		try {			return new ClassParser(in, fileName).parse();		} finally {			try {				in.close();			} catch (IOException ignore) {				// Ignore			}		}	}	/**	 * Process -bugCategories option.	 * 	 * @param userPreferences	 *            UserPreferences representing which Detectors are enabled	 * @param categories	 *            comma-separated list of bug categories	 * @return Set of categories to be used	 */	static Set<String> handleBugCategories(UserPreferences userPreferences, String categories) {		// Parse list of bug categories		Set<String> categorySet = new HashSet<String>();		StringTokenizer tok = new StringTokenizer(categories, ",");		while (tok.hasMoreTokens()) {			categorySet.add(tok.nextToken());		}//		// Enable only those detectors that can emit those categories//		// (and the ones that produce unknown bug patterns, just to be safe).//		// Skip disabled detectors, though.//		for (Iterator<DetectorFactory> i = DetectorFactoryCollection.instance().factoryIterator(); i.hasNext();) {//			DetectorFactory factory = i.next();//			if (!factory.isEnabledForCurrentJRE())//				continue;//			Collection<BugPattern> reported = factory.getReportedBugPatterns();//			boolean enable = false;//			if (reported.isEmpty()) {//				// Don't know what bug patterns are produced by this detector//				if (DEBUG) System.out.println("Unknown bug patterns for " + factory.getShortName());//				enable = true;//			} else {//				for (Iterator<BugPattern> j = reported.iterator(); j.hasNext();) {//					BugPattern bugPattern = j.next();//					if (categorySet.contains(bugPattern.getCategory())) {//						if (DEBUG)//							System.out.println("MATCH ==> " + categorySet +//							        " -- " + bugPattern.getCategory());//						enable = true;//						break;//					}//				}//			}//			if (DEBUG && enable) {//				System.out.println("Enabling " + factory.getShortName());//			}//			userPreferences.enableDetector(factory, enable);//		}		return categorySet;	}	/* ----------------------------------------------------------------------	 * main() method	 * ---------------------------------------------------------------------- */	public static void main(String[] argv) {		try {			TextUICommandLine commandLine = new TextUICommandLine();			FindBugs findBugs = createEngine(commandLine, argv);			try {				runMain(findBugs, commandLine);			} catch (RuntimeException e) {				System.err.println("Fatal exception: " + e.toString());				String currentClass = findBugs.getCurrentClass();				if (currentClass != null) {					System.err.println("\tWhile analyzing " + currentClass);				}				e.printStackTrace();				System.err.println("Please report the failure to " + Version.SUPPORT_EMAIL);				System.exit(1);			}		} catch (java.io.IOException e) {			// Probably a missing file			if (DEBUG) {				e.printStackTrace();			}			System.err.println("IO Error: " + e.getMessage());			System.exit(1);		} catch (FilterException e) {			System.err.println("Filter exception: " + e.getMessage());		} catch (IllegalArgumentException e) {			// Probably an illegal command line argument			System.err.println("Illegal argument: " + e.getMessage());			System.exit(1);		}	}	private static FindBugs createEngine(TextUICommandLine commandLine, String[] argv)			throws java.io.IOException, FilterException {		FindBugs findBugs = new FindBugs();		processCommandLine(commandLine, argv, findBugs);		return findBugs;	}	/**	 * Process the command line.	 * 	 * @param commandLine  the TextUICommandLine object which will parse the command line	 * @param argv         the command line arguments	 * @param findBugs     the IFindBugsEngine to configure	 * @throws IOException	 * @throws FilterException	 */	public static void processCommandLine(TextUICommandLine commandLine, String[] argv, IFindBugsEngine findBugs) throws IOException, FilterException {		// Expand option files in command line.		// An argument beginning with "@" is treated as specifying		// the name of an option file.		// Each line of option files are treated as a single argument.		// Blank lines and comment lines (beginning with "#")		// are ignored.		argv = CommandLine.expandOptionFiles(argv, true, true);		int argCount = 0;		try {			argCount = commandLine.parse(argv);		} catch (IllegalArgumentException e) {			System.out.println(e.getMessage());			showHelp(commandLine);		} catch (HelpRequestedException e) {			showHelp(commandLine);		}		Project project = commandLine.getProject();		for (int i = argCount; i < argv.length; ++i)			project.addFile(argv[i]);		commandLine.handleXArgs();		if (project.getFileCount() == 0) {			showHelp(commandLine);		}		commandLine.configureEngine(findBugs);	}	@SuppressWarnings("DM_EXIT")	public static void showHelp(TextUICommandLine commandLine) {		showSynopsis();		ShowHelp.showGeneralOptions();		FindBugs.showCommandLineOptions(commandLine);		System.exit(1);	}	@SuppressWarnings("DM_EXIT")	public static void runMain(IFindBugsEngine findBugs, TextUICommandLine commandLine)			throws java.io.IOException, RuntimeException {		try {			findBugs.execute();		} catch (InterruptedException e) {			// Not possible when running from the command line		}		int bugCount = findBugs.getBugCount();		int missingClassCount = findBugs.getMissingClassCount();		int errorCount = findBugs.getErrorCount();		if (!commandLine.quiet() || commandLine.setExitCode()) {			if (bugCount > 0)				System.err.println("Warnings generated: " + bugCount);			if (missingClassCount > 0)				System.err.println("Missing classes: " + missingClassCount);			if (errorCount > 0)				System.err.println("Analysis errors: " + errorCount);		}		if (commandLine.setExitCode()) {			int exitCode = 0;			if (errorCount > 0)				exitCode |= ERROR_FLAG;			if (missingClassCount > 0)				exitCode |= MISSING_CLASS_FLAG;			if (bugCount > 0)				exitCode |= BUGS_FOUND_FLAG;			System.exit(exitCode);		}	}	/**	 * Print command line options synopses to stdout.	 */	public static void showCommandLineOptions() {		showCommandLineOptions(new TextUICommandLine());	}	public static void showCommandLineOptions(TextUICommandLine commandLine) {		System.out.println("Command line options:");		commandLine.printUsage(System.out);	}	public static void showSynopsis() {		System.out.println("Usage: findbugs [general options] -textui [command line options...] [jar/zip/class files, directories...]");	}	public static void configureFilter(DelegatingBugReporter bugReporter, String filterFileName, boolean include)			throws IOException, FilterException {		Filter filter = new Filter(filterFileName);		BugReporter origBugReporter = bugReporter.getDelegate();		BugReporter filterBugReporter = new FilterBugReporter(origBugReporter, filter, include);		bugReporter.setDelegate(filterBugReporter);	}	/**	 * Configure the BugCollection (if the BugReporter being used	 * is constructing one).	 * 	 * @param findBugs the IFindBugsEngine	 */	public static void configureBugCollection(IFindBugsEngine findBugs) {		BugReporter realBugReporter = findBugs.getBugReporter().getRealBugReporter();		if (realBugReporter instanceof BugCollectionBugReporter) {			BugCollectionBugReporter bugCollectionBugReporter =				(BugCollectionBugReporter) realBugReporter;			bugCollectionBugReporter = (BugCollectionBugReporter) realBugReporter;			bugCollectionBugReporter.getBugCollection().setReleaseName(findBugs.getReleaseName());			Project project = findBugs.getProject();			if (project.getProjectName() == null)				project.setProjectName(findBugs.getProjectName());			if (project.getTimestamp() != 0) {				bugCollectionBugReporter.getBugCollection().setTimestamp(project.getTimestamp());				bugCollectionBugReporter.getBugCollection().getProjectStats().setTimestamp(project.getTimestamp());			}		}	}	/* (non-Javadoc)		* @see edu.umd.cs.findbugs.IFindBugsEngine#getProjectName()		*/	public String getProjectName() {		return projectName;	}	/* (non-Javadoc)		* @see edu.umd.cs.findbugs.IFindBugsEngine#setProjectName(java.lang.String)		*/	public void setProjectName(String projectName) {		this.projectName = projectName;	}	/* (non-Javadoc)		* @see edu.umd.cs.findbugs.IFindBugsEngine#setAbridgedMessages(boolean)		*/	public void setAbridgedMessages(boolean xmlWithAbridgedMessages) {		// TODO Auto-generated method stub	}}// vim:ts=4

⌨️ 快捷键说明

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