idx
int64 0
165k
| question
stringlengths 73
4.15k
| target
stringlengths 5
918
| len_question
int64 21
890
| len_target
int64 3
255
|
|---|---|---|---|---|
153,000
|
public static boolean preTiger ( JavaClass jclass ) { return jclass . getMajor ( ) < JDK15_MAJOR || ( jclass . getMajor ( ) == JDK15_MAJOR && jclass . getMinor ( ) < JDK15_MINOR ) ; }
|
Checks if classfile was compiled for pre 1 . 5 target
| 64
| 13
|
153,001
|
public void addBugCategory ( BugCategory bugCategory ) { BugCategory old = bugCategories . get ( bugCategory . getCategory ( ) ) ; if ( old != null ) { throw new IllegalArgumentException ( "Category already exists" ) ; } bugCategories . put ( bugCategory . getCategory ( ) , bugCategory ) ; }
|
Add a BugCategory reported by the Plugin .
| 72
| 9
|
153,002
|
public DetectorFactory getFactoryByShortName ( final String shortName ) { return findFirstMatchingFactory ( factory -> factory . getShortName ( ) . equals ( shortName ) ) ; }
|
Look up a DetectorFactory by short name .
| 41
| 10
|
153,003
|
public DetectorFactory getFactoryByFullName ( final String fullName ) { return findFirstMatchingFactory ( factory -> factory . getFullName ( ) . equals ( fullName ) ) ; }
|
Look up a DetectorFactory by full name .
| 41
| 10
|
153,004
|
public Collection < TypeQualifierValue < ? > > getDirectlyRelevantTypeQualifiers ( MethodDescriptor m ) { Collection < TypeQualifierValue < ? > > result = methodToDirectlyRelevantQualifiersMap . get ( m ) ; if ( result != null ) { return result ; } return Collections . < TypeQualifierValue < ? > > emptyList ( ) ; }
|
Get the directly - relevant type qualifiers applied to given method .
| 83
| 12
|
153,005
|
public void setDirectlyRelevantTypeQualifiers ( MethodDescriptor methodDescriptor , Collection < TypeQualifierValue < ? > > qualifiers ) { methodToDirectlyRelevantQualifiersMap . put ( methodDescriptor , qualifiers ) ; allKnownQualifiers . addAll ( qualifiers ) ; }
|
Set the collection of directly - relevant type qualifiers for a given method .
| 65
| 14
|
153,006
|
private int adjustPriority ( int priority ) { try { Subtypes2 subtypes2 = AnalysisContext . currentAnalysisContext ( ) . getSubtypes2 ( ) ; if ( ! subtypes2 . hasSubtypes ( getClassDescriptor ( ) ) ) { priority ++ ; } else { Set < ClassDescriptor > mySubtypes = subtypes2 . getSubtypes ( getClassDescriptor ( ) ) ; String myPackagename = getThisClass ( ) . getPackageName ( ) ; for ( ClassDescriptor c : mySubtypes ) { if ( c . equals ( getClassDescriptor ( ) ) ) { continue ; } if ( ! c . getPackageName ( ) . equals ( myPackagename ) ) { priority -- ; break ; } } } } catch ( ClassNotFoundException e ) { bugReporter . reportMissingClass ( e ) ; } return priority ; }
|
Adjust the priority of a warning about to be reported .
| 194
| 11
|
153,007
|
void registerDetector ( DetectorFactory factory ) { if ( FindBugs . DEBUG ) { System . out . println ( "Registering detector: " + factory . getFullName ( ) ) ; } String detectorName = factory . getShortName ( ) ; if ( ! factoryList . contains ( factory ) ) { factoryList . add ( factory ) ; } else { LOGGER . log ( Level . WARNING , "Trying to add already registered factory: " + factory + ", " + factory . getPlugin ( ) ) ; } factoriesByName . put ( detectorName , factory ) ; factoriesByDetectorClassName . put ( factory . getFullName ( ) , factory ) ; }
|
Register a DetectorFactory .
| 145
| 6
|
153,008
|
public @ CheckForNull BugPattern lookupBugPattern ( String bugType ) { if ( bugType == null ) { return null ; } return bugPatternMap . get ( bugType ) ; }
|
Look up bug pattern .
| 40
| 5
|
153,009
|
public Collection < String > getBugCategories ( ) { ArrayList < String > result = new ArrayList <> ( categoryDescriptionMap . size ( ) ) ; for ( BugCategory c : categoryDescriptionMap . values ( ) ) { if ( ! c . isHidden ( ) ) { result . add ( c . getCategory ( ) ) ; } } return result ; }
|
Get a Collection containing all known bug category keys . E . g . CORRECTNESS MT_CORRECTNESS PERFORMANCE etc .
| 78
| 28
|
153,010
|
public static boolean isGetterMethod ( ClassContext classContext , Method method ) { MethodGen methodGen = classContext . getMethodGen ( method ) ; if ( methodGen == null ) { return false ; } InstructionList il = methodGen . getInstructionList ( ) ; // System.out.println("Checking getter method: " + method.getName()); if ( il . getLength ( ) > 60 ) { return false ; } int count = 0 ; Iterator < InstructionHandle > it = il . iterator ( ) ; while ( it . hasNext ( ) ) { InstructionHandle ih = it . next ( ) ; switch ( ih . getInstruction ( ) . getOpcode ( ) ) { case Const . GETFIELD : count ++ ; if ( count > 1 ) { return false ; } break ; case Const . PUTFIELD : case Const . BALOAD : case Const . CALOAD : case Const . DALOAD : case Const . FALOAD : case Const . IALOAD : case Const . LALOAD : case Const . SALOAD : case Const . AALOAD : case Const . BASTORE : case Const . CASTORE : case Const . DASTORE : case Const . FASTORE : case Const . IASTORE : case Const . LASTORE : case Const . SASTORE : case Const . AASTORE : case Const . PUTSTATIC : return false ; case Const . INVOKESTATIC : case Const . INVOKEVIRTUAL : case Const . INVOKEINTERFACE : case Const . INVOKESPECIAL : case Const . GETSTATIC : // no-op } } // System.out.println("Found getter method: " + method.getName()); return true ; }
|
Determine whether or not the the given method is a getter method . I . e . if it just returns the value of an instance field .
| 374
| 31
|
153,011
|
private FieldStats getStats ( XField field ) { FieldStats stats = statMap . get ( field ) ; if ( stats == null ) { stats = new FieldStats ( field ) ; statMap . put ( field , stats ) ; } return stats ; }
|
Get the access statistics for given field .
| 54
| 8
|
153,012
|
private static Set < Method > findLockedMethods ( ClassContext classContext , SelfCalls selfCalls , Set < CallSite > obviouslyLockedSites ) { JavaClass javaClass = classContext . getJavaClass ( ) ; Method [ ] methodList = javaClass . getMethods ( ) ; CallGraph callGraph = selfCalls . getCallGraph ( ) ; // Initially, assume all methods are locked Set < Method > lockedMethodSet = new HashSet <> ( ) ; // Assume all public methods are unlocked for ( Method method : methodList ) { if ( method . isSynchronized ( ) ) { lockedMethodSet . add ( method ) ; } } // Explore the self-call graph to find nonpublic methods // that can be called from an unlocked context. boolean change ; do { change = false ; for ( Iterator < CallGraphEdge > i = callGraph . edgeIterator ( ) ; i . hasNext ( ) ; ) { CallGraphEdge edge = i . next ( ) ; CallSite callSite = edge . getCallSite ( ) ; if ( obviouslyLockedSites . contains ( callSite ) || lockedMethodSet . contains ( callSite . getMethod ( ) ) ) { // Calling method is locked, so the called method // is also locked. CallGraphNode target = edge . getTarget ( ) ; if ( lockedMethodSet . add ( target . getMethod ( ) ) ) { change = true ; } } } } while ( change ) ; if ( DEBUG ) { System . out . println ( "Apparently locked methods:" ) ; for ( Method method : lockedMethodSet ) { System . out . println ( "\t" + method . getName ( ) ) ; } } // We assume that any methods left in the locked set // are called only from a locked context. return lockedMethodSet ; }
|
Find methods that appear to always be called from a locked context . We assume that nonpublic methods will only be called from within the class which is not really a valid assumption .
| 386
| 35
|
153,013
|
private static Set < CallSite > findObviouslyLockedCallSites ( ClassContext classContext , SelfCalls selfCalls ) throws CFGBuilderException , DataflowAnalysisException { ConstantPoolGen cpg = classContext . getConstantPoolGen ( ) ; // Find all obviously locked call sites Set < CallSite > obviouslyLockedSites = new HashSet <> ( ) ; for ( Iterator < CallSite > i = selfCalls . callSiteIterator ( ) ; i . hasNext ( ) ; ) { CallSite callSite = i . next ( ) ; Method method = callSite . getMethod ( ) ; Location location = callSite . getLocation ( ) ; InstructionHandle handle = location . getHandle ( ) ; // Only instance method calls qualify as candidates for // "obviously locked" Instruction ins = handle . getInstruction ( ) ; if ( ins . getOpcode ( ) == Const . INVOKESTATIC ) { continue ; } // Get lock set for site LockChecker lockChecker = classContext . getLockChecker ( method ) ; LockSet lockSet = lockChecker . getFactAtLocation ( location ) ; // Get value number frame for site ValueNumberDataflow vnaDataflow = classContext . getValueNumberDataflow ( method ) ; ValueNumberFrame frame = vnaDataflow . getFactAtLocation ( location ) ; // NOTE: if the CFG on which the value number analysis was performed // was pruned, there may be unreachable instructions. Therefore, // we can't assume the frame is valid. if ( ! frame . isValid ( ) ) { continue ; } // Find the ValueNumber of the receiver object int numConsumed = ins . consumeStack ( cpg ) ; MethodGen methodGen = classContext . getMethodGen ( method ) ; assert methodGen != null ; if ( numConsumed == Const . UNPREDICTABLE ) { throw new DataflowAnalysisException ( "Unpredictable stack consumption" , methodGen , handle ) ; } // if (DEBUG) System.out.println("Getting receiver for frame: " + // frame); ValueNumber instance = frame . getStackValue ( numConsumed - 1 ) ; // Is the instance locked? int lockCount = lockSet . getLockCount ( instance . getNumber ( ) ) ; if ( lockCount > 0 ) { // This is a locked call site obviouslyLockedSites . add ( callSite ) ; } } return obviouslyLockedSites ; }
|
Find all self - call sites that are obviously locked .
| 525
| 11
|
153,014
|
private static boolean implementsMap ( ClassDescriptor d ) { while ( d != null ) { try { // Do not report this warning for EnumMap: EnumMap.keySet()/get() iteration is as fast as entrySet() iteration if ( "java.util.EnumMap" . equals ( d . getDottedClassName ( ) ) ) { return false ; } // True if variable is itself declared as a Map if ( "java.util.Map" . equals ( d . getDottedClassName ( ) ) ) { return true ; } XClass classNameAndInfo = Global . getAnalysisCache ( ) . getClassAnalysis ( XClass . class , d ) ; ClassDescriptor is [ ] = classNameAndInfo . getInterfaceDescriptorList ( ) ; d = classNameAndInfo . getSuperclassDescriptor ( ) ; for ( ClassDescriptor i : is ) { if ( "java.util.Map" . equals ( i . getDottedClassName ( ) ) ) { return true ; } } } catch ( CheckedAnalysisException e ) { d = null ; } } return false ; }
|
Determine from the class descriptor for a variable whether that variable implements java . util . Map .
| 245
| 20
|
153,015
|
private void restoreDefaultSettings ( ) { if ( getProject ( ) != null ) { // By default, don't run FindBugs automatically chkEnableFindBugs . setSelection ( false ) ; chkRunAtFullBuild . setEnabled ( false ) ; FindBugsPreferenceInitializer . restoreDefaults ( projectStore ) ; } else { FindBugsPreferenceInitializer . restoreDefaults ( workspaceStore ) ; } currentUserPreferences = FindBugsPreferenceInitializer . createDefaultUserPreferences ( ) ; refreshUI ( currentUserPreferences ) ; }
|
Restore default settings . This just changes the dialog widgets - the user still needs to confirm by clicking the OK button .
| 123
| 24
|
153,016
|
@ Override public boolean performOk ( ) { reportConfigurationTab . performOk ( ) ; boolean analysisSettingsChanged = false ; boolean reporterSettingsChanged = false ; boolean needRedisplayMarkers = false ; if ( workspaceSettingsTab != null ) { workspaceSettingsTab . performOK ( ) ; } boolean pluginsChanged = false ; // Have user preferences for project changed? // If so, write them to the user preferences file & re-run builder if ( ! currentUserPreferences . equals ( origUserPreferences ) ) { pluginsChanged = ! currentUserPreferences . getCustomPlugins ( ) . equals ( origUserPreferences . getCustomPlugins ( ) ) ; // save only if we in the workspace page OR in the project page with // enabled // project settings if ( getProject ( ) == null || enableProjectCheck . getSelection ( ) ) { try { FindbugsPlugin . saveUserPreferences ( getProject ( ) , currentUserPreferences ) ; } catch ( CoreException e ) { FindbugsPlugin . getDefault ( ) . logException ( e , "Could not store SpotBugs preferences for project" ) ; } } if ( pluginsChanged ) { FindbugsPlugin . applyCustomDetectors ( true ) ; } } analysisSettingsChanged = pluginsChanged || areAnalysisPrefsChanged ( currentUserPreferences , origUserPreferences ) ; reporterSettingsChanged = ! currentUserPreferences . getFilterSettings ( ) . equals ( origUserPreferences . getFilterSettings ( ) ) ; boolean markerSeveritiesChanged = reportConfigurationTab . isMarkerSeveritiesChanged ( ) ; needRedisplayMarkers = pluginsChanged || markerSeveritiesChanged || reporterSettingsChanged ; boolean builderEnabled = false ; if ( getProject ( ) != null ) { builderEnabled = chkEnableFindBugs . getSelection ( ) ; // Update whether or not FindBugs is run automatically. if ( ! natureEnabled && builderEnabled ) { addNature ( ) ; } else if ( natureEnabled && ! builderEnabled ) { removeNature ( ) ; } // update the flag to match the incremental/not property builderEnabled &= chkRunAtFullBuild . getSelection ( ) ; boolean newSelection = enableProjectCheck . getSelection ( ) ; if ( projectPropsInitiallyEnabled != newSelection ) { analysisSettingsChanged = true ; FindbugsPlugin . setProjectSettingsEnabled ( project , projectStore , newSelection ) ; } } if ( analysisSettingsChanged ) { // trigger a Findbugs rebuild here if ( builderEnabled ) { runFindbugsBuilder ( ) ; needRedisplayMarkers = false ; } else { if ( ! getPreferenceStore ( ) . getBoolean ( FindBugsConstants . DONT_REMIND_ABOUT_FULL_BUILD ) ) { remindAboutFullBuild ( ) ; } } } if ( needRedisplayMarkers ) { redisplayMarkers ( ) ; } return true ; }
|
Will be called when the user presses the OK button .
| 623
| 11
|
153,017
|
public Token next ( ) throws IOException { skipWhitespace ( ) ; int c = reader . read ( ) ; if ( c < 0 ) { return new Token ( Token . EOF ) ; } else if ( c == ' ' ) { return new Token ( Token . EOL ) ; } else if ( c == ' ' || c == ' ' ) { return munchString ( c ) ; } else if ( c == ' ' ) { return maybeComment ( ) ; } else if ( single . get ( c ) ) { return new Token ( Token . SINGLE , String . valueOf ( ( char ) c ) ) ; } else { reader . unread ( c ) ; return parseWord ( ) ; } }
|
Get the next Token in the stream .
| 154
| 8
|
153,018
|
private void reportResultsToConsole ( ) { if ( ! isStreamReportingEnabled ( ) ) { return ; } printToStream ( "Finished, found: " + bugCount + " bugs" ) ; ConfigurableXmlOutputStream xmlStream = new ConfigurableXmlOutputStream ( stream , true ) ; ProjectStats stats = bugCollection . getProjectStats ( ) ; printToStream ( "\nFootprint: " + new Footprint ( stats . getBaseFootprint ( ) ) . toString ( ) ) ; Profiler profiler = stats . getProfiler ( ) ; PrintStream printStream ; try { printStream = new PrintStream ( stream , false , "UTF-8" ) ; } catch ( UnsupportedEncodingException e1 ) { // can never happen with UTF-8 return ; } printToStream ( "\nTotal time:" ) ; profiler . report ( new Profiler . TotalTimeComparator ( profiler ) , new Profiler . FilterByTime ( 10000000 ) , printStream ) ; printToStream ( "\nTotal calls:" ) ; int numClasses = stats . getNumClasses ( ) ; if ( numClasses > 0 ) { profiler . report ( new Profiler . TotalCallsComparator ( profiler ) , new Profiler . FilterByCalls ( numClasses ) , printStream ) ; printToStream ( "\nTime per call:" ) ; profiler . report ( new Profiler . TimePerCallComparator ( profiler ) , new Profiler . FilterByTimePerCall ( 10000000 / numClasses ) , printStream ) ; } try { xmlStream . finish ( ) ; } catch ( IOException e ) { FindbugsPlugin . getDefault ( ) . logException ( e , "Print to console failed" ) ; } }
|
If there is a FB console opened report results and statistics to it .
| 381
| 14
|
153,019
|
public ByteCodePattern addWild ( int numWild ) { Wild wild = isLastWild ( ) ; if ( wild != null ) { wild . setMinAndMax ( 0 , numWild ) ; } else { addElement ( new Wild ( numWild ) ) ; } return this ; }
|
Add a wildcard to match between 0 and given number of instructions . If there is already a wildcard at the end of the current pattern resets its max value to that given .
| 60
| 37
|
153,020
|
public Edge lookupEdgeById ( int id ) { Iterator < Edge > i = edgeIterator ( ) ; while ( i . hasNext ( ) ) { Edge edge = i . next ( ) ; if ( edge . getId ( ) == id ) { return edge ; } } return null ; }
|
Look up an Edge by its id .
| 62
| 8
|
153,021
|
public BasicBlock lookupBlockByLabel ( int blockLabel ) { for ( Iterator < BasicBlock > i = blockIterator ( ) ; i . hasNext ( ) ; ) { BasicBlock basicBlock = i . next ( ) ; if ( basicBlock . getLabel ( ) == blockLabel ) { return basicBlock ; } } return null ; }
|
Look up a BasicBlock by its unique label .
| 72
| 10
|
153,022
|
public Collection < Location > orderedLocations ( ) { TreeSet < Location > tree = new TreeSet <> ( ) ; for ( Iterator < Location > locs = locationIterator ( ) ; locs . hasNext ( ) ; ) { Location loc = locs . next ( ) ; tree . add ( loc ) ; } return tree ; }
|
Returns a collection of locations ordered according to the compareTo ordering over locations . If you want to list all the locations in a CFG for debugging purposes this is a good order to do so in .
| 73
| 40
|
153,023
|
public Collection < BasicBlock > getBlocks ( BitSet labelSet ) { LinkedList < BasicBlock > result = new LinkedList <> ( ) ; for ( Iterator < BasicBlock > i = blockIterator ( ) ; i . hasNext ( ) ; ) { BasicBlock block = i . next ( ) ; if ( labelSet . get ( block . getLabel ( ) ) ) { result . add ( block ) ; } } return result ; }
|
Get Collection of basic blocks whose IDs are specified by given BitSet .
| 96
| 14
|
153,024
|
public Collection < BasicBlock > getBlocksContainingInstructionWithOffset ( int offset ) { LinkedList < BasicBlock > result = new LinkedList <> ( ) ; for ( Iterator < BasicBlock > i = blockIterator ( ) ; i . hasNext ( ) ; ) { BasicBlock block = i . next ( ) ; if ( block . containsInstructionWithOffset ( offset ) ) { result . add ( block ) ; } } return result ; }
|
Get a Collection of basic blocks which contain the bytecode instruction with given offset .
| 98
| 16
|
153,025
|
public Collection < Location > getLocationsContainingInstructionWithOffset ( int offset ) { LinkedList < Location > result = new LinkedList <> ( ) ; for ( Iterator < Location > i = locationIterator ( ) ; i . hasNext ( ) ; ) { Location location = i . next ( ) ; if ( location . getHandle ( ) . getPosition ( ) == offset ) { result . add ( location ) ; } } return result ; }
|
Get a Collection of Locations which specify the instruction at given bytecode offset .
| 98
| 15
|
153,026
|
public int getNumNonExceptionSucessors ( BasicBlock block ) { int numNonExceptionSuccessors = block . getNumNonExceptionSuccessors ( ) ; if ( numNonExceptionSuccessors < 0 ) { numNonExceptionSuccessors = 0 ; for ( Iterator < Edge > i = outgoingEdgeIterator ( block ) ; i . hasNext ( ) ; ) { Edge edge = i . next ( ) ; if ( ! edge . isExceptionEdge ( ) ) { numNonExceptionSuccessors ++ ; } } block . setNumNonExceptionSuccessors ( numNonExceptionSuccessors ) ; } return numNonExceptionSuccessors ; }
|
Get number of non - exception control successors of given basic block .
| 132
| 13
|
153,027
|
public Location getLocationAtEntry ( ) { InstructionHandle handle = getEntry ( ) . getFirstInstruction ( ) ; assert handle != null ; return new Location ( handle , getEntry ( ) ) ; }
|
Get the Location representing the entry to the CFG . Note that this is a fake Location and shouldn t be relied on to yield source line information .
| 43
| 30
|
153,028
|
public void addPlugin ( Plugin plugin ) throws OrderingConstraintException { if ( DEBUG ) { System . out . println ( "Adding plugin " + plugin . getPluginId ( ) + " to execution plan" ) ; } pluginList . add ( plugin ) ; // Add ordering constraints copyTo ( plugin . interPassConstraintIterator ( ) , interPassConstraintList ) ; copyTo ( plugin . intraPassConstraintIterator ( ) , intraPassConstraintList ) ; // Add detector factories for ( DetectorFactory factory : plugin . getDetectorFactories ( ) ) { if ( DEBUG ) { System . out . println ( " Detector factory " + factory . getShortName ( ) ) ; } if ( factoryMap . put ( factory . getFullName ( ) , factory ) != null ) { throw new OrderingConstraintException ( "Detector " + factory . getFullName ( ) + " is defined by more than one plugin" ) ; } } }
|
Add a Plugin whose Detectors should be added to the execution plan .
| 210
| 14
|
153,029
|
private void assignToPass ( DetectorFactory factory , AnalysisPass pass ) { pass . addToPass ( factory ) ; assignedToPassSet . add ( factory ) ; }
|
Make a DetectorFactory a member of an AnalysisPass .
| 36
| 12
|
153,030
|
public void execute ( InstructionScannerGenerator generator ) { // Pump the instructions in the path through the generator and all // generated scanners while ( edgeIter . hasNext ( ) ) { Edge edge = edgeIter . next ( ) ; BasicBlock source = edge . getSource ( ) ; if ( DEBUG ) { System . out . println ( "ISD: scanning instructions in block " + source . getLabel ( ) ) ; } // Traverse all instructions in the source block Iterator < InstructionHandle > i = source . instructionIterator ( ) ; int count = 0 ; while ( i . hasNext ( ) ) { InstructionHandle handle = i . next ( ) ; // Check if the generator wants to create a new scanner if ( generator . start ( handle ) ) { scannerList . add ( generator . createScanner ( ) ) ; } // Pump the instruction into all scanners for ( InstructionScanner scanner : scannerList ) { scanner . scanInstruction ( handle ) ; } ++ count ; } if ( DEBUG ) { System . out . println ( "ISD: scanned " + count + " instructions" ) ; } // Now that we've finished the source block, pump the edge // into all scanners for ( InstructionScanner scanner : scannerList ) { scanner . traverseEdge ( edge ) ; } } }
|
Execute by driving the InstructionScannerGenerator over all instructions . Each generated InstructionScanner is driven over all instructions and edges .
| 271
| 27
|
153,031
|
@ SuppressWarnings ( "rawtypes" ) @ Override protected IProject [ ] build ( int kind , Map args , IProgressMonitor monitor ) throws CoreException { monitor . subTask ( "Running SpotBugs..." ) ; switch ( kind ) { case IncrementalProjectBuilder . FULL_BUILD : { FindBugs2Eclipse . cleanClassClache ( getProject ( ) ) ; if ( FindbugsPlugin . getUserPreferences ( getProject ( ) ) . isRunAtFullBuild ( ) ) { if ( DEBUG ) { System . out . println ( "FULL BUILD" ) ; } doBuild ( args , monitor , kind ) ; } else { // TODO probably worth to cleanup? // MarkerUtil.removeMarkers(getProject()); } break ; } case IncrementalProjectBuilder . INCREMENTAL_BUILD : { if ( DEBUG ) { System . out . println ( "INCREMENTAL BUILD" ) ; } doBuild ( args , monitor , kind ) ; break ; } case IncrementalProjectBuilder . AUTO_BUILD : { if ( DEBUG ) { System . out . println ( "AUTO BUILD" ) ; } doBuild ( args , monitor , kind ) ; break ; } default : { FindbugsPlugin . getDefault ( ) . logWarning ( "UKNOWN BUILD kind" + kind ) ; doBuild ( args , monitor , kind ) ; break ; } } return null ; }
|
Run the builder .
| 310
| 4
|
153,032
|
protected void work ( final IResource resource , final List < WorkItem > resources , IProgressMonitor monitor ) { IPreferenceStore store = FindbugsPlugin . getPluginPreferences ( getProject ( ) ) ; boolean runAsJob = store . getBoolean ( FindBugsConstants . KEY_RUN_ANALYSIS_AS_EXTRA_JOB ) ; FindBugsJob fbJob = new StartedFromBuilderJob ( "Finding bugs in " + resource . getName ( ) + "..." , resource , resources ) ; if ( runAsJob ) { // run asynchronously, so there might be more similar jobs waiting to run if ( DEBUG ) { FindbugsPlugin . log ( "cancelSimilarJobs" ) ; } FindBugsJob . cancelSimilarJobs ( fbJob ) ; if ( DEBUG ) { FindbugsPlugin . log ( "scheduleAsSystem" ) ; } fbJob . scheduleAsSystem ( ) ; if ( DEBUG ) { FindbugsPlugin . log ( "done scheduleAsSystem" ) ; } } else { // run synchronously (in same thread) if ( DEBUG ) { FindbugsPlugin . log ( "running fbJob" ) ; } fbJob . run ( monitor ) ; if ( DEBUG ) { FindbugsPlugin . log ( "done fbJob" ) ; } } }
|
Run a FindBugs analysis on the given resource as build job BUT not delaying the current Java build
| 286
| 20
|
153,033
|
public static @ DottedClassName String getMissingClassName ( ClassNotFoundException ex ) { // If the exception has a ResourceNotFoundException as the cause, // then we have an easy answer. Throwable cause = ex . getCause ( ) ; if ( cause instanceof ResourceNotFoundException ) { String resourceName = ( ( ResourceNotFoundException ) cause ) . getResourceName ( ) ; if ( resourceName != null ) { ClassDescriptor classDesc = DescriptorFactory . createClassDescriptorFromResourceName ( resourceName ) ; return classDesc . toDottedClassName ( ) ; } } if ( ex . getMessage ( ) == null ) { return null ; } // Try the regular expression patterns to parse the class name // from the exception message. for ( Pattern pattern : patternList ) { Matcher matcher = pattern . matcher ( ex . getMessage ( ) ) ; if ( matcher . matches ( ) ) { String className = matcher . group ( 1 ) ; ClassName . assertIsDotted ( className ) ; return className ; } } return null ; }
|
Get the name of the missing class from a ClassNotFoundException .
| 235
| 14
|
153,034
|
public void addFieldLine ( String className , String fieldName , SourceLineRange range ) { fieldLineMap . put ( new FieldDescriptor ( className , fieldName ) , range ) ; }
|
Add a line number entry for a field .
| 43
| 9
|
153,035
|
public void addMethodLine ( String className , String methodName , String methodSignature , SourceLineRange range ) { methodLineMap . put ( new MethodDescriptor ( className , methodName , methodSignature ) , range ) ; }
|
Add a line number entry for a method .
| 52
| 9
|
153,036
|
public @ CheckForNull SourceLineRange getFieldLine ( String className , String fieldName ) { return fieldLineMap . get ( new FieldDescriptor ( className , fieldName ) ) ; }
|
Look up the line number range for a field .
| 43
| 10
|
153,037
|
public @ CheckForNull SourceLineRange getMethodLine ( String className , String methodName , String methodSignature ) { return methodLineMap . get ( new MethodDescriptor ( className , methodName , methodSignature ) ) ; }
|
Look up the line number range for a method .
| 52
| 10
|
153,038
|
private static String parseVersionNumber ( String line ) { StringTokenizer tokenizer = new StringTokenizer ( line , " \t" ) ; if ( ! expect ( tokenizer , "sourceInfo" ) || ! expect ( tokenizer , "version" ) || ! tokenizer . hasMoreTokens ( ) ) { return null ; } return tokenizer . nextToken ( ) ; }
|
Parse the sourceInfo version string .
| 80
| 8
|
153,039
|
private static boolean expect ( StringTokenizer tokenizer , String token ) { if ( ! tokenizer . hasMoreTokens ( ) ) { return false ; } String s = tokenizer . nextToken ( ) ; if ( DEBUG ) { System . out . println ( "token=" + s ) ; } return s . equals ( token ) ; }
|
Expect a particular token string to be returned by the given StringTokenizer .
| 71
| 16
|
153,040
|
private int compareClassesAllowingNull ( ClassAnnotation lhs , ClassAnnotation rhs ) { if ( lhs == null || rhs == null ) { return compareNullElements ( lhs , rhs ) ; } String lhsClassName = classNameRewriter . rewriteClassName ( lhs . getClassName ( ) ) ; String rhsClassName = classNameRewriter . rewriteClassName ( rhs . getClassName ( ) ) ; if ( DEBUG ) { System . err . println ( "Comparing " + lhsClassName + " and " + rhsClassName ) ; } int cmp = lhsClassName . compareTo ( rhsClassName ) ; if ( DEBUG ) { System . err . println ( "\t==> " + cmp ) ; } return cmp ; }
|
Compare class annotations .
| 176
| 4
|
153,041
|
static int countFilteredBugs ( ) { int result = 0 ; for ( BugLeafNode bug : getMainBugSet ( ) . mainList ) { if ( suppress ( bug ) ) { result ++ ; } } return result ; }
|
used to update the status bar in mainframe with the number of bugs that are filtered out
| 51
| 18
|
153,042
|
public BugSet query ( BugAspects a ) { BugSet result = this ; for ( SortableValue sp : a ) { result = result . query ( sp ) ; } return result ; }
|
Gives you back the BugSet containing all bugs that match your query
| 41
| 14
|
153,043
|
private static Location pcToLocation ( ClassContext classContext , Method method , int pc ) throws CFGBuilderException { CFG cfg = classContext . getCFG ( method ) ; for ( Iterator < Location > i = cfg . locationIterator ( ) ; i . hasNext ( ) ; ) { Location location = i . next ( ) ; if ( location . getHandle ( ) . getPosition ( ) == pc ) { return location ; } } return null ; }
|
Get a Location matching the given PC value . Because of JSR subroutines there may be multiple Locations referring to the given instruction . This method simply returns one of them arbitrarily .
| 101
| 37
|
153,044
|
private static void addReceiverObjectType ( WarningPropertySet < WarningProperty > propertySet , ClassContext classContext , Method method , Location location ) { try { Instruction ins = location . getHandle ( ) . getInstruction ( ) ; if ( ! receiverObjectInstructionSet . get ( ins . getOpcode ( ) ) ) { return ; } TypeDataflow typeDataflow = classContext . getTypeDataflow ( method ) ; TypeFrame frame = typeDataflow . getFactAtLocation ( location ) ; if ( frame . isValid ( ) ) { Type type = frame . getInstance ( ins , classContext . getConstantPoolGen ( ) ) ; if ( type instanceof ReferenceType ) { propertySet . setProperty ( GeneralWarningProperty . RECEIVER_OBJECT_TYPE , type . toString ( ) ) ; } } } catch ( DataflowAnalysisException e ) { // Ignore } catch ( CFGBuilderException e ) { // Ignore } }
|
Add a RECEIVER_OBJECT_TYPE warning property for a particular location in a method to given warning property set .
| 204
| 25
|
153,045
|
private Set < String > buildClassSet ( BugCollection bugCollection ) { Set < String > classSet = new HashSet <> ( ) ; for ( Iterator < BugInstance > i = bugCollection . iterator ( ) ; i . hasNext ( ) ; ) { BugInstance warning = i . next ( ) ; for ( Iterator < BugAnnotation > j = warning . annotationIterator ( ) ; j . hasNext ( ) ; ) { BugAnnotation annotation = j . next ( ) ; if ( ! ( annotation instanceof ClassAnnotation ) ) { continue ; } classSet . add ( ( ( ClassAnnotation ) annotation ) . getClassName ( ) ) ; } } return classSet ; }
|
Find set of classes referenced in given BugCollection .
| 148
| 10
|
153,046
|
private void suppressWarningsIfOneLiveStoreOnLine ( BugAccumulator accumulator , BitSet liveStoreSourceLineSet ) { if ( ! SUPPRESS_IF_AT_LEAST_ONE_LIVE_STORE_ON_LINE ) { return ; } // Eliminate any accumulated warnings for instructions // that (due to inlining) *can* be live stores. entryLoop : for ( Iterator < ? extends BugInstance > i = accumulator . uniqueBugs ( ) . iterator ( ) ; i . hasNext ( ) ; ) { for ( SourceLineAnnotation annotation : accumulator . locations ( i . next ( ) ) ) { if ( liveStoreSourceLineSet . get ( annotation . getStartLine ( ) ) ) { // This instruction can be a live store; don't report // it as a warning. i . remove ( ) ; continue entryLoop ; } } } }
|
If feature is enabled suppress warnings where there is at least one live store on the line where the warning would be reported .
| 191
| 24
|
153,047
|
private void countLocalStoresLoadsAndIncrements ( int [ ] localStoreCount , int [ ] localLoadCount , int [ ] localIncrementCount , CFG cfg ) { for ( Iterator < Location > i = cfg . locationIterator ( ) ; i . hasNext ( ) ; ) { Location location = i . next ( ) ; if ( location . getBasicBlock ( ) . isExceptionHandler ( ) ) { continue ; } boolean isStore = isStore ( location ) ; boolean isLoad = isLoad ( location ) ; if ( ! isStore && ! isLoad ) { continue ; } IndexedInstruction ins = ( IndexedInstruction ) location . getHandle ( ) . getInstruction ( ) ; int local = ins . getIndex ( ) ; if ( ins instanceof IINC ) { localStoreCount [ local ] ++ ; localLoadCount [ local ] ++ ; localIncrementCount [ local ] ++ ; } else if ( isStore ) { localStoreCount [ local ] ++ ; } else { localLoadCount [ local ] ++ ; } } }
|
Count stores loads and increments of local variables in method whose CFG is given .
| 228
| 16
|
153,048
|
private boolean isStore ( Location location ) { Instruction ins = location . getHandle ( ) . getInstruction ( ) ; return ( ins instanceof StoreInstruction ) || ( ins instanceof IINC ) ; }
|
Is instruction at given location a store?
| 44
| 8
|
153,049
|
private boolean isLoad ( Location location ) { Instruction ins = location . getHandle ( ) . getInstruction ( ) ; return ( ins instanceof LoadInstruction ) || ( ins instanceof IINC ) ; }
|
Is instruction at given location a load?
| 44
| 8
|
153,050
|
public AnnotationVisitor getAnnotationVisitor ( ) { return new AnnotationVisitor ( FindBugsASM . ASM_VERSION ) { @ Override public void visit ( String name , Object value ) { name = canonicalString ( name ) ; valueMap . put ( name , value ) ; } /* * (non-Javadoc) * * @see * org.objectweb.asm.AnnotationVisitor#visitAnnotation(java.lang * .String, java.lang.String) */ @ Override public AnnotationVisitor visitAnnotation ( String name , String desc ) { name = canonicalString ( name ) ; AnnotationValue newValue = new AnnotationValue ( desc ) ; valueMap . put ( name , newValue ) ; typeMap . put ( name , desc ) ; return newValue . getAnnotationVisitor ( ) ; } /* * (non-Javadoc) * * @see * org.objectweb.asm.AnnotationVisitor#visitArray(java.lang.String) */ @ Override public AnnotationVisitor visitArray ( String name ) { name = canonicalString ( name ) ; return new AnnotationArrayVisitor ( name ) ; } /* * (non-Javadoc) * * @see org.objectweb.asm.AnnotationVisitor#visitEnd() */ @ Override public void visitEnd ( ) { } /* * (non-Javadoc) * * @see * org.objectweb.asm.AnnotationVisitor#visitEnum(java.lang.String, * java.lang.String, java.lang.String) */ @ Override public void visitEnum ( String name , String desc , String value ) { name = canonicalString ( name ) ; valueMap . put ( name , new EnumValue ( desc , value ) ) ; typeMap . put ( name , desc ) ; } } ; }
|
Get an AnnotationVisitor which can populate this AnnotationValue object .
| 412
| 15
|
153,051
|
private Constant readConstant ( ) throws InvalidClassFileFormatException , IOException { int tag = in . readUnsignedByte ( ) ; if ( tag < 0 || tag >= CONSTANT_FORMAT_MAP . length ) { throw new InvalidClassFileFormatException ( expectedClassDescriptor , codeBaseEntry ) ; } String format = CONSTANT_FORMAT_MAP [ tag ] ; if ( format == null ) { throw new InvalidClassFileFormatException ( expectedClassDescriptor , codeBaseEntry ) ; } Object [ ] data = new Object [ format . length ( ) ] ; for ( int i = 0 ; i < format . length ( ) ; i ++ ) { char spec = format . charAt ( i ) ; switch ( spec ) { case ' ' : data [ i ] = in . readUTF ( ) ; break ; case ' ' : data [ i ] = in . readInt ( ) ; break ; case ' ' : data [ i ] = Float . valueOf ( in . readFloat ( ) ) ; break ; case ' ' : data [ i ] = in . readLong ( ) ; break ; case ' ' : data [ i ] = Double . valueOf ( in . readDouble ( ) ) ; break ; case ' ' : data [ i ] = in . readUnsignedShort ( ) ; break ; case ' ' : data [ i ] = in . readUnsignedByte ( ) ; break ; default : throw new IllegalStateException ( ) ; } } return new Constant ( tag , data ) ; }
|
Read a constant from the constant pool . Return null for
| 325
| 11
|
153,052
|
private String getUtf8String ( int refIndex ) throws InvalidClassFileFormatException { checkConstantPoolIndex ( refIndex ) ; Constant refConstant = constantPool [ refIndex ] ; checkConstantTag ( refConstant , IClassConstants . CONSTANT_Utf8 ) ; return ( String ) refConstant . data [ 0 ] ; }
|
Get the UTF - 8 string constant at given constant pool index .
| 78
| 13
|
153,053
|
private void checkConstantPoolIndex ( int index ) throws InvalidClassFileFormatException { if ( index < 0 || index >= constantPool . length || constantPool [ index ] == null ) { throw new InvalidClassFileFormatException ( expectedClassDescriptor , codeBaseEntry ) ; } }
|
Check that a constant pool index is valid .
| 61
| 9
|
153,054
|
private void checkConstantTag ( Constant constant , int expectedTag ) throws InvalidClassFileFormatException { if ( constant . tag != expectedTag ) { throw new InvalidClassFileFormatException ( expectedClassDescriptor , codeBaseEntry ) ; } }
|
Check that a constant has the expected tag .
| 52
| 9
|
153,055
|
private String getSignatureFromNameAndType ( int index ) throws InvalidClassFileFormatException { checkConstantPoolIndex ( index ) ; Constant constant = constantPool [ index ] ; checkConstantTag ( constant , IClassConstants . CONSTANT_NameAndType ) ; return getUtf8String ( ( Integer ) constant . data [ 1 ] ) ; }
|
Get the signature from a CONSTANT_NameAndType .
| 78
| 13
|
153,056
|
private void checkUnconditionalDerefDatabase ( Location location , ValueNumberFrame vnaFrame , UnconditionalValueDerefSet fact ) throws DataflowAnalysisException { ConstantPoolGen constantPool = methodGen . getConstantPool ( ) ; for ( ValueNumber vn : checkUnconditionalDerefDatabase ( location , vnaFrame , constantPool , invDataflow . getFactAtLocation ( location ) , typeDataflow ) ) { fact . addDeref ( vn , location ) ; } }
|
Check method call at given location to see if it unconditionally dereferences a parameter . Mark any such arguments as derefs .
| 111
| 27
|
153,057
|
private void checkInstance ( Location location , ValueNumberFrame vnaFrame , UnconditionalValueDerefSet fact ) throws DataflowAnalysisException { // See if this instruction has a null check. // If it does, the fall through predecessor will be // identify itself as the null check. if ( ! location . isFirstInstructionInBasicBlock ( ) ) { return ; } if ( invDataflow == null ) { return ; } BasicBlock fallThroughPredecessor = cfg . getPredecessorWithEdgeType ( location . getBasicBlock ( ) , EdgeTypes . FALL_THROUGH_EDGE ) ; if ( fallThroughPredecessor == null || ! fallThroughPredecessor . isNullCheck ( ) ) { return ; } // Get the null-checked value ValueNumber vn = vnaFrame . getInstance ( location . getHandle ( ) . getInstruction ( ) , methodGen . getConstantPool ( ) ) ; // Ignore dereferences of this if ( ! methodGen . isStatic ( ) ) { ValueNumber v = vnaFrame . getValue ( 0 ) ; if ( v . equals ( vn ) ) { return ; } } if ( vn . hasFlag ( ValueNumber . CONSTANT_CLASS_OBJECT ) ) { return ; } IsNullValueFrame startFact = null ; startFact = invDataflow . getStartFact ( fallThroughPredecessor ) ; if ( ! startFact . isValid ( ) ) { return ; } int slot = startFact . getInstanceSlot ( location . getHandle ( ) . getInstruction ( ) , methodGen . getConstantPool ( ) ) ; if ( ! reportDereference ( startFact , slot ) ) { return ; } if ( DEBUG ) { System . out . println ( "FOUND GUARANTEED DEREFERENCE" ) ; System . out . println ( "Load: " + vnaFrame . getLoad ( vn ) ) ; System . out . println ( "Pred: " + fallThroughPredecessor ) ; System . out . println ( "startFact: " + startFact ) ; System . out . println ( "Location: " + location ) ; System . out . println ( "Value number frame: " + vnaFrame ) ; System . out . println ( "Dereferenced valueNumber: " + vn ) ; System . out . println ( "invDataflow: " + startFact ) ; System . out . println ( "IGNORE_DEREF_OF_NCP: " + IGNORE_DEREF_OF_NCP ) ; } // Mark the value number as being dereferenced at this location fact . addDeref ( vn , location ) ; }
|
Check to see if the instruction has a null check associated with it and if so add a dereference .
| 584
| 21
|
153,058
|
private UnconditionalValueDerefSet duplicateFact ( UnconditionalValueDerefSet fact ) { UnconditionalValueDerefSet copyOfFact = createFact ( ) ; copy ( fact , copyOfFact ) ; fact = copyOfFact ; return fact ; }
|
Return a duplicate of given dataflow fact .
| 59
| 9
|
153,059
|
private @ CheckForNull ValueNumber findValueKnownNonnullOnBranch ( UnconditionalValueDerefSet fact , Edge edge ) { IsNullValueFrame invFrame = invDataflow . getResultFact ( edge . getSource ( ) ) ; if ( ! invFrame . isValid ( ) ) { return null ; } IsNullConditionDecision decision = invFrame . getDecision ( ) ; if ( decision == null ) { return null ; } IsNullValue inv = decision . getDecision ( edge . getType ( ) ) ; if ( inv == null || ! inv . isDefinitelyNotNull ( ) ) { return null ; } ValueNumber value = decision . getValue ( ) ; if ( DEBUG ) { System . out . println ( "Value number " + value + " is known nonnull on " + edge ) ; } return value ; }
|
Clear deref sets of values if this edge is the non - null branch of an if comparison .
| 182
| 20
|
153,060
|
private boolean isExceptionEdge ( Edge edge ) { boolean isExceptionEdge = edge . isExceptionEdge ( ) ; if ( isExceptionEdge ) { if ( DEBUG ) { System . out . println ( "NOT Ignoring " + edge ) ; } return true ; // false } if ( edge . getType ( ) != EdgeTypes . FALL_THROUGH_EDGE ) { return false ; } InstructionHandle h = edge . getSource ( ) . getLastInstruction ( ) ; return h != null && h . getInstruction ( ) instanceof IFNONNULL && isNullCheck ( h , methodGen . getConstantPool ( ) ) ; }
|
Determine whether dataflow should be propagated on given edge .
| 139
| 14
|
153,061
|
public static boolean isSubtype ( ReferenceType t , ReferenceType possibleSupertype ) throws ClassNotFoundException { return Global . getAnalysisCache ( ) . getDatabase ( Subtypes2 . class ) . isSubtype ( t , possibleSupertype ) ; }
|
Determine if one reference type is a subtype of another .
| 54
| 14
|
153,062
|
public static boolean isMonitorWait ( String methodName , String methodSig ) { return "wait" . equals ( methodName ) && ( "()V" . equals ( methodSig ) || "(J)V" . equals ( methodSig ) || "(JI)V" . equals ( methodSig ) ) ; }
|
Determine if method whose name and signature is specified is a monitor wait operation .
| 70
| 17
|
153,063
|
public static boolean isMonitorNotify ( String methodName , String methodSig ) { return ( "notify" . equals ( methodName ) || "notifyAll" . equals ( methodName ) ) && "()V" . equals ( methodSig ) ; }
|
Determine if method whose name and signature is specified is a monitor notify operation .
| 57
| 17
|
153,064
|
public static boolean isMonitorNotify ( Instruction ins , ConstantPoolGen cpg ) { if ( ! ( ins instanceof InvokeInstruction ) ) { return false ; } if ( ins . getOpcode ( ) == Const . INVOKESTATIC ) { return false ; } InvokeInstruction inv = ( InvokeInstruction ) ins ; String methodName = inv . getMethodName ( cpg ) ; String methodSig = inv . getSignature ( cpg ) ; return isMonitorNotify ( methodName , methodSig ) ; }
|
Determine if given Instruction is a monitor wait .
| 117
| 11
|
153,065
|
public static JavaClassAndMethod visitSuperClassMethods ( JavaClassAndMethod method , JavaClassAndMethodChooser chooser ) throws ClassNotFoundException { return findMethod ( method . getJavaClass ( ) . getSuperClasses ( ) , method . getMethod ( ) . getName ( ) , method . getMethod ( ) . getSignature ( ) , chooser ) ; }
|
Visit all superclass methods which the given method overrides .
| 81
| 12
|
153,066
|
public static JavaClassAndMethod visitSuperInterfaceMethods ( JavaClassAndMethod method , JavaClassAndMethodChooser chooser ) throws ClassNotFoundException { return findMethod ( method . getJavaClass ( ) . getAllInterfaces ( ) , method . getMethod ( ) . getName ( ) , method . getMethod ( ) . getSignature ( ) , chooser ) ; }
|
Visit all superinterface methods which the given method implements .
| 81
| 11
|
153,067
|
public static Set < JavaClassAndMethod > resolveMethodCallTargets ( ReferenceType receiverType , InvokeInstruction invokeInstruction , ConstantPoolGen cpg ) throws ClassNotFoundException { return resolveMethodCallTargets ( receiverType , invokeInstruction , cpg , false ) ; }
|
Resolve possible instance method call targets . Assumes that invokevirtual and invokeinterface methods may call any subtype of the receiver class .
| 63
| 27
|
153,068
|
@ Deprecated public static boolean isConcrete ( XMethod xmethod ) { int accessFlags = xmethod . getAccessFlags ( ) ; return ( accessFlags & Const . ACC_ABSTRACT ) == 0 && ( accessFlags & Const . ACC_NATIVE ) == 0 ; }
|
Return whether or not the given method is concrete .
| 60
| 10
|
153,069
|
public static Field findField ( String className , String fieldName ) throws ClassNotFoundException { JavaClass jclass = Repository . lookupClass ( className ) ; while ( jclass != null ) { Field [ ] fieldList = jclass . getFields ( ) ; for ( Field field : fieldList ) { if ( field . getName ( ) . equals ( fieldName ) ) { return field ; } } jclass = jclass . getSuperClass ( ) ; } return null ; }
|
Find a field with given name defined in given class .
| 105
| 11
|
153,070
|
public static boolean isInnerClassAccess ( INVOKESTATIC inv , ConstantPoolGen cpg ) { String methodName = inv . getName ( cpg ) ; return methodName . startsWith ( "access$" ) ; }
|
Determine whether the given INVOKESTATIC instruction is an inner - class field accessor method .
| 50
| 22
|
153,071
|
public static InnerClassAccess getInnerClassAccess ( INVOKESTATIC inv , ConstantPoolGen cpg ) throws ClassNotFoundException { String className = inv . getClassName ( cpg ) ; String methodName = inv . getName ( cpg ) ; String methodSig = inv . getSignature ( cpg ) ; InnerClassAccess access = AnalysisContext . currentAnalysisContext ( ) . getInnerClassAccessMap ( ) . getInnerClassAccess ( className , methodName ) ; return ( access != null && access . getMethodSignature ( ) . equals ( methodSig ) ) ? access : null ; }
|
Get the InnerClassAccess for access method called by given INVOKESTATIC .
| 136
| 17
|
153,072
|
@ SuppressWarnings ( "unchecked" ) @ Override public synchronized Enumeration < Object > keys ( ) { // sort elements based on detector (prop key) names Set < ? > set = keySet ( ) ; return ( Enumeration < Object > ) sortKeys ( ( Set < String > ) set ) ; }
|
Overriden to be able to write properties sorted by keys to the disk
| 71
| 15
|
153,073
|
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 ( ) ; }
|
Load existing FindBugs xml report for the given collection of files .
| 148
| 14
|
153,074
|
private void clearMarkers ( List < WorkItem > files ) throws CoreException { if ( files == null ) { project . deleteMarkers ( FindBugsMarker . NAME , true , IResource . DEPTH_INFINITE ) ; return ; } for ( WorkItem item : files ) { if ( item != null ) { item . clearMarkers ( ) ; } } }
|
Clear associated markers
| 82
| 3
|
153,075
|
private void collectClassFiles ( List < WorkItem > resources , Map < IPath , IPath > outLocations , Project fbProject ) { for ( WorkItem workItem : resources ) { workItem . addFilesToProject ( fbProject , outLocations ) ; } }
|
Updates given outputFiles map with class name patterns matching given java source names
| 60
| 15
|
153,076
|
private void runFindBugs ( final FindBugs2 findBugs ) { if ( DEBUG ) { FindbugsPlugin . log ( "Running findbugs in thread " + Thread . currentThread ( ) . getName ( ) ) ; } System . setProperty ( "findbugs.progress" , "true" ) ; try { // Perform the analysis! (note: This is not thread-safe) findBugs . execute ( ) ; } catch ( InterruptedException e ) { if ( DEBUG ) { FindbugsPlugin . getDefault ( ) . logException ( e , "Worker interrupted" ) ; } Thread . currentThread ( ) . interrupt ( ) ; } catch ( IOException e ) { FindbugsPlugin . getDefault ( ) . logException ( e , "Error performing SpotBugs analysis" ) ; } finally { findBugs . dispose ( ) ; } }
|
this method will block current thread until the findbugs is running
| 184
| 12
|
153,077
|
private void updateBugCollection ( Project findBugsProject , Reporter bugReporter , boolean incremental ) { SortedBugCollection newBugCollection = bugReporter . getBugCollection ( ) ; try { st . newPoint ( "getBugCollection" ) ; SortedBugCollection oldBugCollection = FindbugsPlugin . getBugCollection ( project , monitor ) ; st . newPoint ( "mergeBugCollections" ) ; SortedBugCollection resultCollection = mergeBugCollections ( oldBugCollection , newBugCollection , incremental ) ; resultCollection . getProject ( ) . setGuiCallback ( new EclipseGuiCallback ( project ) ) ; resultCollection . setTimestamp ( System . currentTimeMillis ( ) ) ; // will store bugs in the default FB file + Eclipse project session // props st . newPoint ( "storeBugCollection" ) ; FindbugsPlugin . storeBugCollection ( project , resultCollection , monitor ) ; } catch ( IOException e ) { FindbugsPlugin . getDefault ( ) . logException ( e , "Error performing SpotBugs results update" ) ; } catch ( CoreException e ) { FindbugsPlugin . getDefault ( ) . logException ( e , "Error performing SpotBugs results update" ) ; } // will store bugs as markers in Eclipse workspace st . newPoint ( "createMarkers" ) ; MarkerUtil . createMarkers ( javaProject , newBugCollection , resource , monitor ) ; }
|
Update the BugCollection for the project .
| 304
| 8
|
153,078
|
public static IPath getFilterPath ( String filePath , IProject project ) { IPath path = new Path ( filePath ) ; if ( path . isAbsolute ( ) ) { return path ; } if ( project != null ) { // try first project relative location IPath newPath = project . getLocation ( ) . append ( path ) ; if ( newPath . toFile ( ) . exists ( ) ) { return newPath ; } } // try to resolve relative to workspace (if we use workspace properties // for project) IPath wspLocation = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getLocation ( ) ; IPath newPath = wspLocation . append ( path ) ; if ( newPath . toFile ( ) . exists ( ) ) { return newPath ; } // something which we have no idea what it can be (or missing/wrong file // path) return path ; }
|
Checks the given path and convert it to absolute path if it is specified relative to the given project or workspace
| 194
| 22
|
153,079
|
public static IPath toFilterPath ( String filePath , IProject project ) { IPath path = new Path ( filePath ) ; IPath commonPath ; if ( project != null ) { commonPath = project . getLocation ( ) ; IPath relativePath = getRelativePath ( path , commonPath ) ; if ( ! relativePath . equals ( path ) ) { return relativePath ; } } commonPath = ResourcesPlugin . getWorkspace ( ) . getRoot ( ) . getLocation ( ) ; return getRelativePath ( path , commonPath ) ; }
|
Checks the given absolute path and convert it to relative path if it is relative to the given project or workspace . This representation can be used to store filter paths in user preferences file
| 119
| 36
|
153,080
|
public static ProjectFilterSettings fromEncodedString ( String s ) { ProjectFilterSettings result = new ProjectFilterSettings ( ) ; if ( s . length ( ) > 0 ) { int bar = s . indexOf ( FIELD_DELIMITER ) ; String minPriority ; if ( bar >= 0 ) { minPriority = s . substring ( 0 , bar ) ; s = s . substring ( bar + 1 ) ; } else { minPriority = s ; s = "" ; } if ( priorityNameToValueMap . get ( minPriority ) == null ) { minPriority = DEFAULT_PRIORITY ; } result . setMinPriority ( minPriority ) ; } if ( s . length ( ) > 0 ) { int bar = s . indexOf ( FIELD_DELIMITER ) ; String categories ; if ( bar >= 0 ) { categories = s . substring ( 0 , bar ) ; s = s . substring ( bar + 1 ) ; } else { categories = s ; s = "" ; } StringTokenizer t = new StringTokenizer ( categories , LISTITEM_DELIMITER ) ; while ( t . hasMoreTokens ( ) ) { String category = t . nextToken ( ) ; // 'result' probably already contains 'category', since // it contains all known bug category keys by default. // But add it to the set anyway in case it is an unknown key. result . addCategory ( category ) ; } } if ( s . length ( ) > 0 ) { int bar = s . indexOf ( FIELD_DELIMITER ) ; String displayFalseWarnings ; if ( bar >= 0 ) { displayFalseWarnings = s . substring ( 0 , bar ) ; s = s . substring ( bar + 1 ) ; } else { displayFalseWarnings = s ; s = "" ; } result . setDisplayFalseWarnings ( Boolean . valueOf ( displayFalseWarnings ) . booleanValue ( ) ) ; } if ( s . length ( ) > 0 ) { int bar = s . indexOf ( FIELD_DELIMITER ) ; String minRankStr ; if ( bar >= 0 ) { minRankStr = s . substring ( 0 , bar ) ; // s = s.substring(bar + 1); } else { minRankStr = s ; // s = ""; } result . setMinRank ( Integer . parseInt ( minRankStr ) ) ; } // if (s.length() > 0) { // // Can add other fields here... // assert true; // } return result ; }
|
Create ProjectFilterSettings from an encoded string .
| 561
| 9
|
153,081
|
public static void hiddenFromEncodedString ( ProjectFilterSettings result , String s ) { if ( s . length ( ) > 0 ) { int bar = s . indexOf ( FIELD_DELIMITER ) ; String categories ; if ( bar >= 0 ) { categories = s . substring ( 0 , bar ) ; } else { categories = s ; } StringTokenizer t = new StringTokenizer ( categories , LISTITEM_DELIMITER ) ; while ( t . hasMoreTokens ( ) ) { String category = t . nextToken ( ) ; result . removeCategory ( category ) ; } } }
|
set the hidden bug categories on the specifed ProjectFilterSettings from an encoded string
| 132
| 17
|
153,082
|
public boolean displayWarning ( BugInstance bugInstance ) { int priority = bugInstance . getPriority ( ) ; if ( priority > getMinPriorityAsInt ( ) ) { return false ; } int rank = bugInstance . getBugRank ( ) ; if ( rank > getMinRank ( ) ) { return false ; } BugPattern bugPattern = bugInstance . getBugPattern ( ) ; // HACK: it is conceivable that the detector plugin which generated // this warning is not available any more, in which case we can't // find out the category. Let the warning be visible in this case. if ( ! containsCategory ( bugPattern . getCategory ( ) ) ) { return false ; } if ( ! displayFalseWarnings ) { boolean isFalseWarning = ! Boolean . valueOf ( bugInstance . getProperty ( BugProperty . IS_BUG , "true" ) ) . booleanValue ( ) ; if ( isFalseWarning ) { return false ; } } return true ; }
|
Return whether or not a warning should be displayed according to the project filter settings .
| 206
| 16
|
153,083
|
public void setMinPriority ( String minPriority ) { this . minPriority = minPriority ; Integer value = priorityNameToValueMap . get ( minPriority ) ; if ( value == null ) { value = priorityNameToValueMap . get ( DEFAULT_PRIORITY ) ; if ( value == null ) { throw new IllegalStateException ( ) ; } } this . minPriorityAsInt = value . intValue ( ) ; }
|
Set minimum warning priority threshold .
| 97
| 6
|
153,084
|
public String hiddenToEncodedString ( ) { StringBuilder buf = new StringBuilder ( ) ; // Encode hidden bug categories for ( Iterator < String > i = hiddenBugCategorySet . iterator ( ) ; i . hasNext ( ) ; ) { buf . append ( i . next ( ) ) ; if ( i . hasNext ( ) ) { buf . append ( LISTITEM_DELIMITER ) ; } } buf . append ( FIELD_DELIMITER ) ; return buf . toString ( ) ; }
|
Create a string containing the encoded form of the hidden bug categories
| 114
| 12
|
153,085
|
public String toEncodedString ( ) { // Priority threshold StringBuilder buf = new StringBuilder ( ) ; buf . append ( getMinPriority ( ) ) ; // Encode enabled bug categories. Note that these aren't really used for // much. // They only come in to play when parsed by a version of FindBugs older // than 1.1. buf . append ( FIELD_DELIMITER ) ; for ( Iterator < String > i = activeBugCategorySet . iterator ( ) ; i . hasNext ( ) ; ) { buf . append ( i . next ( ) ) ; if ( i . hasNext ( ) ) { buf . append ( LISTITEM_DELIMITER ) ; } } // Whether to display false warnings buf . append ( FIELD_DELIMITER ) ; buf . append ( displayFalseWarnings ? "true" : "false" ) ; buf . append ( FIELD_DELIMITER ) ; buf . append ( getMinRank ( ) ) ; return buf . toString ( ) ; }
|
Create a string containing the encoded form of the ProjectFilterSettings .
| 227
| 13
|
153,086
|
public static String getIntPriorityAsString ( int prio ) { String minPriority ; switch ( prio ) { case Priorities . EXP_PRIORITY : minPriority = ProjectFilterSettings . EXPERIMENTAL_PRIORITY ; break ; case Priorities . LOW_PRIORITY : minPriority = ProjectFilterSettings . LOW_PRIORITY ; break ; case Priorities . NORMAL_PRIORITY : minPriority = ProjectFilterSettings . MEDIUM_PRIORITY ; break ; case Priorities . HIGH_PRIORITY : minPriority = ProjectFilterSettings . HIGH_PRIORITY ; break ; default : minPriority = ProjectFilterSettings . DEFAULT_PRIORITY ; break ; } return minPriority ; }
|
Convert an integer warning priority threshold value to a String .
| 162
| 12
|
153,087
|
public GraphType transpose ( GraphType orig , GraphToolkit < GraphType , EdgeType , VertexType > toolkit ) { GraphType trans = toolkit . createGraph ( ) ; // For each vertex in original graph, create an equivalent // vertex in the transposed graph, // ensuring that vertex labels in the transposed graph // match vertex labels in the original graph for ( Iterator < VertexType > i = orig . vertexIterator ( ) ; i . hasNext ( ) ; ) { VertexType v = i . next ( ) ; // Make a duplicate of original vertex // (Ensuring that transposed graph has same labeling as original) VertexType dupVertex = toolkit . duplicateVertex ( v ) ; dupVertex . setLabel ( v . getLabel ( ) ) ; trans . addVertex ( v ) ; // Keep track of correspondence between equivalent vertices m_origToTransposeMap . put ( v , dupVertex ) ; m_transposeToOrigMap . put ( dupVertex , v ) ; } trans . setNumVertexLabels ( orig . getNumVertexLabels ( ) ) ; // For each edge in the original graph, create a reversed edge // in the transposed graph for ( Iterator < EdgeType > i = orig . edgeIterator ( ) ; i . hasNext ( ) ; ) { EdgeType e = i . next ( ) ; VertexType transSource = m_origToTransposeMap . get ( e . getTarget ( ) ) ; VertexType transTarget = m_origToTransposeMap . get ( e . getSource ( ) ) ; EdgeType dupEdge = trans . createEdge ( transSource , transTarget ) ; dupEdge . setLabel ( e . getLabel ( ) ) ; // Copy auxiliary information for edge toolkit . copyEdge ( e , dupEdge ) ; } trans . setNumEdgeLabels ( orig . getNumEdgeLabels ( ) ) ; return trans ; }
|
Transpose a graph . Note that the original graph is not modified ; the new graph and its vertices and edges are new objects .
| 419
| 27
|
153,088
|
public void mapInputToOutput ( ValueNumber input , ValueNumber output ) { BitSet inputSet = getInputSet ( output ) ; inputSet . set ( input . getNumber ( ) ) ; if ( DEBUG ) { System . out . println ( input . getNumber ( ) + "->" + output . getNumber ( ) ) ; System . out . println ( "Input set for " + output . getNumber ( ) + " is now " + inputSet ) ; } }
|
Map an input ValueNumber to an output ValueNumber .
| 101
| 11
|
153,089
|
public BitSet getInputSet ( ValueNumber output ) { BitSet outputSet = outputToInputMap . get ( output ) ; if ( outputSet == null ) { if ( DEBUG ) { System . out . println ( "Create new input set for " + output . getNumber ( ) ) ; } outputSet = new BitSet ( ) ; outputToInputMap . put ( output , outputSet ) ; } return outputSet ; }
|
Get the set of input ValueNumbers which directly contributed to the given output ValueNumber .
| 91
| 17
|
153,090
|
private static boolean mightInheritFromException ( ClassDescriptor d ) { while ( d != null ) { try { if ( "java.lang.Exception" . equals ( d . getDottedClassName ( ) ) ) { return true ; } XClass classNameAndInfo = Global . getAnalysisCache ( ) . getClassAnalysis ( XClass . class , d ) ; d = classNameAndInfo . getSuperclassDescriptor ( ) ; } catch ( CheckedAnalysisException e ) { return true ; // don't know } } return false ; }
|
Determine whether the class descriptor ultimately inherits from java . lang . Exception
| 120
| 16
|
153,091
|
public void launch ( ) throws Exception { // Sanity-check the loaded BCEL classes if ( ! CheckBcel . check ( ) ) { System . exit ( 1 ) ; } int launchProperty = getLaunchProperty ( ) ; if ( GraphicsEnvironment . isHeadless ( ) || launchProperty == TEXTUI ) { FindBugs2 . main ( args ) ; } else if ( launchProperty == SHOW_HELP ) { ShowHelp . main ( args ) ; } else if ( launchProperty == SHOW_VERSION ) { Version . main ( new String [ ] { "-release" } ) ; } else { Class < ? > launchClass = Class . forName ( "edu.umd.cs.findbugs.gui2.Driver" ) ; Method mainMethod = launchClass . getMethod ( "main" , args . getClass ( ) ) ; mainMethod . invoke ( null , ( Object ) args ) ; } }
|
Launch the appropriate UI .
| 195
| 5
|
153,092
|
private int getLaunchProperty ( ) { // See if the first command line argument specifies the UI. if ( args . length > 0 ) { String firstArg = args [ 0 ] ; if ( firstArg . startsWith ( "-" ) ) { String uiName = firstArg . substring ( 1 ) ; if ( uiNameToCodeMap . containsKey ( uiName ) ) { // Strip the first argument from the command line arguments. String [ ] modifiedArgs = new String [ args . length - 1 ] ; System . arraycopy ( args , 1 , modifiedArgs , 0 , args . length - 1 ) ; args = modifiedArgs ; return uiNameToCodeMap . get ( uiName ) ; } } } // Check findbugs.launchUI property. // "gui2" is the default if not otherwise specified. String s = System . getProperty ( "findbugs.launchUI" ) ; if ( s == null ) { for ( String a : args ) { if ( "-output" . equals ( a ) || "-xml" . equals ( a ) || a . endsWith ( ".class" ) || a . endsWith ( ".jar" ) ) { return TEXTUI ; } } s = "gui2" ; } // See if the property value is one of the human-readable // UI names. if ( uiNameToCodeMap . containsKey ( s ) ) { return uiNameToCodeMap . get ( s ) ; } // Fall back: try to parse it as an integer. try { return Integer . parseInt ( s ) ; } catch ( NumberFormatException nfe ) { return GUI2 ; } }
|
Find out what UI should be launched .
| 349
| 8
|
153,093
|
@ Override public void configure ( ) throws CoreException { if ( DEBUG ) { System . out . println ( "Adding findbugs to the project build spec." ) ; } // register FindBugs builder addToBuildSpec ( FindbugsPlugin . BUILDER_ID ) ; }
|
Adds the FindBugs builder to the project .
| 59
| 10
|
153,094
|
@ Override public void deconfigure ( ) throws CoreException { if ( DEBUG ) { System . out . println ( "Removing findbugs from the project build spec." ) ; } // de-register FindBugs builder removeFromBuildSpec ( FindbugsPlugin . BUILDER_ID ) ; }
|
Removes the FindBugs builder from the project .
| 63
| 11
|
153,095
|
protected void removeFromBuildSpec ( String builderID ) throws CoreException { MarkerUtil . removeMarkers ( getProject ( ) ) ; IProjectDescription description = getProject ( ) . getDescription ( ) ; ICommand [ ] commands = description . getBuildSpec ( ) ; for ( int i = 0 ; i < commands . length ; ++ i ) { if ( commands [ i ] . getBuilderName ( ) . equals ( builderID ) ) { ICommand [ ] newCommands = new ICommand [ commands . length - 1 ] ; System . arraycopy ( commands , 0 , newCommands , 0 , i ) ; System . arraycopy ( commands , i + 1 , newCommands , i , commands . length - i - 1 ) ; description . setBuildSpec ( newCommands ) ; getProject ( ) . setDescription ( description , null ) ; return ; } } }
|
Removes the given builder from the build spec for the given project .
| 188
| 14
|
153,096
|
protected void addToBuildSpec ( String builderID ) throws CoreException { IProjectDescription description = getProject ( ) . getDescription ( ) ; ICommand findBugsCommand = getFindBugsCommand ( description ) ; if ( findBugsCommand == null ) { // Add a Java command to the build spec ICommand newCommand = description . newCommand ( ) ; newCommand . setBuilderName ( builderID ) ; setFindBugsCommand ( description , newCommand ) ; } }
|
Adds a builder to the build spec for the given project .
| 102
| 12
|
153,097
|
private ICommand getFindBugsCommand ( IProjectDescription description ) { ICommand [ ] commands = description . getBuildSpec ( ) ; for ( int i = 0 ; i < commands . length ; ++ i ) { if ( FindbugsPlugin . BUILDER_ID . equals ( commands [ i ] . getBuilderName ( ) ) ) { return commands [ i ] ; } } return null ; }
|
Find the specific FindBugs command amongst the build spec of a given description
| 85
| 15
|
153,098
|
public void addSwitch ( String option , String description ) { optionList . add ( option ) ; optionDescriptionMap . put ( option , description ) ; if ( option . length ( ) > maxWidth ) { maxWidth = option . length ( ) ; } }
|
Add a command line switch . This method is for adding options that do not require an argument .
| 54
| 19
|
153,099
|
public void addSwitchWithOptionalExtraPart ( String option , String optionExtraPartSynopsis , String description ) { optionList . add ( option ) ; optionExtraPartSynopsisMap . put ( option , optionExtraPartSynopsis ) ; optionDescriptionMap . put ( option , description ) ; // Option will display as -foo[:extraPartSynopsis] int length = option . length ( ) + optionExtraPartSynopsis . length ( ) + 3 ; if ( length > maxWidth ) { maxWidth = length ; } }
|
Add a command line switch that allows optional extra information to be specified as part of it .
| 105
| 18
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.