idx
int64 0
165k
| question
stringlengths 73
4.15k
| target
stringlengths 5
918
| len_question
int64 21
890
| len_target
int64 3
255
|
|---|---|---|---|---|
153,500
|
protected ReferenceType mergeReferenceTypes ( ReferenceType aRef , ReferenceType bRef ) throws DataflowAnalysisException { if ( aRef . equals ( bRef ) ) { return aRef ; } byte aType = aRef . getType ( ) ; byte bType = bRef . getType ( ) ; try { // Special case: ExceptionObjectTypes. // We want to preserve the ExceptionSets associated, // in order to track the exact set of exceptions if ( isObjectType ( aType ) && isObjectType ( bType ) && ( ( aType == T_EXCEPTION || isThrowable ( aRef ) ) && ( bType == T_EXCEPTION || isThrowable ( bRef ) ) ) ) { ExceptionSet union = exceptionSetFactory . createExceptionSet ( ) ; if ( aType == Const . T_OBJECT && "Ljava/lang/Throwable;" . equals ( aRef . getSignature ( ) ) ) { return aRef ; } if ( bType == Const . T_OBJECT && "Ljava/lang/Throwable;" . equals ( bRef . getSignature ( ) ) ) { return bRef ; } updateExceptionSet ( union , ( ObjectType ) aRef ) ; updateExceptionSet ( union , ( ObjectType ) bRef ) ; Type t = ExceptionObjectType . fromExceptionSet ( union ) ; if ( t instanceof ReferenceType ) { return ( ReferenceType ) t ; } } if ( aRef instanceof GenericObjectType && bRef instanceof GenericObjectType && aRef . getSignature ( ) . equals ( bRef . getSignature ( ) ) ) { GenericObjectType aG = ( GenericObjectType ) aRef ; GenericObjectType bG = ( GenericObjectType ) bRef ; if ( aG . getTypeCategory ( ) == bG . getTypeCategory ( ) ) { switch ( aG . getTypeCategory ( ) ) { case PARAMETERIZED : List < ? extends ReferenceType > aP = aG . getParameters ( ) ; List < ? extends ReferenceType > bP = bG . getParameters ( ) ; assert aP != null ; assert bP != null ; if ( aP . size ( ) != bP . size ( ) ) { break ; } ArrayList < ReferenceType > result = new ArrayList <> ( aP . size ( ) ) ; for ( int i = 0 ; i < aP . size ( ) ; i ++ ) { result . add ( mergeReferenceTypes ( aP . get ( i ) , bP . get ( i ) ) ) ; } GenericObjectType rOT = GenericUtilities . getType ( aG . getClassName ( ) , result ) ; return rOT ; } } } if ( aRef instanceof GenericObjectType ) { aRef = ( ( GenericObjectType ) aRef ) . getObjectType ( ) ; } if ( bRef instanceof GenericObjectType ) { bRef = ( ( GenericObjectType ) bRef ) . getObjectType ( ) ; } if ( Subtypes2 . ENABLE_SUBTYPES2_FOR_COMMON_SUPERCLASS_QUERIES ) { return AnalysisContext . currentAnalysisContext ( ) . getSubtypes2 ( ) . getFirstCommonSuperclass ( aRef , bRef ) ; } else { return aRef . getFirstCommonSuperclass ( bRef ) ; } } catch ( ClassNotFoundException e ) { lookupFailureCallback . reportMissingClass ( e ) ; return Type . OBJECT ; } }
|
Default implementation of merging reference types . This just returns the first common superclass which is compliant with the JVM Spec . Subclasses may override this method in order to implement extended type rules .
| 756
| 38
|
153,501
|
public void read ( ) { File prefFile = new File ( SystemProperties . getProperty ( "user.home" ) , PREF_FILE_NAME ) ; if ( ! prefFile . exists ( ) || ! prefFile . isFile ( ) ) { return ; } try { read ( new FileInputStream ( prefFile ) ) ; } catch ( IOException e ) { // Ignore - just use default preferences } }
|
Read persistent global UserPreferences from file in the user s home directory .
| 89
| 15
|
153,502
|
public void write ( ) { try { File prefFile = new File ( SystemProperties . getProperty ( "user.home" ) , PREF_FILE_NAME ) ; write ( new FileOutputStream ( prefFile ) ) ; } catch ( IOException e ) { if ( FindBugs . DEBUG ) { e . printStackTrace ( ) ; // Ignore } } }
|
Write persistent global UserPreferences to file in user s home directory .
| 80
| 14
|
153,503
|
public void useProject ( String projectName ) { removeProject ( projectName ) ; recentProjectsList . addFirst ( projectName ) ; while ( recentProjectsList . size ( ) > MAX_RECENT_FILES ) { recentProjectsList . removeLast ( ) ; } }
|
Add given project filename to the front of the recently - used project list .
| 61
| 15
|
153,504
|
public void removeProject ( String projectName ) { // It should only be in list once (usually in slot 0) but check entire // list... Iterator < String > it = recentProjectsList . iterator ( ) ; while ( it . hasNext ( ) ) { // LinkedList, so remove() via iterator is faster than // remove(index). if ( projectName . equals ( it . next ( ) ) ) { it . remove ( ) ; } } }
|
Remove project filename from the recently - used project list .
| 98
| 11
|
153,505
|
public void enableAllDetectors ( boolean enable ) { detectorEnablementMap . clear ( ) ; Collection < Plugin > allPlugins = Plugin . getAllPlugins ( ) ; for ( Plugin plugin : allPlugins ) { for ( DetectorFactory factory : plugin . getDetectorFactories ( ) ) { detectorEnablementMap . put ( factory . getShortName ( ) , enable ) ; } } }
|
Enable or disable all known Detectors .
| 86
| 8
|
153,506
|
private static Map < String , Boolean > readProperties ( Properties props , String keyPrefix ) { Map < String , Boolean > filters = new TreeMap <> ( ) ; int counter = 0 ; boolean keyFound = true ; while ( keyFound ) { String property = props . getProperty ( keyPrefix + counter ) ; if ( property != null ) { int pipePos = property . indexOf ( BOOL_SEPARATOR ) ; if ( pipePos >= 0 ) { String name = property . substring ( 0 , pipePos ) ; String enabled = property . substring ( pipePos + 1 ) ; filters . put ( name , Boolean . valueOf ( enabled ) ) ; } else { filters . put ( property , Boolean . TRUE ) ; } counter ++ ; } else { keyFound = false ; } } return filters ; }
|
Helper method to read array of strings out of the properties file using a Findbugs style format .
| 176
| 19
|
153,507
|
private static void writeProperties ( Properties props , String keyPrefix , Map < String , Boolean > filters ) { int counter = 0 ; Set < Entry < String , Boolean > > entrySet = filters . entrySet ( ) ; for ( Entry < String , Boolean > entry : entrySet ) { props . setProperty ( keyPrefix + counter , entry . getKey ( ) + BOOL_SEPARATOR + entry . getValue ( ) ) ; counter ++ ; } // remove obsolete keys from the properties file boolean keyFound = true ; while ( keyFound ) { String key = keyPrefix + counter ; String property = props . getProperty ( key ) ; if ( property == null ) { keyFound = false ; } else { props . remove ( key ) ; } } }
|
Helper method to write array of strings out of the properties file using a Findbugs style format .
| 164
| 19
|
153,508
|
public AnalysisFeatureSetting [ ] getAnalysisFeatureSettings ( ) { if ( EFFORT_DEFAULT . equals ( effort ) ) { return FindBugs . DEFAULT_EFFORT ; } else if ( EFFORT_MIN . equals ( effort ) ) { return FindBugs . MIN_EFFORT ; } return FindBugs . MAX_EFFORT ; }
|
Returns the effort level as an array of feature settings as expected by FindBugs .
| 75
| 17
|
153,509
|
public JavaClass parse ( ) throws IOException { JavaClass jclass = classParser . parse ( ) ; Repository . addClass ( jclass ) ; return jclass ; }
|
Parse the class file into a JavaClass object . If successful the new JavaClass is entered into the Repository .
| 37
| 24
|
153,510
|
void setSourceBaseList ( Iterable < String > sourceBaseList ) { for ( String repos : sourceBaseList ) { if ( repos . endsWith ( ".zip" ) || repos . endsWith ( ".jar" ) || repos . endsWith ( ".z0p.gz" ) ) { // Zip or jar archive try { if ( repos . startsWith ( "http:" ) || repos . startsWith ( "https:" ) || repos . startsWith ( "file:" ) ) { String url = SystemProperties . rewriteURLAccordingToProperties ( repos ) ; repositoryList . add ( makeInMemorySourceRepository ( url ) ) ; } else { repositoryList . add ( new ZipSourceRepository ( new ZipFile ( repos ) ) ) ; } } catch ( IOException e ) { // Ignored - we won't use this archive AnalysisContext . logError ( "Unable to load " + repos , e ) ; } } else { File dir = new File ( repos ) ; if ( dir . canRead ( ) && dir . isDirectory ( ) ) { repositoryList . add ( new DirectorySourceRepository ( repos ) ) ; } else { AnalysisContext . logError ( "Unable to load " + repos ) ; } } } }
|
Set the list of source directories .
| 277
| 7
|
153,511
|
public InputStream openSource ( String packageName , String fileName ) throws IOException { SourceFile sourceFile = findSourceFile ( packageName , fileName ) ; return sourceFile . getInputStream ( ) ; }
|
Open an input stream on a source file in given package .
| 44
| 12
|
153,512
|
public SourceFile findSourceFile ( String packageName , String fileName ) throws IOException { // On windows the fileName specification is different between a file in // a directory tree, and a // file in a zip file. In a directory tree the separator used is '\', // while in a zip it's '/' // Therefore for each repository figure out what kind it is and use the // appropriate separator. // In all practicality, this code could just use the hardcoded '/' char, // as windows can open // files with this separator, but to allow for the mythical 'other' // platform that uses an // alternate separator, make a distinction String platformName = getPlatformName ( packageName , fileName ) ; String canonicalName = getCanonicalName ( packageName , fileName ) ; // Is the file in the cache already? Always cache it with the canonical // name SourceFile sourceFile = cache . get ( canonicalName ) ; if ( sourceFile != null ) { return sourceFile ; } // Find this source file, add its data to the cache if ( DEBUG ) { System . out . println ( "Trying " + fileName + " in package " + packageName + "..." ) ; } // Query each element of the source path to find the requested source // file for ( SourceRepository repos : repositoryList ) { if ( repos instanceof BlockingSourceRepository && ! ( ( BlockingSourceRepository ) repos ) . isReady ( ) ) { continue ; } fileName = repos . isPlatformDependent ( ) ? platformName : canonicalName ; if ( DEBUG ) { System . out . println ( "Looking in " + repos + " for " + fileName ) ; } if ( repos . contains ( fileName ) ) { // Found it sourceFile = new SourceFile ( repos . getDataSource ( fileName ) ) ; cache . put ( canonicalName , sourceFile ) ; // always cache with // canonicalName return sourceFile ; } } throw new FileNotFoundException ( "Can't find source file " + fileName ) ; }
|
Open a source file in given package .
| 442
| 8
|
153,513
|
public int compareSourceLines ( BugCollection lhsCollection , BugCollection rhsCollection , SourceLineAnnotation lhs , SourceLineAnnotation rhs ) { if ( lhs == null || rhs == null ) { return compareNullElements ( lhs , rhs ) ; } // Classes must match fuzzily. int cmp = compareClassesByName ( lhsCollection , rhsCollection , lhs . getClassName ( ) , rhs . getClassName ( ) ) ; if ( cmp != 0 ) { return cmp ; } return 0 ; }
|
Compare source line annotations .
| 122
| 5
|
153,514
|
public void process ( ) throws IOException { int pos = 0 ; do { int meta = findNextMeta ( text , pos ) ; if ( meta >= 0 ) { emitLiteral ( text . substring ( pos , meta ) ) ; emitLiteral ( map . getReplacement ( text . substring ( meta , meta + 1 ) ) ) ; pos = meta + 1 ; } else { emitLiteral ( text . substring ( pos , text . length ( ) ) ) ; pos = text . length ( ) ; } } while ( pos < text . length ( ) ) ; }
|
Quote metacharacters in the text .
| 127
| 9
|
153,515
|
private E createUsingConstructor ( ) throws CheckedAnalysisException { Constructor < E > constructor ; try { constructor = databaseClass . getConstructor ( new Class [ 0 ] ) ; } catch ( NoSuchMethodException e ) { return null ; } try { return constructor . newInstance ( new Object [ 0 ] ) ; } catch ( InstantiationException e ) { throw new CheckedAnalysisException ( "Could not create " + databaseClass . getName ( ) , e ) ; } catch ( IllegalAccessException e ) { throw new CheckedAnalysisException ( "Could not create " + databaseClass . getName ( ) , e ) ; } catch ( InvocationTargetException e ) { throw new CheckedAnalysisException ( "Could not create " + databaseClass . getName ( ) , e ) ; } }
|
Try to create the database using a no - arg constructor .
| 170
| 12
|
153,516
|
@ Override protected void work ( final IWorkbenchPart part , IResource resource , final List < WorkItem > resources ) { FindBugsJob clearMarkersJob = new ClearMarkersJob ( resource , resources ) ; clearMarkersJob . addJobChangeListener ( new JobChangeAdapter ( ) { @ Override public void done ( IJobChangeEvent event ) { refreshViewer ( part , resources ) ; } } ) ; clearMarkersJob . scheduleInteractive ( ) ; }
|
Clear the FindBugs markers on each project in the given selection displaying a progress monitor .
| 103
| 18
|
153,517
|
public void pushValue ( ValueType value ) { if ( VERIFY_INTEGRITY && value == null ) { throw new IllegalArgumentException ( ) ; } if ( ! isValid ( ) ) { throw new IllegalStateException ( "accessing top or bottom frame" ) ; } slotList . add ( value ) ; }
|
Push a value onto the Java operand stack .
| 71
| 10
|
153,518
|
public ValueType popValue ( ) throws DataflowAnalysisException { if ( ! isValid ( ) ) { throw new DataflowAnalysisException ( "accessing top or bottom frame" ) ; } if ( slotList . size ( ) == numLocals ) { throw new DataflowAnalysisException ( "operand stack empty" ) ; } return slotList . remove ( slotList . size ( ) - 1 ) ; }
|
Pop a value off of the Java operand stack .
| 87
| 11
|
153,519
|
public ValueType getTopValue ( ) throws DataflowAnalysisException { if ( ! isValid ( ) ) { throw new DataflowAnalysisException ( "accessing top or bottom frame" ) ; } assert slotList . size ( ) >= numLocals ; if ( slotList . size ( ) == numLocals ) { throw new DataflowAnalysisException ( "operand stack is empty" ) ; } return slotList . get ( slotList . size ( ) - 1 ) ; }
|
Get the value on the top of the Java operand stack .
| 101
| 13
|
153,520
|
public void getTopStackWords ( ValueType [ ] valueList ) throws DataflowAnalysisException { int stackDepth = getStackDepth ( ) ; if ( valueList . length > stackDepth ) { throw new DataflowAnalysisException ( "not enough values on stack" ) ; } int numSlots = slotList . size ( ) ; for ( int i = numSlots - valueList . length , j = 0 ; i < numSlots ; ++ i , ++ j ) { valueList [ j ] = slotList . get ( i ) ; } }
|
Get the values on the top of the Java operand stack . The top stack item is placed at the end of the array so that to restore the values to the stack you would push them in the order they appear in the array .
| 117
| 47
|
153,521
|
public ValueType getStackValue ( int loc ) throws DataflowAnalysisException { if ( ! isValid ( ) ) { throw new DataflowAnalysisException ( "Accessing TOP or BOTTOM frame!" ) ; } int stackDepth = getStackDepth ( ) ; if ( loc >= stackDepth ) { throw new DataflowAnalysisException ( "not enough values on stack: access=" + loc + ", avail=" + stackDepth ) ; } if ( loc < 0 ) { throw new DataflowAnalysisException ( "can't get position " + loc + " of stack" ) ; } int pos = slotList . size ( ) - ( loc + 1 ) ; return slotList . get ( pos ) ; }
|
Get a value on the operand stack .
| 147
| 9
|
153,522
|
public int getStackLocation ( int loc ) throws DataflowAnalysisException { int stackDepth = getStackDepth ( ) ; if ( loc >= stackDepth ) { throw new DataflowAnalysisException ( "not enough values on stack: access=" + loc + ", avail=" + stackDepth ) ; } return slotList . size ( ) - ( loc + 1 ) ; }
|
Get a the location in the frame of a value on the operand stack .
| 76
| 16
|
153,523
|
public int getInstanceSlot ( Instruction ins , ConstantPoolGen cpg ) throws DataflowAnalysisException { if ( ! isValid ( ) ) { throw new DataflowAnalysisException ( "Accessing invalid frame at " + ins ) ; } int numConsumed = ins . consumeStack ( cpg ) ; if ( numConsumed == Const . UNPREDICTABLE ) { throw new DataflowAnalysisException ( "Unpredictable stack consumption in " + ins ) ; } if ( numConsumed > getStackDepth ( ) ) { throw new DataflowAnalysisException ( "Stack underflow " + ins ) ; } return getNumSlots ( ) - numConsumed ; }
|
Get the slot the object instance referred to by given instruction is located in .
| 142
| 15
|
153,524
|
public int getNumArguments ( InvokeInstruction ins , ConstantPoolGen cpg ) { SignatureParser parser = new SignatureParser ( ins . getSignature ( cpg ) ) ; return parser . getNumParameters ( ) ; }
|
Get the number of arguments passed to given method invocation .
| 49
| 11
|
153,525
|
public int getNumArgumentsIncludingObjectInstance ( InvokeInstruction ins , ConstantPoolGen cpg ) throws DataflowAnalysisException { int numConsumed = ins . consumeStack ( cpg ) ; if ( numConsumed == Const . UNPREDICTABLE ) { throw new DataflowAnalysisException ( "Unpredictable stack consumption in " + ins ) ; } return numConsumed ; }
|
Get the number of arguments passed to given method invocation including the object instance if the call is to an instance method .
| 85
| 23
|
153,526
|
public BitSet getArgumentSet ( InvokeInstruction invokeInstruction , ConstantPoolGen cpg , DataflowValueChooser < ValueType > chooser ) throws DataflowAnalysisException { BitSet chosenArgSet = new BitSet ( ) ; SignatureParser sigParser = new SignatureParser ( invokeInstruction . getSignature ( cpg ) ) ; for ( int i = 0 ; i < sigParser . getNumParameters ( ) ; ++ i ) { ValueType value = getArgument ( invokeInstruction , cpg , i , sigParser ) ; if ( chooser . choose ( value ) ) { chosenArgSet . set ( i ) ; } } return chosenArgSet ; }
|
Get set of arguments passed to a method invocation which match given predicate .
| 145
| 14
|
153,527
|
public void clearStack ( ) { if ( ! isValid ( ) ) { throw new IllegalStateException ( "accessing top or bottom frame" ) ; } assert slotList . size ( ) >= numLocals ; if ( slotList . size ( ) > numLocals ) { slotList . subList ( numLocals , slotList . size ( ) ) . clear ( ) ; } }
|
Clear the Java operand stack . Only local variable slots will remain in the frame .
| 83
| 17
|
153,528
|
public boolean sameAs ( Frame < ValueType > other ) { if ( isTop != other . isTop ) { return false ; } if ( isTop && other . isTop ) { return true ; } if ( isBottom != other . isBottom ) { return false ; } if ( isBottom && other . isBottom ) { return true ; } if ( getNumSlots ( ) != other . getNumSlots ( ) ) { return false ; } for ( int i = 0 ; i < getNumSlots ( ) ; ++ i ) { if ( ! getValue ( i ) . equals ( other . getValue ( i ) ) ) { return false ; } } return true ; }
|
Return true if this stack frame is the same as the one given as a parameter .
| 146
| 17
|
153,529
|
public void copyFrom ( Frame < ValueType > other ) { lastUpdateTimestamp = other . lastUpdateTimestamp ; slotList = new ArrayList <> ( other . slotList ) ; isTop = other . isTop ; isBottom = other . isBottom ; }
|
Make this Frame exactly the same as the one given as a parameter .
| 57
| 14
|
153,530
|
public void addAnnotation ( AnnotationValue annotationValue ) { HashMap < ClassDescriptor , AnnotationValue > updatedMap = new HashMap <> ( classAnnotations ) ; updatedMap . put ( annotationValue . getAnnotationClass ( ) , annotationValue ) ; classAnnotations = Util . immutableMap ( updatedMap ) ; }
|
Destructively add an annotation to the object . In general this is not a great idea since it could cause the same class to appear to have different annotations at different times . However this method is necessary for built - in annotations that FindBugs adds to system classes . As long as we add such annotations early enough that nobody will notice we should be ok .
| 73
| 72
|
153,531
|
String getResourceName ( String fileName ) { // FIXME: there is probably a more robust way to do this // Strip off the directory part. String dirPath = directory . getPath ( ) ; if ( ! fileName . startsWith ( dirPath ) ) { throw new IllegalStateException ( "Filename " + fileName + " not inside directory " + dirPath ) ; } // The problem here is that we need to take the relative part of the // filename // and break it into components that we can then reconstruct into // a resource name (using '/' characters to separate the components). // Unfortunately, the File class does not make this task particularly // easy. String relativeFileName = fileName . substring ( dirPath . length ( ) ) ; File file = new File ( relativeFileName ) ; LinkedList < String > partList = new LinkedList <> ( ) ; do { partList . addFirst ( file . getName ( ) ) ; } while ( ( file = file . getParentFile ( ) ) != null ) ; StringBuilder buf = new StringBuilder ( ) ; for ( String part : partList ) { if ( buf . length ( ) > 0 ) { buf . append ( ' ' ) ; } buf . append ( part ) ; } return buf . toString ( ) ; }
|
Get the resource name given a full filename .
| 276
| 9
|
153,532
|
private void work ( final IProject project , final String fileName ) { FindBugsJob runFindBugs = new FindBugsJob ( "Saving SpotBugs XML data to " + fileName + "..." , project ) { @ Override protected void runWithProgress ( IProgressMonitor monitor ) throws CoreException { BugCollection bugCollection = FindbugsPlugin . getBugCollection ( project , monitor ) ; try { bugCollection . writeXML ( fileName ) ; } catch ( IOException e ) { CoreException ex = new CoreException ( FindbugsPlugin . createErrorStatus ( "Can't write SpotBugs bug collection from project " + project + " to file " + fileName , e ) ) ; throw ex ; } } } ; runFindBugs . setRule ( project ) ; runFindBugs . scheduleInteractive ( ) ; }
|
Save the XML result of a FindBugs analysis on the given project displaying a progress monitor .
| 180
| 19
|
153,533
|
protected void printBug ( BugInstance bugInstance ) { if ( showRank ) { int rank = BugRanker . findRank ( bugInstance ) ; outputStream . printf ( "%2d " , rank ) ; } switch ( bugInstance . getPriority ( ) ) { case Priorities . EXP_PRIORITY : outputStream . print ( "E " ) ; break ; case Priorities . LOW_PRIORITY : outputStream . print ( "L " ) ; break ; case Priorities . NORMAL_PRIORITY : outputStream . print ( "M " ) ; break ; case Priorities . HIGH_PRIORITY : outputStream . print ( "H " ) ; break ; default : assert false ; } BugPattern pattern = bugInstance . getBugPattern ( ) ; if ( pattern != null ) { String categoryAbbrev = null ; BugCategory bcat = DetectorFactoryCollection . instance ( ) . getBugCategory ( pattern . getCategory ( ) ) ; if ( bcat != null ) { categoryAbbrev = bcat . getAbbrev ( ) ; } if ( categoryAbbrev == null ) { categoryAbbrev = OTHER_CATEGORY_ABBREV ; } outputStream . print ( categoryAbbrev ) ; outputStream . print ( " " ) ; } if ( useLongBugCodes ) { outputStream . print ( bugInstance . getType ( ) ) ; outputStream . print ( " " ) ; } if ( reportHistory ) { long first = bugInstance . getFirstVersion ( ) ; long last = bugInstance . getLastVersion ( ) ; outputStream . print ( first ) ; outputStream . print ( " " ) ; outputStream . print ( last ) ; outputStream . print ( " " ) ; } SourceLineAnnotation line = bugInstance . getPrimarySourceLineAnnotation ( ) ; outputStream . println ( bugInstance . getMessage ( ) . replace ( ' ' , ' ' ) + " " + line . toString ( ) ) ; }
|
Print bug in one - line format .
| 428
| 8
|
153,534
|
public ClassFeatureSet initialize ( JavaClass javaClass ) { this . className = javaClass . getClassName ( ) ; this . isInterface = javaClass . isInterface ( ) ; addFeature ( CLASS_NAME_KEY + transformClassName ( javaClass . getClassName ( ) ) ) ; for ( Method method : javaClass . getMethods ( ) ) { if ( ! isSynthetic ( method ) ) { String transformedMethodSignature = transformMethodSignature ( method . getSignature ( ) ) ; if ( method . isStatic ( ) || ! overridesSuperclassMethod ( javaClass , method ) ) { addFeature ( METHOD_NAME_KEY + method . getName ( ) + ":" + transformedMethodSignature ) ; } Code code = method . getCode ( ) ; if ( code != null && code . getCode ( ) != null && code . getCode ( ) . length >= MIN_CODE_LENGTH ) { addFeature ( CODE_LENGTH_KEY + method . getName ( ) + ":" + transformedMethodSignature + ":" + code . getCode ( ) . length ) ; } } } for ( Field field : javaClass . getFields ( ) ) { if ( ! isSynthetic ( field ) ) { addFeature ( FIELD_NAME_KEY + field . getName ( ) + ":" + transformSignature ( field . getSignature ( ) ) ) ; } } return this ; }
|
Initialize from given JavaClass .
| 310
| 7
|
153,535
|
private boolean overridesSuperclassMethod ( JavaClass javaClass , Method method ) { if ( method . isStatic ( ) ) { return false ; } try { JavaClass [ ] superclassList = javaClass . getSuperClasses ( ) ; if ( superclassList != null ) { JavaClassAndMethod match = Hierarchy . findMethod ( superclassList , method . getName ( ) , method . getSignature ( ) , Hierarchy . INSTANCE_METHOD ) ; if ( match != null ) { return true ; } } JavaClass [ ] interfaceList = javaClass . getAllInterfaces ( ) ; if ( interfaceList != null ) { JavaClassAndMethod match = Hierarchy . findMethod ( interfaceList , method . getName ( ) , method . getSignature ( ) , Hierarchy . INSTANCE_METHOD ) ; if ( match != null ) { return true ; } } return false ; } catch ( ClassNotFoundException e ) { return true ; } }
|
Determine if given method overrides a superclass or superinterface method .
| 206
| 16
|
153,536
|
public static String transformClassName ( String className ) { int lastDot = className . lastIndexOf ( ' ' ) ; if ( lastDot >= 0 ) { String pkg = className . substring ( 0 , lastDot ) ; if ( ! isUnlikelyToBeRenamed ( pkg ) ) { className = className . substring ( lastDot + 1 ) ; } } return className ; }
|
Transform a class name by stripping its package name .
| 93
| 10
|
153,537
|
public static String transformMethodSignature ( String signature ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( ' ' ) ; SignatureParser parser = new SignatureParser ( signature ) ; for ( Iterator < String > i = parser . parameterSignatureIterator ( ) ; i . hasNext ( ) ; ) { String param = i . next ( ) ; param = transformSignature ( param ) ; buf . append ( param ) ; } buf . append ( ' ' ) ; return buf . toString ( ) ; }
|
Transform a method signature to allow it to be compared even if any of its parameter types are moved to another package .
| 111
| 23
|
153,538
|
public static String transformSignature ( String signature ) { StringBuilder buf = new StringBuilder ( ) ; int lastBracket = signature . lastIndexOf ( ' ' ) ; if ( lastBracket > 0 ) { buf . append ( signature . substring ( 0 , lastBracket + 1 ) ) ; signature = signature . substring ( lastBracket + 1 ) ; } if ( signature . startsWith ( "L" ) ) { signature = signature . substring ( 1 , signature . length ( ) - 1 ) . replace ( ' ' , ' ' ) ; signature = transformClassName ( signature ) ; signature = "L" + signature . replace ( ' ' , ' ' ) + ";" ; } buf . append ( signature ) ; return buf . toString ( ) ; }
|
Transform a field or method parameter signature to allow it to be compared even if it is moved to another package .
| 165
| 22
|
153,539
|
private void handleExceptions ( Subroutine subroutine , InstructionHandle pei , BasicBlock etb ) { etb . setExceptionThrower ( pei ) ; // Remember whether or not a universal exception handler // is reachable. If so, then we know that exceptions raised // at this instruction cannot propagate out of the method. boolean sawUniversalExceptionHandler = false ; List < CodeExceptionGen > exceptionHandlerList = exceptionHandlerMap . getHandlerList ( pei ) ; if ( exceptionHandlerList != null ) { for ( CodeExceptionGen exceptionHandler : exceptionHandlerList ) { InstructionHandle handlerStart = exceptionHandler . getHandlerPC ( ) ; subroutine . addEdgeAndExplore ( etb , handlerStart , HANDLED_EXCEPTION_EDGE ) ; if ( Hierarchy . isUniversalExceptionHandler ( exceptionHandler . getCatchType ( ) ) ) { sawUniversalExceptionHandler = true ; } } } // If required, mark this block as throwing an unhandled exception. // For now, we assume that if there is no reachable handler that handles // ANY exception type, then the exception can be thrown out of the // method. if ( ! sawUniversalExceptionHandler ) { if ( DEBUG ) { System . out . println ( "Adding unhandled exception edge from " + pei ) ; } subroutine . setUnhandledExceptionBlock ( etb ) ; } }
|
Add exception edges for given instruction .
| 292
| 7
|
153,540
|
private boolean isPEI ( InstructionHandle handle ) throws CFGBuilderException { Instruction ins = handle . getInstruction ( ) ; if ( ! ( ins instanceof ExceptionThrower ) ) { return false ; } if ( ins instanceof NEW ) { return false ; } // if (ins instanceof ATHROW) return false; if ( ins instanceof GETSTATIC ) { return false ; } if ( ins instanceof PUTSTATIC ) { return false ; } if ( ins instanceof ReturnInstruction ) { return false ; } if ( ins instanceof INSTANCEOF ) { return false ; } if ( ins instanceof MONITOREXIT ) { return false ; } if ( ins instanceof LDC ) { return false ; } if ( ins instanceof GETFIELD && ! methodGen . isStatic ( ) ) { // Assume that GETFIELD on this object is not PEI return ! isSafeFieldSource ( handle . getPrev ( ) ) ; } if ( ins instanceof PUTFIELD && ! methodGen . isStatic ( ) ) { // Assume that PUTFIELD on this object is not PEI int depth = ins . consumeStack ( cpg ) ; for ( InstructionHandle prev = handle . getPrev ( ) ; prev != null ; prev = prev . getPrev ( ) ) { Instruction prevInst = prev . getInstruction ( ) ; if ( prevInst instanceof BranchInstruction ) { if ( prevInst instanceof GotoInstruction ) { // Currently we support only jumps to the PUTFIELD itself // This will cover simple cases like this.a = flag ? foo : bar if ( ( ( BranchInstruction ) prevInst ) . getTarget ( ) == handle ) { depth = ins . consumeStack ( cpg ) ; } else { return true ; } } else if ( ! ( prevInst instanceof IfInstruction ) ) { // As IF instructions may fall through then the stack depth remains unchanged // Actually we should not go here for normal Java bytecode: switch or jsr should not appear in this context return true ; } } depth = depth - prevInst . produceStack ( cpg ) + prevInst . consumeStack ( cpg ) ; if ( depth < 1 ) { throw new CFGBuilderException ( "Invalid stack at " + prev + " when checking " + handle ) ; } if ( depth == 1 ) { InstructionHandle prevPrev = prev . getPrev ( ) ; if ( prevPrev != null && prevPrev . getInstruction ( ) instanceof BranchInstruction ) { continue ; } return ! isSafeFieldSource ( prevPrev ) ; } } } return true ; }
|
Return whether or not the given instruction can throw exceptions .
| 553
| 11
|
153,541
|
private static boolean isMerge ( InstructionHandle handle ) { if ( handle . hasTargeters ( ) ) { // Check all targeters of this handle to see if any // of them are branches. If so, the instruction is a merge. InstructionTargeter [ ] targeterList = handle . getTargeters ( ) ; for ( InstructionTargeter targeter : targeterList ) { if ( targeter instanceof BranchInstruction ) { return true ; } } } return false ; }
|
Determine whether or not the given instruction is a control flow merge .
| 105
| 15
|
153,542
|
private CFG inlineAll ( ) throws CFGBuilderException { CFG result = new CFG ( ) ; Context rootContext = new Context ( null , topLevelSubroutine , result ) ; rootContext . mapBlock ( topLevelSubroutine . getEntry ( ) , result . getEntry ( ) ) ; rootContext . mapBlock ( topLevelSubroutine . getExit ( ) , result . getExit ( ) ) ; BasicBlock resultStartBlock = rootContext . getBlock ( topLevelSubroutine . getStartBlock ( ) ) ; result . createEdge ( result . getEntry ( ) , resultStartBlock , START_EDGE ) ; inline ( rootContext ) ; return result ; }
|
Inline all JSR subroutines into the top - level subroutine . This produces a complete CFG for the entire method in which all JSR subroutines are inlined .
| 149
| 41
|
153,543
|
public static void main ( String [ ] argv ) throws Exception { if ( argv . length != 1 ) { System . err . println ( "Usage: " + BetterCFGBuilder2 . class . getName ( ) + " <class file>" ) ; System . exit ( 1 ) ; } String methodName = SystemProperties . getProperty ( "cfgbuilder.method" ) ; JavaClass jclass = new ClassParser ( argv [ 0 ] ) . parse ( ) ; ClassGen classGen = new ClassGen ( jclass ) ; Method [ ] methodList = jclass . getMethods ( ) ; for ( Method method : methodList ) { if ( method . isAbstract ( ) || method . isNative ( ) ) { continue ; } if ( methodName != null && ! method . getName ( ) . equals ( methodName ) ) { continue ; } MethodDescriptor descriptor = DescriptorFactory . instance ( ) . getMethodDescriptor ( jclass , method ) ; MethodGen methodGen = new MethodGen ( method , jclass . getClassName ( ) , classGen . getConstantPool ( ) ) ; CFGBuilder cfgBuilder = new BetterCFGBuilder2 ( descriptor , methodGen ) ; cfgBuilder . build ( ) ; CFG cfg = cfgBuilder . getCFG ( ) ; CFGPrinter cfgPrinter = new CFGPrinter ( cfg ) ; System . out . println ( "---------------------------------------------------------------------" ) ; System . out . println ( "Method: " + SignatureConverter . convertMethodSignature ( methodGen ) ) ; System . out . println ( "---------------------------------------------------------------------" ) ; cfgPrinter . print ( System . out ) ; } }
|
Test driver .
| 370
| 3
|
153,544
|
public static XField createXField ( String className , Field field ) { String fieldName = field . getName ( ) ; String fieldSig = field . getSignature ( ) ; XField xfield = getExactXField ( className , fieldName , fieldSig , field . isStatic ( ) ) ; assert xfield . isResolved ( ) : "Could not exactly resolve " + xfield ; return xfield ; }
|
Create an XField object from a BCEL Field .
| 94
| 11
|
153,545
|
public static XMethod createXMethod ( InvokeInstruction invokeInstruction , ConstantPoolGen cpg ) { String className = invokeInstruction . getClassName ( cpg ) ; String methodName = invokeInstruction . getName ( cpg ) ; String methodSig = invokeInstruction . getSignature ( cpg ) ; if ( invokeInstruction instanceof INVOKEDYNAMIC ) { // XXX the lambda representation makes no sense for XMethod // "classical" instruction attributes are filled with garbage, causing // the code later to produce crazy errors (looking for non existing types etc) // We should NOT be called here from our code, but 3rd party code still may // use this method. So *at least* provide a valid class name, which is // (don't ask me why) is encoded in the first argument type of the lambda // className = invokeInstruction.getArgumentTypes(cpg)[0].toString(); className = Values . DOTTED_JAVA_LANG_OBJECT ; } return createXMethod ( className , methodName , methodSig , invokeInstruction . getOpcode ( ) == Const . INVOKESTATIC ) ; }
|
Create an XMethod object from an InvokeInstruction .
| 256
| 12
|
153,546
|
public static XMethod createXMethod ( PreorderVisitor visitor ) { JavaClass javaClass = visitor . getThisClass ( ) ; Method method = visitor . getMethod ( ) ; XMethod m = createXMethod ( javaClass , method ) ; return m ; }
|
Create an XMethod object from the method currently being visited by the given PreorderVisitor .
| 56
| 19
|
153,547
|
public static XField createXField ( PreorderVisitor visitor ) { JavaClass javaClass = visitor . getThisClass ( ) ; Field field = visitor . getField ( ) ; XField f = createXField ( javaClass , field ) ; return f ; }
|
Create an XField object from the field currently being visited by the given PreorderVisitor .
| 56
| 19
|
153,548
|
public @ CheckForNull XClass getXClass ( ClassDescriptor classDescriptor ) { try { IAnalysisCache analysisCache = Global . getAnalysisCache ( ) ; return analysisCache . getClassAnalysis ( XClass . class , classDescriptor ) ; } catch ( CheckedAnalysisException e ) { return null ; } }
|
Get the XClass object providing information about the class named by the given ClassDescriptor .
| 71
| 19
|
153,549
|
protected void work ( IWorkbenchPart part , final IResource resource , final List < WorkItem > resources ) { FindBugsJob runFindBugs = new StartedFromViewJob ( "Finding bugs in " + resource . getName ( ) + "..." , resource , resources , part ) ; runFindBugs . scheduleInteractive ( ) ; }
|
Run a FindBugs analysis on the given resource displaying a progress monitor .
| 74
| 15
|
153,550
|
public void setClasspath ( Path src ) { if ( classpath == null ) { classpath = src ; } else { classpath . append ( src ) ; } }
|
Set the classpath to use .
| 36
| 7
|
153,551
|
public void setClasspathRef ( Reference r ) { Path path = createClasspath ( ) ; path . setRefid ( r ) ; path . toString ( ) ; // Evaluated for its side-effects (throwing a // BuildException) }
|
Adds a reference to a classpath defined elsewhere .
| 53
| 10
|
153,552
|
protected void checkParameters ( ) { if ( homeDir == null && classpath == null ) { throw new BuildException ( "either home attribute or " + "classpath attributes " + " must be defined for task <" + getTaskName ( ) + "/>" , getLocation ( ) ) ; } if ( pluginList != null ) { // Make sure that all plugins are actually Jar files. String [ ] pluginFileList = pluginList . list ( ) ; for ( String pluginFile : pluginFileList ) { if ( ! pluginFile . endsWith ( ".jar" ) ) { throw new BuildException ( "plugin file " + pluginFile + " is not a Jar file " + "in task <" + getTaskName ( ) + "/>" , getLocation ( ) ) ; } } } for ( SystemProperty systemProperty : systemPropertyList ) { if ( systemProperty . getName ( ) == null || systemProperty . getValue ( ) == null ) { throw new BuildException ( "systemProperty elements must have name and value attributes" ) ; } } }
|
Check that all required attributes have been set .
| 223
| 9
|
153,553
|
private void execFindbugs ( ) throws BuildException { System . out . println ( "Executing SpotBugs " + this . getClass ( ) . getSimpleName ( ) + " from ant task" ) ; createFindbugsEngine ( ) ; configureFindbugsEngine ( ) ; beforeExecuteJavaProcess ( ) ; if ( getDebug ( ) ) { log ( getFindbugsEngine ( ) . getCommandLine ( ) . describeCommand ( ) ) ; } /* * set property containing return code of child process using a task * identifier and a UUID to ensure exit code corresponds to this * execution (the base Ant Task won't overwrite return code once it's * been set, so unique identifiers must be used for each execution if we * want to get the exit code) */ String execReturnCodeIdentifier = execResultProperty + "." + UUID . randomUUID ( ) . toString ( ) ; getFindbugsEngine ( ) . setResultProperty ( execReturnCodeIdentifier ) ; /* * if the execution fails, we'll report it ourself -- prevent the * underlying Ant Java object from throwing an exception */ getFindbugsEngine ( ) . setFailonerror ( false ) ; try { getFindbugsEngine ( ) . execute ( ) ; } catch ( BuildException be ) { // setFailonerror(false) should ensure that this doesn't happen, // but... log ( be . toString ( ) ) ; } String returnProperty = getFindbugsEngine ( ) . getProject ( ) . getProperty ( execReturnCodeIdentifier ) ; int rc = returnProperty == null ? 0 : Integer . parseInt ( returnProperty ) ; afterExecuteJavaProcess ( rc ) ; }
|
Create a new JVM to do the work .
| 355
| 10
|
153,554
|
public static void configureTrainingDatabases ( IFindBugsEngine findBugs ) throws IOException { if ( findBugs . emitTrainingOutput ( ) ) { String trainingOutputDir = findBugs . getTrainingOutputDir ( ) ; if ( ! new File ( trainingOutputDir ) . isDirectory ( ) ) { throw new IOException ( "Training output directory " + trainingOutputDir + " does not exist" ) ; } AnalysisContext . currentAnalysisContext ( ) . setDatabaseOutputDir ( trainingOutputDir ) ; // XXX: hack System . setProperty ( "findbugs.checkreturn.savetraining" , new File ( trainingOutputDir , "checkReturn.db" ) . getPath ( ) ) ; } if ( findBugs . useTrainingInput ( ) ) { String trainingInputDir = findBugs . getTrainingInputDir ( ) ; if ( ! new File ( trainingInputDir ) . isDirectory ( ) ) { throw new IOException ( "Training input directory " + trainingInputDir + " does not exist" ) ; } AnalysisContext . currentAnalysisContext ( ) . setDatabaseInputDir ( trainingInputDir ) ; AnalysisContext . currentAnalysisContext ( ) . loadInterproceduralDatabases ( ) ; // XXX: hack System . setProperty ( "findbugs.checkreturn.loadtraining" , new File ( trainingInputDir , "checkReturn.db" ) . getPath ( ) ) ; } else { AnalysisContext . currentAnalysisContext ( ) . loadDefaultInterproceduralDatabases ( ) ; } }
|
Configure training databases .
| 324
| 5
|
153,555
|
public static boolean isDetectorEnabled ( IFindBugsEngine findBugs , DetectorFactory factory , int rankThreshold ) { if ( ! findBugs . getUserPreferences ( ) . isDetectorEnabled ( factory ) ) { return false ; } if ( ! factory . isEnabledForCurrentJRE ( ) ) { return false ; } // Slow first pass detectors are usually disabled, but may be explicitly // enabled if ( ! AnalysisContext . currentAnalysisContext ( ) . getBoolProperty ( FindBugsAnalysisFeatures . INTERPROCEDURAL_ANALYSIS ) && factory . isDetectorClassSubtypeOf ( InterproceduralFirstPassDetector . class ) ) { return false ; } int maxRank = Integer . MAX_VALUE ; Set < BugPattern > reportedBugPatterns = factory . getReportedBugPatterns ( ) ; boolean isNonReportingDetector = factory . isDetectorClassSubtypeOf ( FirstPassDetector . class ) ; if ( ! isNonReportingDetector && ! reportedBugPatterns . isEmpty ( ) ) { for ( BugPattern b : reportedBugPatterns ) { int rank = BugRanker . findRank ( b , factory ) ; if ( maxRank > rank ) { maxRank = rank ; } } if ( maxRank > rankThreshold ) { return false ; } } // Training detectors are enabled if, and only if, we are emitting // training output boolean isTrainingDetector = factory . isDetectorClassSubtypeOf ( TrainingDetector . class ) ; if ( findBugs . emitTrainingOutput ( ) ) { return isTrainingDetector || isNonReportingDetector ; } return ! isTrainingDetector ; }
|
Determines whether or not given DetectorFactory should be enabled .
| 359
| 14
|
153,556
|
public static Set < String > handleBugCategories ( String categories ) { // Parse list of bug categories Set < String > categorySet = new HashSet <> ( ) ; StringTokenizer tok = new StringTokenizer ( categories , "," ) ; while ( tok . hasMoreTokens ( ) ) { categorySet . add ( tok . nextToken ( ) ) ; } return categorySet ; }
|
Process - bugCategories option .
| 86
| 7
|
153,557
|
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. try { argv = commandLine . expandOptionFiles ( argv , true , true ) ; } catch ( HelpRequestedException e ) { showHelp ( commandLine ) ; } int argCount = 0 ; try { argCount = commandLine . parse ( argv ) ; } catch ( IllegalArgumentException e ) { LOG . severe ( 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 ( ) ; commandLine . configureEngine ( findBugs ) ; if ( commandLine . getProject ( ) . getFileCount ( ) == 0 && ! commandLine . justPrintConfiguration ( ) && ! commandLine . justPrintVersion ( ) ) { LOG . warning ( "No files to be analyzed" ) ; showHelp ( commandLine ) ; } }
|
Process the command line .
| 323
| 5
|
153,558
|
@ SuppressFBWarnings ( "DM_EXIT" ) public static void showHelp ( TextUICommandLine commandLine ) { showSynopsis ( ) ; ShowHelp . showGeneralOptions ( ) ; FindBugs . showCommandLineOptions ( commandLine ) ; System . exit ( 1 ) ; }
|
Show - help message .
| 66
| 5
|
153,559
|
@ SuppressFBWarnings ( "DM_EXIT" ) public static void runMain ( IFindBugsEngine findBugs , TextUICommandLine commandLine ) throws IOException { boolean verbose = ! commandLine . quiet ( ) ; try { findBugs . execute ( ) ; } catch ( InterruptedException e ) { assert false ; // should not occur checkExitCodeFail ( commandLine , e ) ; throw new RuntimeException ( e ) ; } catch ( RuntimeException | IOException e ) { checkExitCodeFail ( commandLine , e ) ; throw e ; } int bugCount = findBugs . getBugCount ( ) ; int missingClassCount = findBugs . getMissingClassCount ( ) ; int errorCount = findBugs . getErrorCount ( ) ; if ( verbose || commandLine . setExitCode ( ) ) { LOG . log ( FINE , "Warnings generated: {0}" , bugCount ) ; LOG . log ( FINE , "Missing classes: {0}" , missingClassCount ) ; LOG . log ( FINE , "Analysis errors: {0}" , errorCount ) ; } if ( commandLine . setExitCode ( ) ) { int exitCode = 0 ; LOG . info ( "Calculating exit code..." ) ; if ( errorCount > 0 ) { exitCode |= ExitCodes . ERROR_FLAG ; LOG . log ( FINE , "Setting 'errors encountered' flag ({0})" , ExitCodes . ERROR_FLAG ) ; } if ( missingClassCount > 0 ) { exitCode |= ExitCodes . MISSING_CLASS_FLAG ; LOG . log ( FINE , "Setting 'missing class' flag ({0})" , ExitCodes . MISSING_CLASS_FLAG ) ; } if ( bugCount > 0 ) { exitCode |= ExitCodes . BUGS_FOUND_FLAG ; LOG . log ( FINE , "Setting 'bugs found' flag ({0})" , ExitCodes . BUGS_FOUND_FLAG ) ; } LOG . log ( FINE , "Exit code set to: {0}" , exitCode ) ; System . exit ( exitCode ) ; } }
|
Given a fully - configured IFindBugsEngine and the TextUICommandLine used to configure it execute the analysis .
| 472
| 26
|
153,560
|
public static BugReporter configureBaselineFilter ( BugReporter bugReporter , String baselineFileName ) throws IOException , DocumentException { return new ExcludingHashesBugReporter ( bugReporter , baselineFileName ) ; }
|
Configure a baseline bug instance filter .
| 49
| 8
|
153,561
|
public void analyzeInstruction ( Instruction ins ) throws DataflowAnalysisException { if ( frame . isValid ( ) ) { try { ins . accept ( this ) ; } catch ( InvalidBytecodeException e ) { String message = "Invalid bytecode: could not analyze instr. " + ins + " at frame " + frame ; throw new DataflowAnalysisException ( message , e ) ; } } }
|
Analyze the given Instruction .
| 83
| 6
|
153,562
|
public int getNumWordsConsumed ( Instruction ins ) { int numWordsConsumed = ins . consumeStack ( cpg ) ; if ( numWordsConsumed == Const . UNPREDICTABLE ) { throw new InvalidBytecodeException ( "Unpredictable stack consumption" ) ; } return numWordsConsumed ; }
|
Get the number of words consumed by given instruction .
| 68
| 10
|
153,563
|
public int getNumWordsProduced ( Instruction ins ) { int numWordsProduced = ins . produceStack ( cpg ) ; if ( numWordsProduced == Const . UNPREDICTABLE ) { throw new InvalidBytecodeException ( "Unpredictable stack productions" ) ; } return numWordsProduced ; }
|
Get the number of words produced by given instruction .
| 68
| 10
|
153,564
|
@ Override public final void visitConversionInstruction ( ConversionInstruction obj ) { visitConversionInstruction2 ( obj ) ; if ( obj instanceof NULL2Z ) { visitNULL2Z ( ( NULL2Z ) obj ) ; } else if ( obj instanceof NONNULL2Z ) { visitNONNULL2Z ( ( NONNULL2Z ) obj ) ; } }
|
To allow for calls to visitNULL2Z and visitNONNULL2Z this method is made final . If you want to override it override visitConversionInstruction2 instead .
| 82
| 37
|
153,565
|
public void handleStoreInstruction ( StoreInstruction obj ) { try { int numConsumed = obj . consumeStack ( cpg ) ; if ( numConsumed == Const . UNPREDICTABLE ) { throw new InvalidBytecodeException ( "Unpredictable stack consumption" ) ; } int index = obj . getIndex ( ) ; // Store values into consecutive locals corresponding // to the order in which the values appeared on the stack. while ( numConsumed -- > 0 ) { Value value = frame . popValue ( ) ; frame . setValue ( index ++ , value ) ; } } catch ( DataflowAnalysisException e ) { throw new InvalidBytecodeException ( e . toString ( ) ) ; } }
|
Handler for all instructions which pop values from the stack and store them in a local variable . Note that two locals are stored into for long and double stores .
| 151
| 31
|
153,566
|
public void modelInstruction ( Instruction ins , int numWordsConsumed , int numWordsProduced , Value pushValue ) { if ( frame . getStackDepth ( ) < numWordsConsumed ) { try { throw new IllegalArgumentException ( " asked to pop " + numWordsConsumed + " stack elements but only " + frame . getStackDepth ( ) + " elements remain in " + frame + " while processing " + ins ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( " asked to pop " + numWordsConsumed + " stack elements but only " + frame . getStackDepth ( ) + " elements remain while processing " + ins ) ; } } try { while ( numWordsConsumed -- > 0 ) { frame . popValue ( ) ; } } catch ( DataflowAnalysisException e ) { throw new InvalidBytecodeException ( "Not enough values on the stack" , e ) ; } while ( numWordsProduced -- > 0 ) { frame . pushValue ( pushValue ) ; } }
|
Primitive to model the stack effect of a single instruction explicitly specifying the value to be pushed on the stack .
| 218
| 22
|
153,567
|
private void locateCodebasesRequiredForAnalysis ( IClassPath classPath , IClassPathBuilderProgress progress ) throws InterruptedException , IOException , ResourceNotFoundException { boolean foundJavaLangObject = false ; boolean foundFindBugsAnnotations = false ; boolean foundJSR305Annotations = false ; for ( DiscoveredCodeBase discoveredCodeBase : discoveredCodeBaseList ) { if ( ! foundJavaLangObject ) { foundJavaLangObject = probeCodeBaseForResource ( discoveredCodeBase , "java/lang/Object.class" ) ; } if ( ! foundFindBugsAnnotations ) { foundFindBugsAnnotations = probeCodeBaseForResource ( discoveredCodeBase , "edu/umd/cs/findbugs/annotations/Nonnull.class" ) ; } if ( ! foundJSR305Annotations ) { foundJSR305Annotations = probeCodeBaseForResource ( discoveredCodeBase , "javax/annotation/meta/TypeQualifier.class" ) ; if ( DEBUG ) { System . out . println ( "foundJSR305Annotations: " + foundJSR305Annotations ) ; } } } if ( ! foundJavaLangObject ) { processWorkList ( classPath , buildSystemCodebaseList ( ) , progress ) ; } // If we're running findbugs-full.jar, IT contains the contents // of jsr305.jar and annotations.jar. So, add it to the classpath. if ( runningFindBugsFullJar ( ) ) { processWorkList ( classPath , buildFindBugsFullJarCodebaseList ( ) , progress ) ; return ; } // Not running findbugs-full.jar: try to find jsr305.jar and // annotations.jar. if ( ! foundFindBugsAnnotations ) { processWorkList ( classPath , buildFindBugsAnnotationCodebaseList ( ) , progress ) ; } if ( ! foundJSR305Annotations ) { processWorkList ( classPath , buildJSR305AnnotationsCodebaseList ( ) , progress ) ; } }
|
Make an effort to find the codebases containing any files required for analysis .
| 443
| 16
|
153,568
|
private boolean probeCodeBaseForResource ( DiscoveredCodeBase discoveredCodeBase , String resourceName ) { ICodeBaseEntry resource = discoveredCodeBase . getCodeBase ( ) . lookupResource ( resourceName ) ; return resource != null ; }
|
Probe a codebase to see if a given source exists in that code base .
| 50
| 17
|
153,569
|
private void addWorkListItemsForClasspath ( LinkedList < WorkListItem > workList , String path ) { if ( path == null ) { return ; } StringTokenizer st = new StringTokenizer ( path , File . pathSeparator ) ; while ( st . hasMoreTokens ( ) ) { String entry = st . nextToken ( ) ; if ( DEBUG ) { System . out . println ( "System classpath entry: " + entry ) ; } addToWorkList ( workList , new WorkListItem ( classFactory . createFilesystemCodeBaseLocator ( entry ) , false , ICodeBase . Discovered . IN_SYSTEM_CLASSPATH ) ) ; } }
|
Add worklist items from given system classpath .
| 149
| 10
|
153,570
|
private void addWorkListItemsForExtDir ( LinkedList < WorkListItem > workList , String extDir ) { File dir = new File ( extDir ) ; File [ ] fileList = dir . listFiles ( ( FileFilter ) pathname -> { String path = pathname . getPath ( ) ; boolean isArchive = Archive . isArchiveFileName ( path ) ; return isArchive ; } ) ; if ( fileList == null ) { return ; } for ( File archive : fileList ) { addToWorkList ( workList , new WorkListItem ( classFactory . createFilesystemCodeBaseLocator ( archive . getPath ( ) ) , false , ICodeBase . Discovered . IN_SYSTEM_CLASSPATH ) ) ; } }
|
Add worklist items from given extensions directory .
| 165
| 9
|
153,571
|
private void parseClassName ( ICodeBaseEntry entry ) { DataInputStream in = null ; try { InputStream resourceIn = entry . openResource ( ) ; if ( resourceIn == null ) { throw new NullPointerException ( "Got null resource" ) ; } in = new DataInputStream ( resourceIn ) ; ClassParserInterface parser = new ClassParser ( in , null , entry ) ; ClassNameAndSuperclassInfo . Builder builder = new ClassNameAndSuperclassInfo . Builder ( ) ; parser . parse ( builder ) ; String trueResourceName = builder . build ( ) . getClassDescriptor ( ) . toResourceName ( ) ; if ( ! trueResourceName . equals ( entry . getResourceName ( ) ) ) { entry . overrideResourceName ( trueResourceName ) ; } } catch ( IOException e ) { errorLogger . logError ( "Invalid class resource " + entry . getResourceName ( ) + " in " + entry , e ) ; } catch ( InvalidClassFileFormatException e ) { errorLogger . logError ( "Invalid class resource " + entry . getResourceName ( ) + " in " + entry , e ) ; } finally { IO . close ( in ) ; } }
|
Attempt to parse data of given resource in order to divine the real name of the class contained in the resource .
| 260
| 22
|
153,572
|
private void scanJarManifestForClassPathEntries ( LinkedList < WorkListItem > workList , ICodeBase codeBase ) throws IOException { // See if this codebase has a jar manifest ICodeBaseEntry manifestEntry = codeBase . lookupResource ( "META-INF/MANIFEST.MF" ) ; if ( manifestEntry == null ) { // Do nothing - no Jar manifest found return ; } // Try to read the manifest InputStream in = null ; try { in = manifestEntry . openResource ( ) ; Manifest manifest = new Manifest ( in ) ; Attributes mainAttrs = manifest . getMainAttributes ( ) ; String classPath = mainAttrs . getValue ( "Class-Path" ) ; if ( classPath != null ) { String [ ] pathList = classPath . split ( "\\s+" ) ; for ( String path : pathList ) { // Create a codebase locator for the classpath entry // relative to the codebase in which we discovered the Jar // manifest ICodeBaseLocator relativeCodeBaseLocator = codeBase . getCodeBaseLocator ( ) . createRelativeCodeBaseLocator ( path ) ; // Codebases found in Class-Path entries are always // added to the aux classpath, not the application. addToWorkList ( workList , new WorkListItem ( relativeCodeBaseLocator , false , ICodeBase . Discovered . IN_JAR_MANIFEST ) ) ; } } } finally { if ( in != null ) { IO . close ( in ) ; } } }
|
Check a codebase for a Jar manifest to examine for Class - Path entries .
| 333
| 16
|
153,573
|
public void addCreatedResource ( Location location , Resource resource ) { resourceList . add ( resource ) ; locationToResourceMap . put ( location , resource ) ; }
|
Add a resource created within the analyzed method .
| 34
| 9
|
153,574
|
protected void syncUserPreferencesWithTable ( ) { TableItem [ ] itemList = availableFactoriesTableViewer . getTable ( ) . getItems ( ) ; UserPreferences currentProps = getCurrentProps ( ) ; for ( int i = 0 ; i < itemList . length ; i ++ ) { DetectorFactory factory = ( DetectorFactory ) itemList [ i ] . getData ( ) ; // set enabled if defined in configuration currentProps . enableDetector ( factory , itemList [ i ] . getChecked ( ) ) ; } }
|
Disables all unchecked detector factories and enables checked factory detectors leaving those not in the table unmodified .
| 120
| 20
|
153,575
|
private Table createDetectorsTableViewer ( Composite parent , IProject project ) { final BugPatternTableSorter sorter = new BugPatternTableSorter ( this ) ; int tableStyle = SWT . BORDER | SWT . H_SCROLL | SWT . V_SCROLL | SWT . SINGLE | SWT . FULL_SELECTION | SWT . CHECK ; availableFactoriesTableViewer = CheckboxTableViewer . newCheckList ( parent , tableStyle ) ; availableFactoriesTableViewer . addCheckStateListener ( new ICheckStateListener ( ) { @ Override public void checkStateChanged ( CheckStateChangedEvent event ) { syncUserPreferencesWithTable ( ) ; } } ) ; int currentColumnIdx = 0 ; Table factoriesTable = availableFactoriesTableViewer . getTable ( ) ; TableColumn factoryNameColumn = createColumn ( currentColumnIdx , factoriesTable , getMessage ( "property.detectorName" ) , 230 , COLUMN . DETECTOR_NAME ) ; addColumnSelectionListener ( sorter , factoryNameColumn , COLUMN . DETECTOR_NAME ) ; currentColumnIdx ++ ; TableColumn bugsAbbrevColumn = createColumn ( currentColumnIdx , factoriesTable , getMessage ( "property.bugCodes" ) , 75 , COLUMN . BUG_CODES ) ; addColumnSelectionListener ( sorter , bugsAbbrevColumn , COLUMN . BUG_CODES ) ; currentColumnIdx ++ ; TableColumn speedColumn = createColumn ( currentColumnIdx , factoriesTable , getMessage ( "property.speed" ) , 70 , COLUMN . DETECTOR_SPEED ) ; addColumnSelectionListener ( sorter , speedColumn , COLUMN . DETECTOR_SPEED ) ; currentColumnIdx ++ ; TableColumn pluginColumn = createColumn ( currentColumnIdx , factoriesTable , getMessage ( "property.provider" ) , 100 , COLUMN . PLUGIN ) ; addColumnSelectionListener ( sorter , pluginColumn , COLUMN . PLUGIN ) ; currentColumnIdx ++ ; TableColumn categoryColumn = createColumn ( currentColumnIdx , factoriesTable , getMessage ( "property.category" ) , 75 , COLUMN . BUG_CATEGORIES ) ; addColumnSelectionListener ( sorter , categoryColumn , COLUMN . BUG_CATEGORIES ) ; factoriesTable . setLinesVisible ( true ) ; factoriesTable . setHeaderVisible ( true ) ; // initial sort indicator factoriesTable . setSortDirection ( sorter . revertOrder ? SWT . UP : SWT . DOWN ) ; factoriesTable . setSortColumn ( factoryNameColumn ) ; sorter . setSortColumnIndex ( COLUMN . DETECTOR_NAME ) ; availableFactoriesTableViewer . setContentProvider ( new DetectorFactoriesContentProvider ( ) ) ; availableFactoriesTableViewer . setLabelProvider ( new DetectorFactoryLabelProvider ( this ) ) ; availableFactoriesTableViewer . setSorter ( sorter ) ; populateAvailableRulesTable ( project ) ; factoriesTable . setEnabled ( true ) ; return factoriesTable ; }
|
Build rule table viewer
| 699
| 4
|
153,576
|
private void populateAvailableRulesTable ( IProject project ) { List < DetectorFactory > allAvailableList = new ArrayList <> ( ) ; factoriesToBugAbbrev = new HashMap <> ( ) ; Iterator < DetectorFactory > iterator = DetectorFactoryCollection . instance ( ) . factoryIterator ( ) ; while ( iterator . hasNext ( ) ) { DetectorFactory factory = iterator . next ( ) ; // Only configure non-hidden factories if ( factory . isHidden ( ) && ! isHiddenVisible ( ) ) { continue ; } allAvailableList . add ( factory ) ; addBugsAbbreviation ( factory ) ; } availableFactoriesTableViewer . setInput ( allAvailableList ) ; TableItem [ ] itemList = availableFactoriesTableViewer . getTable ( ) . getItems ( ) ; UserPreferences userPreferences = getCurrentProps ( ) ; for ( int i = 0 ; i < itemList . length ; i ++ ) { DetectorFactory rule = ( DetectorFactory ) itemList [ i ] . getData ( ) ; // set enabled if defined in configuration if ( userPreferences . isDetectorEnabled ( rule ) ) { itemList [ i ] . setChecked ( true ) ; } } }
|
Populate the rule table
| 267
| 5
|
153,577
|
public void mergeWith ( ReturnPathType fact ) { if ( fact . isTop ( ) ) { // other fact is top: no change to this one return ; } else if ( this . isTop ( ) ) { // this fact is top: copy other fact this . copyFrom ( fact ) ; } else { // neither fact is top: as long as one of the two // facts represents a (possible) normal return, then the result // is a possible normal return if ( fact . type == CAN_RETURN_NORMALLY ) { this . type = CAN_RETURN_NORMALLY ; } } }
|
Merge this fact with given fact .
| 131
| 8
|
153,578
|
@ Override public void handleAbout ( ApplicationEvent ae ) { if ( mainApp != null ) { ae . setHandled ( true ) ; // We need to invoke modal About Dialog asynchronously // otherwise the Application queue is locked for the duration // of the about Dialog, which results in a deadlock if a URL is // selected, and we get a ReOpenApplication event when user // switches back to Findbugs. javax . swing . SwingUtilities . invokeLater ( ( ) -> mainApp . about ( ) ) ; } else { throw new IllegalStateException ( "handleAbout: " + "MyApp instance detached from listener" ) ; } }
|
over from another platform .
| 143
| 5
|
153,579
|
@ Override public BleIllegalOperationException handleMismatchData ( BluetoothGattCharacteristic characteristic , int neededProperties ) { RxBleLog . w ( messageCreator . createMismatchMessage ( characteristic , neededProperties ) ) ; return null ; }
|
This method logs a warning .
| 56
| 6
|
153,580
|
public static RxBleClient getRxBleClient ( Context context ) { SampleApplication application = ( SampleApplication ) context . getApplicationContext ( ) ; return application . rxBleClient ; }
|
In practise you will use some kind of dependency injection pattern .
| 40
| 12
|
153,581
|
public Completable checkAnyPropertyMatches ( final BluetoothGattCharacteristic characteristic , final @ BluetoothGattCharacteristicProperty int neededProperties ) { return Completable . fromAction ( new Action ( ) { public void run ( ) { final int characteristicProperties = characteristic . getProperties ( ) ; if ( ( characteristicProperties & neededProperties ) == 0 ) { BleIllegalOperationException exception = resultHandler . handleMismatchData ( characteristic , neededProperties ) ; if ( exception != null ) { throw exception ; } } } } ) ; }
|
This method checks whether the supplied characteristic possesses properties supporting the requested kind of operation specified by the supplied bitmask .
| 120
| 22
|
153,582
|
public static void handleException ( final Activity context , final BleScanException exception ) { final String text ; final int reason = exception . getReason ( ) ; // Special case, as there might or might not be a retry date suggestion if ( reason == BleScanException . UNDOCUMENTED_SCAN_THROTTLE ) { text = getUndocumentedScanThrottleErrorMessage ( context , exception . getRetryDateSuggestion ( ) ) ; } else { // Handle all other possible errors final Integer resId = ERROR_MESSAGES . get ( reason ) ; if ( resId != null ) { text = context . getString ( resId ) ; } else { // unknown error - return default message Log . w ( "Scanning" , String . format ( "No message found for reason=%d. Consider adding one." , reason ) ) ; text = context . getString ( R . string . error_unknown_error ) ; } } Log . w ( "Scanning" , text , exception ) ; Toast . makeText ( context , text , Toast . LENGTH_SHORT ) . show ( ) ; }
|
Show toast with error message appropriate to exception reason .
| 241
| 10
|
153,583
|
@ NonNull private Single < BluetoothGatt > getConnectedBluetoothGatt ( ) { // start connecting the BluetoothGatt // note: Due to different Android BLE stack implementations it is not certain whether `connectGatt()` or `BluetoothGattCallback` // will emit BluetoothGatt first return Single . create ( new SingleOnSubscribe < BluetoothGatt > ( ) { @ Override public void subscribe ( final SingleEmitter < BluetoothGatt > emitter ) throws Exception { final DisposableSingleObserver < BluetoothGatt > disposableGattObserver = getBluetoothGattAndChangeStatusToConnected ( ) // when the connected state will be emitted bluetoothGattProvider should contain valid Gatt . delaySubscription ( rxBleGattCallback . getOnConnectionStateChange ( ) . filter ( new Predicate < RxBleConnection . RxBleConnectionState > ( ) { @ Override public boolean test ( RxBleConnection . RxBleConnectionState rxBleConnectionState ) throws Exception { return rxBleConnectionState == CONNECTED ; } } ) ) // disconnect may happen even if the connection was not established yet . mergeWith ( rxBleGattCallback . < BluetoothGatt > observeDisconnect ( ) . firstOrError ( ) ) . firstOrError ( ) . subscribeWith ( disposableSingleObserverFromEmitter ( emitter ) ) ; emitter . setDisposable ( disposableGattObserver ) ; connectionStateChangedAction . onConnectionStateChange ( CONNECTING ) ; /* * Apparently the connection may be established fast enough to introduce a race condition so the subscription * must be established first before starting the connection. * https://github.com/Polidea/RxAndroidBle/issues/178 * */ final BluetoothGatt bluetoothGatt = connectionCompat . connectGatt ( bluetoothDevice , autoConnect , rxBleGattCallback . getBluetoothGattCallback ( ) ) ; /* * Update BluetoothGatt when connection is initiated. It is not certain * if this or RxBleGattCallback.onConnectionStateChange will be first. * */ bluetoothGattProvider . updateBluetoothGatt ( bluetoothGatt ) ; } } ) ; }
|
Emits BluetoothGatt and completes after connection is established .
| 469
| 12
|
153,584
|
private ObservableTransformer < RxBleInternalScanResult , RxBleInternalScanResult > repeatedWindowTransformer ( @ IntRange ( from = 0 , to = 4999 ) final int windowInMillis ) { final long repeatCycleTimeInMillis = TimeUnit . SECONDS . toMillis ( 5 ) ; final long delayToNextWindow = Math . max ( repeatCycleTimeInMillis - windowInMillis , 0 ) ; // to be sure that it won't be negative return new ObservableTransformer < RxBleInternalScanResult , RxBleInternalScanResult > ( ) { @ Override public Observable < RxBleInternalScanResult > apply ( final Observable < RxBleInternalScanResult > rxBleInternalScanResultObservable ) { return rxBleInternalScanResultObservable . take ( windowInMillis , TimeUnit . MILLISECONDS , scheduler ) . repeatWhen ( new Function < Observable < Object > , ObservableSource < ? > > ( ) { @ Override public ObservableSource < ? > apply ( Observable < Object > observable ) throws Exception { return observable . delay ( delayToNextWindow , TimeUnit . MILLISECONDS , scheduler ) ; } } ) ; } } ; }
|
A convenience method for running a scan for a period of time and repeat in five seconds intervals .
| 269
| 19
|
153,585
|
private boolean matchesServiceUuids ( ParcelUuid uuid , ParcelUuid parcelUuidMask , List < ParcelUuid > uuids ) { if ( uuid == null ) { return true ; } if ( uuids == null ) { return false ; } for ( ParcelUuid parcelUuid : uuids ) { UUID uuidMask = parcelUuidMask == null ? null : parcelUuidMask . getUuid ( ) ; if ( matchesServiceUuid ( uuid . getUuid ( ) , uuidMask , parcelUuid . getUuid ( ) ) ) { return true ; } } return false ; }
|
Check if the uuid pattern is contained in a list of parcel uuids .
| 143
| 17
|
153,586
|
private boolean isPermissionGranted ( String permission ) { if ( permission == null ) { throw new IllegalArgumentException ( "permission is null" ) ; } return context . checkPermission ( permission , android . os . Process . myPid ( ) , Process . myUid ( ) ) == PackageManager . PERMISSION_GRANTED ; }
|
Copied from android . support . v4 . content . ContextCompat for backwards compatibility
| 77
| 17
|
153,587
|
private static int parseServiceUuid ( byte [ ] scanRecord , int currentPos , int dataLength , int uuidLength , List < ParcelUuid > serviceUuids ) { while ( dataLength > 0 ) { byte [ ] uuidBytes = extractBytes ( scanRecord , currentPos , uuidLength ) ; serviceUuids . add ( parseUuidFrom ( uuidBytes ) ) ; dataLength -= uuidLength ; currentPos += uuidLength ; } return currentPos ; }
|
Parse service UUIDs .
| 107
| 7
|
153,588
|
private static byte [ ] extractBytes ( byte [ ] scanRecord , int start , int length ) { byte [ ] bytes = new byte [ length ] ; System . arraycopy ( scanRecord , start , bytes , 0 , length ) ; return bytes ; }
|
Helper method to extract bytes from byte array .
| 53
| 9
|
153,589
|
private static int unsignedBytesToInt ( byte b0 , byte b1 , byte b2 , byte b3 ) { return ( unsignedByteToInt ( b0 ) + ( unsignedByteToInt ( b1 ) << 8 ) ) + ( unsignedByteToInt ( b2 ) << 16 ) + ( unsignedByteToInt ( b3 ) << 24 ) ; }
|
Convert signed bytes to a 32 - bit unsigned int .
| 77
| 12
|
153,590
|
private static float bytesToFloat ( byte b0 , byte b1 ) { int mantissa = unsignedToSigned ( unsignedByteToInt ( b0 ) + ( ( unsignedByteToInt ( b1 ) & 0x0F ) << 8 ) , 12 ) ; int exponent = unsignedToSigned ( unsignedByteToInt ( b1 ) >> 4 , 4 ) ; return ( float ) ( mantissa * Math . pow ( 10 , exponent ) ) ; }
|
Convert signed bytes to a 16 - bit short float value .
| 98
| 13
|
153,591
|
private static float bytesToFloat ( byte b0 , byte b1 , byte b2 , byte b3 ) { int mantissa = unsignedToSigned ( unsignedByteToInt ( b0 ) + ( unsignedByteToInt ( b1 ) << 8 ) + ( unsignedByteToInt ( b2 ) << 16 ) , 24 ) ; return ( float ) ( mantissa * Math . pow ( 10 , b3 ) ) ; }
|
Convert signed bytes to a 32 - bit short float value .
| 91
| 13
|
153,592
|
private static int unsignedToSigned ( int unsigned , int size ) { if ( ( unsigned & ( 1 << size - 1 ) ) != 0 ) { unsigned = - 1 * ( ( 1 << size - 1 ) - ( unsigned & ( ( 1 << size - 1 ) - 1 ) ) ) ; } return unsigned ; }
|
Convert an unsigned integer value to a two s - complement encoded signed value .
| 68
| 16
|
153,593
|
@ NonNull private static < T > ObservableTransformer < T , T > repeatAfterCompleted ( ) { return observable -> observable . repeatWhen ( completedNotification -> completedNotification ) ; }
|
A convenience function creating a transformer that will repeat the source observable whenever it will complete
| 41
| 16
|
153,594
|
public static void updateLogOptions ( LogOptions logOptions ) { LoggerSetup oldLoggerSetup = RxBleLog . loggerSetup ; LoggerSetup newLoggerSetup = oldLoggerSetup . merge ( logOptions ) ; d ( "Received new options (%s) and merged with old setup: %s. New setup: %s" , logOptions , oldLoggerSetup , newLoggerSetup ) ; RxBleLog . loggerSetup = newLoggerSetup ; }
|
Method to update current logger setup with new LogOptions . Only set options will be updated . Options that were not set or set to null on the LogOptions will not update the current setup leaving the previous values untouched .
| 100
| 43
|
153,595
|
private void updateUI ( BluetoothGattCharacteristic characteristic ) { connectButton . setText ( characteristic != null ? R . string . disconnect : R . string . connect ) ; readButton . setEnabled ( hasProperty ( characteristic , BluetoothGattCharacteristic . PROPERTY_READ ) ) ; writeButton . setEnabled ( hasProperty ( characteristic , BluetoothGattCharacteristic . PROPERTY_WRITE ) ) ; notifyButton . setEnabled ( hasProperty ( characteristic , BluetoothGattCharacteristic . PROPERTY_NOTIFY ) ) ; }
|
This method updates the UI to a proper state .
| 115
| 10
|
153,596
|
@ NonNull private static Single < Boolean > checkPermissionUntilGranted ( final LocationServicesStatus locationServicesStatus , Scheduler timerScheduler ) { return Observable . interval ( 0 , 1L , TimeUnit . SECONDS , timerScheduler ) . takeWhile ( new Predicate < Long > ( ) { @ Override public boolean test ( Long timer ) { return ! locationServicesStatus . isLocationPermissionOk ( ) ; } } ) . count ( ) . map ( new Function < Long , Boolean > ( ) { @ Override public Boolean apply ( Long count ) { // if no elements were emitted then the permission was granted from the beginning return count == 0 ; } } ) ; }
|
Observable that emits true if the permission was granted on the time of subscription
| 148
| 16
|
153,597
|
@ Override @ TargetApi ( Build . VERSION_CODES . HONEYCOMB ) protected View onCreateView ( View parent , String name , AttributeSet attrs ) throws ClassNotFoundException { return mCalligraphyFactory . onViewCreated ( super . onCreateView ( parent , name , attrs ) , getContext ( ) , attrs ) ; }
|
The LayoutInflater onCreateView is the fourth port of call for LayoutInflation . BUT only for none CustomViews .
| 81
| 27
|
153,598
|
public static CharSequence applyTypefaceSpan ( CharSequence s , Typeface typeface ) { if ( s != null && s . length ( ) > 0 ) { if ( ! ( s instanceof Spannable ) ) { s = new SpannableString ( s ) ; } ( ( Spannable ) s ) . setSpan ( TypefaceUtils . getSpan ( typeface ) , 0 , s . length ( ) , Spanned . SPAN_EXCLUSIVE_EXCLUSIVE ) ; } return s ; }
|
Applies a custom typeface span to the text .
| 116
| 11
|
153,599
|
public static boolean applyFontToTextView ( final TextView textView , final Typeface typeface , boolean deferred ) { if ( textView == null || typeface == null ) return false ; textView . setPaintFlags ( textView . getPaintFlags ( ) | Paint . SUBPIXEL_TEXT_FLAG | Paint . ANTI_ALIAS_FLAG ) ; textView . setTypeface ( typeface ) ; if ( deferred ) { textView . setText ( applyTypefaceSpan ( textView . getText ( ) , typeface ) , TextView . BufferType . SPANNABLE ) ; textView . addTextChangedListener ( new TextWatcher ( ) { @ Override public void beforeTextChanged ( CharSequence s , int start , int count , int after ) { } @ Override public void onTextChanged ( CharSequence s , int start , int before , int count ) { } @ Override public void afterTextChanged ( Editable s ) { applyTypefaceSpan ( s , typeface ) ; } } ) ; } return true ; }
|
Applies a Typeface to a TextView if deferred its recommend you don t call this multiple times as this adds a TextWatcher .
| 232
| 28
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.