/** * Extracts the module name from the specified project. If empty then the provided default name is * used. * * @param defaultName the default module name to use * @param project the maven 2 project * @return the module name to use */ private String extractModuleName(final String defaultName, final Project project) { if (StringUtils.isBlank(project.getProjectName())) { return defaultName; } else { return project.getProjectName(); } }
/** * ファイル一覧をチェックしてマーカーを作成します。 * * @param env * @param files ファイル一覧 * @param monitor 遷移モニタ * @return 処理に成功したらtrue */ private boolean markAll(LimyQalabEnvironment env, String[] files, IProgressMonitor monitor) { IFindBugsEngine engine = getEngine(env.getProject(), monitor); try { LimyBugReporter reporter = new LimyBugReporter(env); reporter.setPriorityThreshold(Detector.LOW_PRIORITY); engine.setBugReporter(reporter); Project findbugsProject = new Project(); for (String file : files) { findbugsProject.addFile(file); } engine.setProject(findbugsProject); engine.execute(); return true; } catch (IOException e) { LimyEclipsePluginUtils.log(e); } catch (InterruptedException e) { LimyEclipsePluginUtils.log(e); } return false; }
/** @since 1.2 */ @Test public void should_support_multiple_binary_dirs() throws IOException { File binaryDir1 = temp.newFolder("binary1"); File binaryDir2 = temp.newFolder("binary2"); fs.addBinaryDir(binaryDir1); fs.addBinaryDir(binaryDir2); Project findbugsProject = conf.getFindbugsProject(); assertThat(findbugsProject.getFileCount()).isEqualTo(2); assertThat(findbugsProject.getFile(0)).isEqualTo(binaryDir1.getAbsolutePath()); assertThat(findbugsProject.getFile(1)).isEqualTo(binaryDir2.getAbsolutePath()); }
private static void addAuxCPEntry(Project p, URL url) { // XXX: need more reliable way File f = FileUtil.archiveOrDirForURL(url); if (f == null) return; p.addAuxClasspathEntry(f.getAbsolutePath()); }
private String findSourceFile( final Project project, final SourceFinder sourceFinder, final SourceLineAnnotation sourceLine) { try { SourceFile sourceFile = sourceFinder.findSourceFile(sourceLine); return sourceFile.getFullFileName(); } catch (IOException exception) { StringBuilder sb = new StringBuilder("Can't resolve absolute file name for file "); sb.append(sourceLine.getSourceFile()); if (isFirstError) { sb.append(", dir list = "); sb.append(project.getSourceDirList()); isFirstError = false; } Logger.getLogger(getClass().getName()).log(Level.WARNING, sb.toString()); return sourceLine.getPackageName().replace(DOT, SLASH) + SLASH + sourceLine.getSourceFile(); } }
/** Get the SourceFinder, for finding source files. */ public SourceFinder getSourceFinder() { return project.getSourceFinder(); }
/** * Returns the parsed FindBugs analysis file. This scanner accepts files in the native FindBugs * format. * * @param file the FindBugs analysis file * @param sources a collection of folders to scan for source files * @param moduleName name of maven module * @param hashToMessageMapping mapping of hash codes to messages * @param categories mapping from bug types to their categories * @return the parsed result (stored in the module instance) * @throws IOException if the file could not be parsed * @throws DocumentException in case of a parser exception */ private Collection<FileAnnotation> parse( final InputStream file, final Collection<String> sources, final String moduleName, final Map<String, String> hashToMessageMapping, final Map<String, String> categories) throws IOException, DocumentException { SortedBugCollection collection = readXml(file); Project project = collection.getProject(); for (String sourceFolder : sources) { project.addSourceDir(sourceFolder); } SourceFinder sourceFinder = new SourceFinder(project); String actualName = extractModuleName(moduleName, project); TreeStringBuilder stringPool = new TreeStringBuilder(); List<FileAnnotation> annotations = new ArrayList<FileAnnotation>(); Collection<BugInstance> bugs = collection.getCollection(); for (BugInstance warning : bugs) { SourceLineAnnotation sourceLine = warning.getPrimarySourceLineAnnotation(); String message = warning.getMessage(); String type = warning.getType(); if (message.contains("TEST: Unknown")) { message = FindBugsMessages.getInstance().getShortMessage(type, LocaleProvider.getLocale()); } String category = categories.get(type); if (category == null) { // alternately, only if warning.getBugPattern().getType().equals("UNKNOWN") category = warning.getBugPattern().getCategory(); } Bug bug = new Bug( getPriority(warning), StringUtils.defaultIfEmpty( hashToMessageMapping.get(warning.getInstanceHash()), message), category, type, sourceLine.getStartLine(), sourceLine.getEndLine()); bug.setInstanceHash(warning.getInstanceHash()); bug.setRank(warning.getBugRank()); boolean ignore = setCloudInformation(collection, warning, bug); if (!ignore) { bug.setNotAProblem(false); bug.setFileName(findSourceFile(project, sourceFinder, sourceLine)); bug.setPackageName(warning.getPrimaryClass().getPackageName()); bug.setModuleName(actualName); setAffectedLines(warning, bug); annotations.add(bug); bug.intern(stringPool); } } return applyFilters(annotations); }
public static List<ErrorDescription> runFindBugs( CompilationInfo info, Preferences customSettings, String singleBug, FileObject sourceRoot, Iterable<? extends String> classNames, FindBugsProgress progress, SigFilesValidator validator) { List<ErrorDescription> result = new ArrayList<ErrorDescription>(); try { Class.forName( "org.netbeans.modules.findbugs.NbClassFactory", true, RunFindBugs.class.getClassLoader()); // NOI18N Project p = new Project(); URL[] binaryRoots = CacheBinaryForSourceQuery.findCacheBinaryRoots(sourceRoot.toURL()).getRoots(); if (classNames == null) { for (URL binary : binaryRoots) { try { p.addFile(new File(binary.toURI()).getAbsolutePath()); } catch (URISyntaxException ex) { Exceptions.printStackTrace(ex); } } } else { ClassPath binary = ClassPathSupport.createClassPath(binaryRoots); List<FileObject> sigFiles = new ArrayList<FileObject>(); for (String className : classNames) { FileObject classFO = binary.findResource(className.replace('.', '/') + ".sig"); // NOI18N if (classFO != null) { sigFiles.add(classFO); } else { LOG.log( Level.WARNING, "Cannot find sig file for: " + className); // TODO: should probably become FINE eventually } } assert validator != null; if (!validator.validate(sigFiles)) return null; for (FileObject classFO : sigFiles) { p.addFile(new File(classFO.toURI()).getAbsolutePath()); } addCompileRootAsSource(p, sourceRoot); } ClassPath compile = ClassPath.getClassPath(sourceRoot, ClassPath.COMPILE); for (FileObject compileRoot : compile.getRoots()) { addCompileRoot(p, compileRoot); } BugCollectionBugReporter r = new BugCollectionBugReporter(p) { @Override protected void emitLine(String line) { LOG.log(Level.FINE, line); } }; r.setPriorityThreshold(Integer.MAX_VALUE); r.setRankThreshold(Integer.MAX_VALUE); FindBugs2 engine = new FindBugs2(); engine.setProject(p); engine.setNoClassOk(true); engine.setBugReporter(r); if (progress != null) { engine.setProgressCallback(progress); } boolean inEditor = validator != null; Preferences settings = customSettings != null ? customSettings : NbPreferences.forModule(RunFindBugs.class).node("global-settings"); UserPreferences preferences; if (singleBug != null) { singleBug = singleBug.substring(PREFIX_FINDBUGS.length()); preferences = forSingleBug(singleBug); } else { preferences = readPreferences(settings, customSettings != null); } if (preferences == null) { // nothing enabled, stop return result; } engine.setUserPreferences(preferences); engine.setDetectorFactoryCollection(DetectorFactoryCollection.instance()); LOG.log(Level.FINE, "Running FindBugs"); engine.execute(); Map<FileObject, List<BugInstance>> file2Bugs = new HashMap<FileObject, List<BugInstance>>(); for (BugInstance b : r.getBugCollection().getCollection()) { if (singleBug != null && !singleBug.equals(b.getBugPattern().getType())) continue; if (singleBug == null && !settings.getBoolean( b.getBugPattern().getType(), customSettings == null && isEnabledByDefault(b.getBugPattern()))) { continue; } SourceLineAnnotation sourceLine = b.getPrimarySourceLineAnnotation(); FileObject sourceFile = null; if (sourceLine != null) { sourceFile = sourceRoot.getFileObject(sourceLine.getSourcePath()); if (sourceFile != null) { List<BugInstance> bugs = file2Bugs.get(sourceFile); if (bugs == null) { file2Bugs.put(sourceFile, bugs = new ArrayList<BugInstance>()); } bugs.add(b); } else { LOG.log( Level.WARNING, "{0}, location: {1}:{2}", new Object[] {b, sourceLine.getSourcePath(), sourceLine.getStartLine()}); } } } for (Entry<FileObject, List<BugInstance>> e : file2Bugs.entrySet()) { int[] lineOffsets = null; FileObject sourceFile = e.getKey(); DataObject d = DataObject.find(sourceFile); EditorCookie ec = d.getLookup().lookup(EditorCookie.class); Document doc = ec.getDocument(); JavaSource js = null; for (BugInstance b : e.getValue()) { SourceLineAnnotation sourceLine = b.getPrimarySourceLineAnnotation(); if (sourceLine.getStartLine() >= 0) { LazyFixList fixes = prepareFixes(b, inEditor, sourceFile, sourceLine.getStartLine(), null); if (doc != null) { result.add( ErrorDescriptionFactory.createErrorDescription( PREFIX_FINDBUGS + b.getType(), Severity.VERIFIER, b.getMessageWithoutPrefix(), b.getBugPattern().getDetailHTML(), fixes, doc, sourceLine.getStartLine())); } else { if (lineOffsets == null) { lineOffsets = computeLineMap(sourceFile, FileEncodingQuery.getEncoding(sourceFile)); } int edLine = 2 * (Math.min(sourceLine.getStartLine(), lineOffsets.length / 2) - 1); result.add( ErrorDescriptionFactory.createErrorDescription( PREFIX_FINDBUGS + b.getType(), Severity.VERIFIER, b.getMessageWithoutPrefix(), b.getBugPattern().getDetailHTML(), fixes, sourceFile, lineOffsets[edLine], lineOffsets[edLine + 1])); } } else { if (js == null) { js = JavaSource.forFileObject(sourceFile); } addByElementAnnotation(b, info, sourceFile, js, result, inEditor); } } } } catch (ClassNotFoundException ex) { Exceptions.printStackTrace(ex); } catch (IOException ex) { Exceptions.printStackTrace(ex); } catch (InterruptedException ex) { LOG.log(Level.FINE, null, ex); } return result; }
/** @param project */ private void setProject(Project project) { this.project = project; repositoryList = new LinkedList<SourceRepository>(); cache = new Cache(); setSourceBaseList(project.getResolvedSourcePaths()); }