idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
156,300
public static Request signV4 ( Request request , String region , String accessKey , String secretKey ) throws NoSuchAlgorithmException , InvalidKeyException { String contentSha256 = request . header ( "x-amz-content-sha256" ) ; DateTime date = DateFormat . AMZ_DATE_FORMAT . parseDateTime ( request . header ( "x-amz-date" ) ) ; Signer signer = new Signer ( request , contentSha256 , date , region , accessKey , secretKey , null ) ; signer . setScope ( ) ; signer . setCanonicalRequest ( ) ; signer . setStringToSign ( ) ; signer . setSigningKey ( ) ; signer . setSignature ( ) ; signer . setAuthorization ( ) ; return request . newBuilder ( ) . header ( "Authorization" , signer . authorization ) . build ( ) ; }
Returns signed request object for given request region access key and secret key .
202
14
156,301
public static HttpUrl presignV4 ( Request request , String region , String accessKey , String secretKey , int expires ) throws NoSuchAlgorithmException , InvalidKeyException { String contentSha256 = "UNSIGNED-PAYLOAD" ; DateTime date = DateFormat . AMZ_DATE_FORMAT . parseDateTime ( request . header ( "x-amz-date" ) ) ; Signer signer = new Signer ( request , contentSha256 , date , region , accessKey , secretKey , null ) ; signer . setScope ( ) ; signer . setPresignCanonicalRequest ( expires ) ; signer . setStringToSign ( ) ; signer . setSigningKey ( ) ; signer . setSignature ( ) ; return signer . url . newBuilder ( ) . addEncodedQueryParameter ( S3Escaper . encode ( "X-Amz-Signature" ) , S3Escaper . encode ( signer . signature ) ) . build ( ) ; }
Returns pre - signed HttpUrl object for given request region access key secret key and expires time .
223
20
156,302
public static String credential ( String accessKey , DateTime date , String region ) { return accessKey + "/" + date . toString ( DateFormat . SIGNER_DATE_FORMAT ) + "/" + region + "/s3/aws4_request" ; }
Returns credential string of given access key date and region .
58
11
156,303
public static String postPresignV4 ( String stringToSign , String secretKey , DateTime date , String region ) throws NoSuchAlgorithmException , InvalidKeyException { Signer signer = new Signer ( null , null , date , region , null , secretKey , null ) ; signer . stringToSign = stringToSign ; signer . setSigningKey ( ) ; signer . setSignature ( ) ; return signer . signature ; }
Returns pre - signed post policy string for given stringToSign secret key date and region .
98
18
156,304
public static byte [ ] sumHmac ( byte [ ] key , byte [ ] data ) throws NoSuchAlgorithmException , InvalidKeyException { Mac mac = Mac . getInstance ( "HmacSHA256" ) ; mac . init ( new SecretKeySpec ( key , "HmacSHA256" ) ) ; mac . update ( data ) ; return mac . doFinal ( ) ; }
Returns HMacSHA256 digest of given key and data .
82
12
156,305
public void setContentType ( String contentType ) throws InvalidArgumentException { if ( Strings . isNullOrEmpty ( contentType ) ) { throw new InvalidArgumentException ( "empty content type" ) ; } this . contentType = contentType ; }
Sets content type .
55
5
156,306
public void setContentEncoding ( String contentEncoding ) throws InvalidArgumentException { if ( Strings . isNullOrEmpty ( contentEncoding ) ) { throw new InvalidArgumentException ( "empty content encoding" ) ; } this . contentEncoding = contentEncoding ; }
Sets content encoding .
60
5
156,307
public void setContentRange ( long startRange , long endRange ) throws InvalidArgumentException { if ( startRange <= 0 || endRange <= 0 ) { throw new InvalidArgumentException ( "negative start/end range" ) ; } if ( startRange > endRange ) { throw new InvalidArgumentException ( "start range is higher than end range" ) ; } this . contentRangeStart = startRange ; this . contentRangeEnd = endRange ; }
Sets content range .
97
5
156,308
public Map < String , String > formData ( String accessKey , String secretKey , String region ) throws NoSuchAlgorithmException , InvalidKeyException , InvalidArgumentException { if ( Strings . isNullOrEmpty ( region ) ) { throw new InvalidArgumentException ( "empty region" ) ; } return makeFormData ( accessKey , secretKey , region ) ; }
Returns form data of this post policy setting the provided region .
80
12
156,309
public void setModified ( DateTime date ) throws InvalidArgumentException { if ( date == null ) { throw new InvalidArgumentException ( "Date cannot be empty" ) ; } copyConditions . put ( "x-amz-copy-source-if-modified-since" , date . toString ( DateFormat . HTTP_HEADER_DATE_FORMAT ) ) ; }
Set modified condition copy object modified since given time .
84
10
156,310
public void setMatchETag ( String etag ) throws InvalidArgumentException { if ( etag == null ) { throw new InvalidArgumentException ( "ETag cannot be empty" ) ; } copyConditions . put ( "x-amz-copy-source-if-match" , etag ) ; }
Set matching ETag condition copy object which matches the following ETag .
68
14
156,311
public void setMatchETagNone ( String etag ) throws InvalidArgumentException { if ( etag == null ) { throw new InvalidArgumentException ( "ETag cannot be empty" ) ; } copyConditions . put ( "x-amz-copy-source-if-none-match" , etag ) ; }
Set matching ETag none condition copy object which does not match the following ETag .
71
17
156,312
public void parseXml ( Reader reader ) throws IOException , XmlPullParserException { this . xmlPullParser . setInput ( reader ) ; Xml . parseElement ( this . xmlPullParser , this , this . defaultNamespaceDictionary , null ) ; }
Parses content from given reader input stream .
57
10
156,313
protected void parseXml ( Reader reader , XmlNamespaceDictionary namespaceDictionary ) throws IOException , XmlPullParserException { this . xmlPullParser . setInput ( reader ) ; Xml . parseElement ( this . xmlPullParser , this , namespaceDictionary , null ) ; }
Parses content from given reader input stream and namespace dictionary .
63
13
156,314
public int read ( ) throws IOException { if ( this . bytesRead == this . length ) { // All chunks and final additional chunk are read. // This means we have reached EOF. return - 1 ; } try { // Read a chunk from given input stream when // it is first chunk or all bytes in chunk body is read if ( this . streamBytesRead == 0 || this . chunkPos == this . chunkBody . length ) { // Check if there are data available to read from given input stream. if ( this . streamBytesRead != this . streamSize ) { // Send all data chunks. int chunkSize = CHUNK_SIZE ; if ( this . streamBytesRead + chunkSize > this . streamSize ) { chunkSize = this . streamSize - this . streamBytesRead ; } if ( readChunk ( chunkSize ) < 0 ) { return - 1 ; } this . streamBytesRead += chunkSize ; } else { // Send final additional chunk to complete chunk upload. byte [ ] chunk = new byte [ 0 ] ; createChunkBody ( chunk ) ; } } this . bytesRead ++ ; // Value must be between 0 to 255. int value = this . chunkBody [ this . chunkPos ] & 0xFF ; this . chunkPos ++ ; return value ; } catch ( NoSuchAlgorithmException | InvalidKeyException | InsufficientDataException | InternalException e ) { throw new IOException ( e . getCause ( ) ) ; } }
read single byte from chunk body .
309
7
156,315
protected String adjustHost ( final String host ) { if ( host . startsWith ( HTTP_PROTOCOL ) ) { return host . replace ( HTTP_PROTOCOL , EMPTY_STRING ) ; } else if ( host . startsWith ( HTTPS_PROTOCOL ) ) { return host . replace ( HTTPS_PROTOCOL , EMPTY_STRING ) ; } return host ; }
adjusts host to needs of SocketInternetObservingStrategy
87
12
156,316
public static void checkNotNullOrEmpty ( String string , String message ) { if ( string == null || string . isEmpty ( ) ) { throw new IllegalArgumentException ( message ) ; } }
Validation method which checks if a string is null or empty
42
12
156,317
@ RequiresPermission ( Manifest . permission . ACCESS_NETWORK_STATE ) public static Observable < Connectivity > observeNetworkConnectivity ( final Context context ) { final NetworkObservingStrategy strategy ; if ( Preconditions . isAtLeastAndroidMarshmallow ( ) ) { strategy = new MarshmallowNetworkObservingStrategy ( ) ; } else if ( Preconditions . isAtLeastAndroidLollipop ( ) ) { strategy = new LollipopNetworkObservingStrategy ( ) ; } else { strategy = new PreLollipopNetworkObservingStrategy ( ) ; } return observeNetworkConnectivity ( context , strategy ) ; }
Observes network connectivity . Information about network state type and typeName are contained in observed Connectivity object .
137
21
156,318
@ RequiresPermission ( Manifest . permission . ACCESS_NETWORK_STATE ) public static Observable < Connectivity > observeNetworkConnectivity ( final Context context , final NetworkObservingStrategy strategy ) { Preconditions . checkNotNull ( context , "context == null" ) ; Preconditions . checkNotNull ( strategy , "strategy == null" ) ; return strategy . observeNetworkConnectivity ( context ) ; }
Observes network connectivity . Information about network state type and typeName are contained in observed Connectivity object . Moreover allows you to define NetworkObservingStrategy .
90
32
156,319
@ RequiresPermission ( Manifest . permission . INTERNET ) protected static Observable < Boolean > observeInternetConnectivity ( final InternetObservingStrategy strategy , final int initialIntervalInMs , final int intervalInMs , final String host , final int port , final int timeoutInMs , final int httpResponse , final ErrorHandler errorHandler ) { checkStrategyIsNotNull ( strategy ) ; return strategy . observeInternetConnectivity ( initialIntervalInMs , intervalInMs , host , port , timeoutInMs , httpResponse , errorHandler ) ; }
Observes connectivity with the Internet in a given time interval .
116
12
156,320
protected static int [ ] appendUnknownNetworkTypeToTypes ( int [ ] types ) { int i = 0 ; final int [ ] extendedTypes = new int [ types . length + 1 ] ; for ( int type : types ) { extendedTypes [ i ] = type ; i ++ ; } extendedTypes [ i ] = Connectivity . UNKNOWN_TYPE ; return extendedTypes ; }
Returns network types from the input with additional unknown type what helps during connections filtering when device is being disconnected from a specific network
79
24
156,321
private int getAndParseHexChar ( ) throws ParseException { final char hexChar = getc ( ) ; if ( hexChar >= ' ' && hexChar <= ' ' ) { return hexChar - ' ' ; } else if ( hexChar >= ' ' && hexChar <= ' ' ) { return hexChar - ' ' + 10 ; } else if ( hexChar >= ' ' && hexChar <= ' ' ) { return hexChar - ' ' + 10 ; } else { throw new ParseException ( this , "Invalid character in Unicode escape sequence: " + hexChar ) ; } }
Get and parse a hexadecimal digit character .
127
11
156,322
private Number parseNumber ( ) throws ParseException { final int startIdx = getPosition ( ) ; if ( peekMatches ( "Infinity" ) ) { advance ( 8 ) ; return Double . POSITIVE_INFINITY ; } else if ( peekMatches ( "-Infinity" ) ) { advance ( 9 ) ; return Double . NEGATIVE_INFINITY ; } else if ( peekMatches ( "NaN" ) ) { advance ( 3 ) ; return Double . NaN ; } if ( peek ( ) == ' ' ) { next ( ) ; } final int integralStartIdx = getPosition ( ) ; for ( ; hasMore ( ) ; next ( ) ) { final char c = peek ( ) ; if ( c < ' ' || c > ' ' ) { break ; } } final int integralEndIdx = getPosition ( ) ; final int numIntegralDigits = integralEndIdx - integralStartIdx ; if ( numIntegralDigits == 0 ) { throw new ParseException ( this , "Expected a number" ) ; } final boolean hasFractionalPart = peek ( ) == ' ' ; if ( hasFractionalPart ) { next ( ) ; for ( ; hasMore ( ) ; next ( ) ) { final char c = peek ( ) ; if ( c < ' ' || c > ' ' ) { break ; } } if ( getPosition ( ) - ( integralEndIdx + 1 ) == 0 ) { throw new ParseException ( this , "Expected digits after decimal point" ) ; } } final boolean hasExponentPart = peek ( ) == ' ' ; if ( hasExponentPart ) { next ( ) ; final char sign = peek ( ) ; if ( sign == ' ' || sign == ' ' ) { next ( ) ; } final int exponentStart = getPosition ( ) ; for ( ; hasMore ( ) ; next ( ) ) { final char c = peek ( ) ; if ( c < ' ' || c > ' ' ) { break ; } } if ( getPosition ( ) - exponentStart == 0 ) { throw new ParseException ( this , "Expected an exponent" ) ; } } final int endIdx = getPosition ( ) ; final String numberStr = getSubstring ( startIdx , endIdx ) ; if ( hasFractionalPart || hasExponentPart ) { return Double . valueOf ( numberStr ) ; } else if ( numIntegralDigits < 9 ) { return Integer . valueOf ( numberStr ) ; } else if ( numIntegralDigits == 9 ) { // For 9-digit numbers, could be int or long final long longVal = Long . parseLong ( numberStr ) ; if ( longVal >= Integer . MIN_VALUE && longVal <= Integer . MAX_VALUE ) { return ( int ) longVal ; } else { return longVal ; } } else { return Long . valueOf ( numberStr ) ; } }
Parses and returns Integer Long or Double type .
634
11
156,323
private JSONObject parseJSONObject ( ) throws ParseException { expect ( ' ' ) ; skipWhitespace ( ) ; if ( peek ( ) == ' ' ) { // Empty object next ( ) ; return new JSONObject ( Collections . < Entry < String , Object > > emptyList ( ) ) ; } final List < Entry < String , Object > > kvPairs = new ArrayList <> ( ) ; final JSONObject jsonObject = new JSONObject ( kvPairs ) ; boolean first = true ; while ( peek ( ) != ' ' ) { if ( first ) { first = false ; } else { expect ( ' ' ) ; } final CharSequence key = parseString ( ) ; if ( key == null ) { throw new ParseException ( this , "Object keys must be strings" ) ; } if ( peek ( ) != ' ' ) { return null ; } expect ( ' ' ) ; final Object value = parseJSON ( ) ; // Check for special object id key if ( key . equals ( JSONUtils . ID_KEY ) ) { if ( value == null ) { throw new ParseException ( this , "Got null value for \"" + JSONUtils . ID_KEY + "\" key" ) ; } jsonObject . objectId = ( CharSequence ) value ; } else { kvPairs . add ( new SimpleEntry <> ( key . toString ( ) , value ) ) ; } } expect ( ' ' ) ; return jsonObject ; }
Parse a JSON Object .
314
6
156,324
Object instantiateOrGet ( final ClassInfo annotationClassInfo , final String paramName ) { final boolean instantiate = annotationClassInfo != null ; if ( enumValue != null ) { return instantiate ? enumValue . loadClassAndReturnEnumValue ( ) : enumValue ; } else if ( classRef != null ) { return instantiate ? classRef . loadClass ( ) : classRef ; } else if ( annotationInfo != null ) { return instantiate ? annotationInfo . loadClassAndInstantiate ( ) : annotationInfo ; } else if ( stringValue != null ) { return stringValue ; } else if ( integerValue != null ) { return integerValue ; } else if ( longValue != null ) { return longValue ; } else if ( shortValue != null ) { return shortValue ; } else if ( booleanValue != null ) { return booleanValue ; } else if ( characterValue != null ) { return characterValue ; } else if ( floatValue != null ) { return floatValue ; } else if ( doubleValue != null ) { return doubleValue ; } else if ( byteValue != null ) { return byteValue ; } else if ( stringArrayValue != null ) { return stringArrayValue ; } else if ( intArrayValue != null ) { return intArrayValue ; } else if ( longArrayValue != null ) { return longArrayValue ; } else if ( shortArrayValue != null ) { return shortArrayValue ; } else if ( booleanArrayValue != null ) { return booleanArrayValue ; } else if ( charArrayValue != null ) { return charArrayValue ; } else if ( floatArrayValue != null ) { return floatArrayValue ; } else if ( doubleArrayValue != null ) { return doubleArrayValue ; } else if ( byteArrayValue != null ) { return byteArrayValue ; } else if ( objectArrayValue != null ) { // Get the element type of the array final Class < ? > eltClass = instantiate ? ( Class < ? > ) getArrayValueClassOrName ( annotationClassInfo , paramName , /* getClass = */ true ) : null ; // Allocate array as either a generic Object[] array, if the element type could not be determined, // or as an array of specific element type, if the element type was determined. final Object annotationValueObjectArray = eltClass == null ? new Object [ objectArrayValue . length ] : Array . newInstance ( eltClass , objectArrayValue . length ) ; // Fill the array instance. for ( int i = 0 ; i < objectArrayValue . length ; i ++ ) { if ( objectArrayValue [ i ] != null ) { // Get the element value (may also cause the element to be instantiated) final Object eltValue = objectArrayValue [ i ] . instantiateOrGet ( annotationClassInfo , paramName ) ; // Store the possibly-instantiated value in the array Array . set ( annotationValueObjectArray , i , eltValue ) ; } } return annotationValueObjectArray ; } else { return null ; } }
Instantiate or get the wrapped value .
642
8
156,325
private Object getArrayValueClassOrName ( final ClassInfo annotationClassInfo , final String paramName , final boolean getClass ) { // Find the method in the annotation class with the same name as the annotation parameter. final MethodInfoList annotationMethodList = annotationClassInfo . methodInfo == null ? null : annotationClassInfo . methodInfo . get ( paramName ) ; if ( annotationMethodList != null && annotationMethodList . size ( ) > 1 ) { // There should only be one method with a given name in an annotation throw new IllegalArgumentException ( "Duplicated annotation parameter method " + paramName + "() in annotation class " + annotationClassInfo . getName ( ) ) ; } else if ( annotationMethodList != null && annotationMethodList . size ( ) == 1 ) { // Get the result type of the method with the same name as the annotation parameter final TypeSignature annotationMethodResultTypeSig = annotationMethodList . get ( 0 ) . getTypeSignatureOrTypeDescriptor ( ) . getResultType ( ) ; // The result type has to be an array type if ( ! ( annotationMethodResultTypeSig instanceof ArrayTypeSignature ) ) { throw new IllegalArgumentException ( "Annotation parameter " + paramName + " in annotation class " + annotationClassInfo . getName ( ) + " holds an array, but does not have an array type signature" ) ; } final ArrayTypeSignature arrayTypeSig = ( ArrayTypeSignature ) annotationMethodResultTypeSig ; if ( arrayTypeSig . getNumDimensions ( ) != 1 ) { throw new IllegalArgumentException ( "Annotations only support 1-dimensional arrays" ) ; } final TypeSignature elementTypeSig = arrayTypeSig . getElementTypeSignature ( ) ; if ( elementTypeSig instanceof ClassRefTypeSignature ) { // Look up the name of the element type, for non-primitive arrays final ClassRefTypeSignature classRefTypeSignature = ( ClassRefTypeSignature ) elementTypeSig ; return getClass ? classRefTypeSignature . loadClass ( ) : classRefTypeSignature . getFullyQualifiedClassName ( ) ; } else if ( elementTypeSig instanceof BaseTypeSignature ) { // Look up the name of the primitive class, for primitive arrays final BaseTypeSignature baseTypeSignature = ( BaseTypeSignature ) elementTypeSig ; return getClass ? baseTypeSignature . getType ( ) : baseTypeSignature . getTypeStr ( ) ; } } else { // Could not find a method with this name -- this is an external class. // Find first non-null object in array, and use its type as the type of the array. for ( final ObjectTypedValueWrapper elt : objectArrayValue ) { if ( elt != null ) { return elt . integerValue != null ? ( getClass ? Integer . class : "int" ) : elt . longValue != null ? ( getClass ? Long . class : "long" ) : elt . shortValue != null ? ( getClass ? Short . class : "short" ) : elt . characterValue != null ? ( getClass ? Character . class : "char" ) : elt . byteValue != null ? ( getClass ? Byte . class : "byte" ) : elt . booleanValue != null ? ( getClass ? Boolean . class : "boolean" ) : elt . doubleValue != null ? ( getClass ? Double . class : "double" ) : elt . floatValue != null ? ( getClass ? Float . class : "float" ) : ( getClass ? null : "" ) ; } } } return getClass ? null : "" ; }
Get the element type of an array element .
794
9
156,326
public ClassGraph enableAllInfo ( ) { enableClassInfo ( ) ; enableFieldInfo ( ) ; enableMethodInfo ( ) ; enableAnnotationInfo ( ) ; enableStaticFinalFieldConstantInitializerValues ( ) ; ignoreClassVisibility ( ) ; ignoreFieldVisibility ( ) ; ignoreMethodVisibility ( ) ; return this ; }
Enables the scanning of all classes fields methods annotations and static final field constant initializer values and ignores all visibility modifiers so that both public and non - public classes fields and methods are all scanned .
71
39
156,327
public ClassGraph overrideClasspath ( final Iterable < ? > overrideClasspathElements ) { final String overrideClasspath = JarUtils . pathElementsToPathStr ( overrideClasspathElements ) ; if ( overrideClasspath . isEmpty ( ) ) { throw new IllegalArgumentException ( "Can't override classpath with an empty path" ) ; } overrideClasspath ( overrideClasspath ) ; return this ; }
Override the automatically - detected classpath with a custom path . Causes system ClassLoaders and the java . class . path system property to be ignored . Also causes modules not to be scanned .
90
38
156,328
public ClassGraph whitelistPackages ( final String ... packageNames ) { enableClassInfo ( ) ; for ( final String packageName : packageNames ) { final String packageNameNormalized = WhiteBlackList . normalizePackageOrClassName ( packageName ) ; if ( packageNameNormalized . startsWith ( "!" ) || packageNameNormalized . startsWith ( "-" ) ) { throw new IllegalArgumentException ( "This style of whitelisting/blacklisting is no longer supported: " + packageNameNormalized ) ; } // Whitelist package scanSpec . packageWhiteBlackList . addToWhitelist ( packageNameNormalized ) ; final String path = WhiteBlackList . packageNameToPath ( packageNameNormalized ) ; scanSpec . pathWhiteBlackList . addToWhitelist ( path + "/" ) ; if ( packageNameNormalized . isEmpty ( ) ) { scanSpec . pathWhiteBlackList . addToWhitelist ( "" ) ; } if ( ! packageNameNormalized . contains ( "*" ) ) { // Whitelist sub-packages if ( packageNameNormalized . isEmpty ( ) ) { scanSpec . packagePrefixWhiteBlackList . addToWhitelist ( "" ) ; scanSpec . pathPrefixWhiteBlackList . addToWhitelist ( "" ) ; } else { scanSpec . packagePrefixWhiteBlackList . addToWhitelist ( packageNameNormalized + "." ) ; scanSpec . pathPrefixWhiteBlackList . addToWhitelist ( path + "/" ) ; } } } return this ; }
Scan one or more specific packages and their sub - packages .
330
12
156,329
public ClassGraph whitelistPaths ( final String ... paths ) { for ( final String path : paths ) { final String pathNormalized = WhiteBlackList . normalizePath ( path ) ; // Whitelist path final String packageName = WhiteBlackList . pathToPackageName ( pathNormalized ) ; scanSpec . packageWhiteBlackList . addToWhitelist ( packageName ) ; scanSpec . pathWhiteBlackList . addToWhitelist ( pathNormalized + "/" ) ; if ( pathNormalized . isEmpty ( ) ) { scanSpec . pathWhiteBlackList . addToWhitelist ( "" ) ; } if ( ! pathNormalized . contains ( "*" ) ) { // Whitelist sub-directories / nested paths if ( pathNormalized . isEmpty ( ) ) { scanSpec . packagePrefixWhiteBlackList . addToWhitelist ( "" ) ; scanSpec . pathPrefixWhiteBlackList . addToWhitelist ( "" ) ; } else { scanSpec . packagePrefixWhiteBlackList . addToWhitelist ( packageName + "." ) ; scanSpec . pathPrefixWhiteBlackList . addToWhitelist ( pathNormalized + "/" ) ; } } } return this ; }
Scan one or more specific paths and their sub - directories or nested paths .
258
15
156,330
public ClassGraph whitelistPackagesNonRecursive ( final String ... packageNames ) { enableClassInfo ( ) ; for ( final String packageName : packageNames ) { final String packageNameNormalized = WhiteBlackList . normalizePackageOrClassName ( packageName ) ; if ( packageNameNormalized . contains ( "*" ) ) { throw new IllegalArgumentException ( "Cannot use a glob wildcard here: " + packageNameNormalized ) ; } // Whitelist package, but not sub-packages scanSpec . packageWhiteBlackList . addToWhitelist ( packageNameNormalized ) ; scanSpec . pathWhiteBlackList . addToWhitelist ( WhiteBlackList . packageNameToPath ( packageNameNormalized ) + "/" ) ; if ( packageNameNormalized . isEmpty ( ) ) { scanSpec . pathWhiteBlackList . addToWhitelist ( "" ) ; } } return this ; }
Scan one or more specific packages without recursively scanning sub - packages unless they are themselves whitelisted .
194
22
156,331
public ClassGraph whitelistPathsNonRecursive ( final String ... paths ) { for ( final String path : paths ) { if ( path . contains ( "*" ) ) { throw new IllegalArgumentException ( "Cannot use a glob wildcard here: " + path ) ; } final String pathNormalized = WhiteBlackList . normalizePath ( path ) ; // Whitelist path, but not sub-directories / nested paths scanSpec . packageWhiteBlackList . addToWhitelist ( WhiteBlackList . pathToPackageName ( pathNormalized ) ) ; scanSpec . pathWhiteBlackList . addToWhitelist ( pathNormalized + "/" ) ; if ( pathNormalized . isEmpty ( ) ) { scanSpec . pathWhiteBlackList . addToWhitelist ( "" ) ; } } return this ; }
Scan one or more specific paths without recursively scanning sub - directories or nested paths unless they are themselves whitelisted .
175
25
156,332
public ClassGraph blacklistPackages ( final String ... packageNames ) { enableClassInfo ( ) ; for ( final String packageName : packageNames ) { final String packageNameNormalized = WhiteBlackList . normalizePackageOrClassName ( packageName ) ; if ( packageNameNormalized . isEmpty ( ) ) { throw new IllegalArgumentException ( "Blacklisting the root package (\"\") will cause nothing to be scanned" ) ; } // Blacklisting always prevents further recursion, no need to blacklist sub-packages scanSpec . packageWhiteBlackList . addToBlacklist ( packageNameNormalized ) ; final String path = WhiteBlackList . packageNameToPath ( packageNameNormalized ) ; scanSpec . pathWhiteBlackList . addToBlacklist ( path + "/" ) ; if ( ! packageNameNormalized . contains ( "*" ) ) { // Blacklist sub-packages (zipfile entries can occur in any order) scanSpec . packagePrefixWhiteBlackList . addToBlacklist ( packageNameNormalized + "." ) ; scanSpec . pathPrefixWhiteBlackList . addToBlacklist ( path + "/" ) ; } } return this ; }
Prevent the scanning of one or more specific packages and their sub - packages .
251
16
156,333
public ClassGraph whitelistClasses ( final String ... classNames ) { enableClassInfo ( ) ; for ( final String className : classNames ) { if ( className . contains ( "*" ) ) { throw new IllegalArgumentException ( "Cannot use a glob wildcard here: " + className ) ; } final String classNameNormalized = WhiteBlackList . normalizePackageOrClassName ( className ) ; // Whitelist the class itself scanSpec . classWhiteBlackList . addToWhitelist ( classNameNormalized ) ; scanSpec . classfilePathWhiteBlackList . addToWhitelist ( WhiteBlackList . classNameToClassfilePath ( classNameNormalized ) ) ; final String packageName = PackageInfo . getParentPackageName ( classNameNormalized ) ; // Record the package containing the class, so we can recurse to this point even if the package // is not itself whitelisted scanSpec . classPackageWhiteBlackList . addToWhitelist ( packageName ) ; scanSpec . classPackagePathWhiteBlackList . addToWhitelist ( WhiteBlackList . packageNameToPath ( packageName ) + "/" ) ; } return this ; }
Scan one or more specific classes without scanning other classes in the same package unless the package is itself whitelisted .
250
23
156,334
public ClassGraph blacklistClasses ( final String ... classNames ) { enableClassInfo ( ) ; for ( final String className : classNames ) { if ( className . contains ( "*" ) ) { throw new IllegalArgumentException ( "Cannot use a glob wildcard here: " + className ) ; } final String classNameNormalized = WhiteBlackList . normalizePackageOrClassName ( className ) ; scanSpec . classWhiteBlackList . addToBlacklist ( classNameNormalized ) ; scanSpec . classfilePathWhiteBlackList . addToBlacklist ( WhiteBlackList . classNameToClassfilePath ( classNameNormalized ) ) ; } return this ; }
Specifically blacklist one or more specific classes preventing them from being scanned even if they are in a whitelisted package .
147
23
156,335
public ClassGraph whitelistJars ( final String ... jarLeafNames ) { for ( final String jarLeafName : jarLeafNames ) { final String leafName = JarUtils . leafName ( jarLeafName ) ; if ( ! leafName . equals ( jarLeafName ) ) { throw new IllegalArgumentException ( "Can only whitelist jars by leafname: " + jarLeafName ) ; } scanSpec . jarWhiteBlackList . addToWhitelist ( leafName ) ; } return this ; }
Whitelist one or more jars . This will cause only the whitelisted jars to be scanned .
113
20
156,336
public ClassGraph blacklistJars ( final String ... jarLeafNames ) { for ( final String jarLeafName : jarLeafNames ) { final String leafName = JarUtils . leafName ( jarLeafName ) ; if ( ! leafName . equals ( jarLeafName ) ) { throw new IllegalArgumentException ( "Can only blacklist jars by leafname: " + jarLeafName ) ; } scanSpec . jarWhiteBlackList . addToBlacklist ( leafName ) ; } return this ; }
Blacklist one or more jars preventing them from being scanned .
111
12
156,337
private void whitelistOrBlacklistLibOrExtJars ( final boolean whitelist , final String ... jarLeafNames ) { if ( jarLeafNames . length == 0 ) { // If no jar leafnames are given, whitelist or blacklist all lib or ext jars for ( final String libOrExtJar : SystemJarFinder . getJreLibOrExtJars ( ) ) { whitelistOrBlacklistLibOrExtJars ( whitelist , JarUtils . leafName ( libOrExtJar ) ) ; } } else { for ( final String jarLeafName : jarLeafNames ) { final String leafName = JarUtils . leafName ( jarLeafName ) ; if ( ! leafName . equals ( jarLeafName ) ) { throw new IllegalArgumentException ( "Can only " + ( whitelist ? "whitelist" : "blacklist" ) + " jars by leafname: " + jarLeafName ) ; } if ( jarLeafName . contains ( "*" ) ) { // Compare wildcarded pattern against all jars in lib and ext dirs final Pattern pattern = WhiteBlackList . globToPattern ( jarLeafName ) ; boolean found = false ; for ( final String libOrExtJarPath : SystemJarFinder . getJreLibOrExtJars ( ) ) { final String libOrExtJarLeafName = JarUtils . leafName ( libOrExtJarPath ) ; if ( pattern . matcher ( libOrExtJarLeafName ) . matches ( ) ) { // Check for "*" in filename to prevent infinite recursion (shouldn't happen) if ( ! libOrExtJarLeafName . contains ( "*" ) ) { whitelistOrBlacklistLibOrExtJars ( whitelist , libOrExtJarLeafName ) ; } found = true ; } } if ( ! found && topLevelLog != null ) { topLevelLog . log ( "Could not find lib or ext jar matching wildcard: " + jarLeafName ) ; } } else { // No wildcards, just whitelist or blacklist the named jar, if present boolean found = false ; for ( final String libOrExtJarPath : SystemJarFinder . getJreLibOrExtJars ( ) ) { final String libOrExtJarLeafName = JarUtils . leafName ( libOrExtJarPath ) ; if ( jarLeafName . equals ( libOrExtJarLeafName ) ) { if ( whitelist ) { scanSpec . libOrExtJarWhiteBlackList . addToWhitelist ( jarLeafName ) ; } else { scanSpec . libOrExtJarWhiteBlackList . addToBlacklist ( jarLeafName ) ; } if ( topLevelLog != null ) { topLevelLog . log ( ( whitelist ? "Whitelisting" : "Blacklisting" ) + " lib or ext jar: " + libOrExtJarPath ) ; } found = true ; break ; } } if ( ! found && topLevelLog != null ) { topLevelLog . log ( "Could not find lib or ext jar: " + jarLeafName ) ; } } } } }
Add lib or ext jars to whitelist or blacklist .
682
11
156,338
public ClassGraph whitelistModules ( final String ... moduleNames ) { for ( final String moduleName : moduleNames ) { scanSpec . moduleWhiteBlackList . addToWhitelist ( WhiteBlackList . normalizePackageOrClassName ( moduleName ) ) ; } return this ; }
Whitelist one or more modules to scan .
60
9
156,339
public ClassGraph blacklistModules ( final String ... moduleNames ) { for ( final String moduleName : moduleNames ) { scanSpec . moduleWhiteBlackList . addToBlacklist ( WhiteBlackList . normalizePackageOrClassName ( moduleName ) ) ; } return this ; }
Blacklist one or more modules preventing them from being scanned .
59
12
156,340
public ClassGraph whitelistClasspathElementsContainingResourcePath ( final String ... resourcePaths ) { for ( final String resourcePath : resourcePaths ) { final String resourcePathNormalized = WhiteBlackList . normalizePath ( resourcePath ) ; scanSpec . classpathElementResourcePathWhiteBlackList . addToWhitelist ( resourcePathNormalized ) ; } return this ; }
Whitelist classpath elements based on resource paths . Only classpath elements that contain resources with paths matching the whitelist will be scanned .
81
27
156,341
public ClassGraph blacklistClasspathElementsContainingResourcePath ( final String ... resourcePaths ) { for ( final String resourcePath : resourcePaths ) { final String resourcePathNormalized = WhiteBlackList . normalizePath ( resourcePath ) ; scanSpec . classpathElementResourcePathWhiteBlackList . addToBlacklist ( resourcePathNormalized ) ; } return this ; }
Blacklist classpath elements based on resource paths . Classpath elements that contain resources with paths matching the blacklist will not be scanned .
80
26
156,342
public T acquire ( ) throws E { final T instance ; final T recycledInstance = unusedInstances . poll ( ) ; if ( recycledInstance == null ) { // Allocate a new instance -- may throw an exception of type E final T newInstance = newInstance ( ) ; if ( newInstance == null ) { throw new NullPointerException ( "Failed to allocate a new recyclable instance" ) ; } instance = newInstance ; } else { // Reuse an unused instance instance = recycledInstance ; } usedInstances . add ( instance ) ; return instance ; }
Acquire on object instance of type T either by reusing a previously recycled instance if possible or if there are no currently - unused instances by allocating a new instance .
120
34
156,343
public List < URI > getClasspathURIs ( ) { if ( closed . get ( ) ) { throw new IllegalArgumentException ( "Cannot use a ScanResult after it has been closed" ) ; } final List < URI > classpathElementOrderURIs = new ArrayList <> ( ) ; for ( final ClasspathElement classpathElement : classpathOrder ) { try { final URI uri = classpathElement . getURI ( ) ; if ( uri != null ) { classpathElementOrderURIs . add ( uri ) ; } } catch ( final IllegalArgumentException e ) { // Skip null location URIs } } return classpathElementOrderURIs ; }
Returns an ordered list of unique classpath element and module URIs .
146
14
156,344
public ResourceList getAllResources ( ) { if ( allWhitelistedResourcesCached == null ) { // Index Resource objects by path final ResourceList whitelistedResourcesList = new ResourceList ( ) ; for ( final ClasspathElement classpathElt : classpathOrder ) { if ( classpathElt . whitelistedResources != null ) { whitelistedResourcesList . addAll ( classpathElt . whitelistedResources ) ; } } // Set atomically for thread safety allWhitelistedResourcesCached = whitelistedResourcesList ; } return allWhitelistedResourcesCached ; }
Get the list of all resources .
128
7
156,345
public ResourceList getResourcesWithPath ( final String resourcePath ) { if ( closed . get ( ) ) { throw new IllegalArgumentException ( "Cannot use a ScanResult after it has been closed" ) ; } final ResourceList allWhitelistedResources = getAllResources ( ) ; if ( allWhitelistedResources . isEmpty ( ) ) { return ResourceList . EMPTY_LIST ; } else { final String path = FileUtils . sanitizeEntryPath ( resourcePath , /* removeInitialSlash = */ true ) ; final ResourceList resourceList = getAllResourcesAsMap ( ) . get ( path ) ; return ( resourceList == null ? new ResourceList ( 1 ) : resourceList ) ; } }
Get the list of all resources found in whitelisted packages that have the given path relative to the package root of the classpath element . May match several resources up to one per classpath element .
153
40
156,346
public ResourceList getResourcesWithLeafName ( final String leafName ) { if ( closed . get ( ) ) { throw new IllegalArgumentException ( "Cannot use a ScanResult after it has been closed" ) ; } final ResourceList allWhitelistedResources = getAllResources ( ) ; if ( allWhitelistedResources . isEmpty ( ) ) { return ResourceList . EMPTY_LIST ; } else { final ResourceList filteredResources = new ResourceList ( ) ; for ( final Resource classpathResource : allWhitelistedResources ) { final String relativePath = classpathResource . getPath ( ) ; final int lastSlashIdx = relativePath . lastIndexOf ( ' ' ) ; if ( relativePath . substring ( lastSlashIdx + 1 ) . equals ( leafName ) ) { filteredResources . add ( classpathResource ) ; } } return filteredResources ; } }
Get the list of all resources found in whitelisted packages that have the requested leafname .
191
19
156,347
public ResourceList getResourcesWithExtension ( final String extension ) { if ( closed . get ( ) ) { throw new IllegalArgumentException ( "Cannot use a ScanResult after it has been closed" ) ; } final ResourceList allWhitelistedResources = getAllResources ( ) ; if ( allWhitelistedResources . isEmpty ( ) ) { return ResourceList . EMPTY_LIST ; } else { String bareExtension = extension ; while ( bareExtension . startsWith ( "." ) ) { bareExtension = bareExtension . substring ( 1 ) ; } final ResourceList filteredResources = new ResourceList ( ) ; for ( final Resource classpathResource : allWhitelistedResources ) { final String relativePath = classpathResource . getPath ( ) ; final int lastSlashIdx = relativePath . lastIndexOf ( ' ' ) ; final int lastDotIdx = relativePath . lastIndexOf ( ' ' ) ; if ( lastDotIdx > lastSlashIdx && relativePath . substring ( lastDotIdx + 1 ) . equalsIgnoreCase ( bareExtension ) ) { filteredResources . add ( classpathResource ) ; } } return filteredResources ; } }
Get the list of all resources found in whitelisted packages that have the requested filename extension .
260
19
156,348
public ResourceList getResourcesMatchingPattern ( final Pattern pattern ) { if ( closed . get ( ) ) { throw new IllegalArgumentException ( "Cannot use a ScanResult after it has been closed" ) ; } final ResourceList allWhitelistedResources = getAllResources ( ) ; if ( allWhitelistedResources . isEmpty ( ) ) { return ResourceList . EMPTY_LIST ; } else { final ResourceList filteredResources = new ResourceList ( ) ; for ( final Resource classpathResource : allWhitelistedResources ) { final String relativePath = classpathResource . getPath ( ) ; if ( pattern . matcher ( relativePath ) . matches ( ) ) { filteredResources . add ( classpathResource ) ; } } return filteredResources ; } }
Get the list of all resources found in whitelisted packages that have a path matching the requested pattern .
162
21
156,349
public ModuleInfoList getModuleInfo ( ) { if ( closed . get ( ) ) { throw new IllegalArgumentException ( "Cannot use a ScanResult after it has been closed" ) ; } if ( ! scanSpec . enableClassInfo ) { throw new IllegalArgumentException ( "Please call ClassGraph#enableClassInfo() before #scan()" ) ; } return new ModuleInfoList ( moduleNameToModuleInfo . values ( ) ) ; }
Get all modules found during the scan .
96
8
156,350
public PackageInfoList getPackageInfo ( ) { if ( closed . get ( ) ) { throw new IllegalArgumentException ( "Cannot use a ScanResult after it has been closed" ) ; } if ( ! scanSpec . enableClassInfo ) { throw new IllegalArgumentException ( "Please call ClassGraph#enableClassInfo() before #scan()" ) ; } return new PackageInfoList ( packageNameToPackageInfo . values ( ) ) ; }
Get all packages found during the scan .
96
8
156,351
public ClassInfoList getAllClasses ( ) { if ( closed . get ( ) ) { throw new IllegalArgumentException ( "Cannot use a ScanResult after it has been closed" ) ; } if ( ! scanSpec . enableClassInfo ) { throw new IllegalArgumentException ( "Please call ClassGraph#enableClassInfo() before #scan()" ) ; } return ClassInfo . getAllClasses ( classNameToClassInfo . values ( ) , scanSpec ) ; }
Get all classes interfaces and annotations found during the scan .
103
11
156,352
public ClassInfoList getSubclasses ( final String superclassName ) { if ( closed . get ( ) ) { throw new IllegalArgumentException ( "Cannot use a ScanResult after it has been closed" ) ; } if ( ! scanSpec . enableClassInfo ) { throw new IllegalArgumentException ( "Please call ClassGraph#enableClassInfo() before #scan()" ) ; } if ( superclassName . equals ( "java.lang.Object" ) ) { // Return all standard classes (interfaces don't extend Object) return getAllStandardClasses ( ) ; } else { final ClassInfo superclass = classNameToClassInfo . get ( superclassName ) ; return superclass == null ? ClassInfoList . EMPTY_LIST : superclass . getSubclasses ( ) ; } }
Get all subclasses of the named superclass .
171
10
156,353
public ClassInfoList getSuperclasses ( final String subclassName ) { if ( closed . get ( ) ) { throw new IllegalArgumentException ( "Cannot use a ScanResult after it has been closed" ) ; } if ( ! scanSpec . enableClassInfo ) { throw new IllegalArgumentException ( "Please call ClassGraph#enableClassInfo() before #scan()" ) ; } final ClassInfo subclass = classNameToClassInfo . get ( subclassName ) ; return subclass == null ? ClassInfoList . EMPTY_LIST : subclass . getSuperclasses ( ) ; }
Get superclasses of the named subclass .
122
8
156,354
public ClassInfoList getClassesWithMethodAnnotation ( final String methodAnnotationName ) { if ( closed . get ( ) ) { throw new IllegalArgumentException ( "Cannot use a ScanResult after it has been closed" ) ; } if ( ! scanSpec . enableClassInfo || ! scanSpec . enableMethodInfo || ! scanSpec . enableAnnotationInfo ) { throw new IllegalArgumentException ( "Please call ClassGraph#enableClassInfo(), #enableMethodInfo(), " + "and #enableAnnotationInfo() before #scan()" ) ; } final ClassInfo classInfo = classNameToClassInfo . get ( methodAnnotationName ) ; return classInfo == null ? ClassInfoList . EMPTY_LIST : classInfo . getClassesWithMethodAnnotation ( ) ; }
Get classes that have a method with an annotation of the named type .
169
14
156,355
public ClassInfoList getClassesWithMethodParameterAnnotation ( final String methodParameterAnnotationName ) { if ( closed . get ( ) ) { throw new IllegalArgumentException ( "Cannot use a ScanResult after it has been closed" ) ; } if ( ! scanSpec . enableClassInfo || ! scanSpec . enableMethodInfo || ! scanSpec . enableAnnotationInfo ) { throw new IllegalArgumentException ( "Please call ClassGraph#enableClassInfo(), #enableMethodInfo(), " + "and #enableAnnotationInfo() before #scan()" ) ; } final ClassInfo classInfo = classNameToClassInfo . get ( methodParameterAnnotationName ) ; return classInfo == null ? ClassInfoList . EMPTY_LIST : classInfo . getClassesWithMethodParameterAnnotation ( ) ; }
Get classes that have a method with a parameter that is annotated with an annotation of the named type .
173
21
156,356
public ClassInfoList getClassesWithFieldAnnotation ( final String fieldAnnotationName ) { if ( closed . get ( ) ) { throw new IllegalArgumentException ( "Cannot use a ScanResult after it has been closed" ) ; } if ( ! scanSpec . enableClassInfo || ! scanSpec . enableFieldInfo || ! scanSpec . enableAnnotationInfo ) { throw new IllegalArgumentException ( "Please call ClassGraph#enableClassInfo(), #enableFieldInfo(), " + "and #enableAnnotationInfo() before #scan()" ) ; } final ClassInfo classInfo = classNameToClassInfo . get ( fieldAnnotationName ) ; return classInfo == null ? ClassInfoList . EMPTY_LIST : classInfo . getClassesWithFieldAnnotation ( ) ; }
Get classes that have a field with an annotation of the named type .
169
14
156,357
public ClassInfoList getInterfaces ( final String className ) { if ( closed . get ( ) ) { throw new IllegalArgumentException ( "Cannot use a ScanResult after it has been closed" ) ; } if ( ! scanSpec . enableClassInfo ) { throw new IllegalArgumentException ( "Please call ClassGraph#enableClassInfo() before #scan()" ) ; } final ClassInfo classInfo = classNameToClassInfo . get ( className ) ; return classInfo == null ? ClassInfoList . EMPTY_LIST : classInfo . getInterfaces ( ) ; }
Get all interfaces implemented by the named class or by one of its superclasses if this is a standard class or the superinterfaces extended by this interface if this is an interface .
125
36
156,358
public ClassInfoList getClassesWithAnnotation ( final String annotationName ) { if ( closed . get ( ) ) { throw new IllegalArgumentException ( "Cannot use a ScanResult after it has been closed" ) ; } if ( ! scanSpec . enableClassInfo || ! scanSpec . enableAnnotationInfo ) { throw new IllegalArgumentException ( "Please call ClassGraph#enableClassInfo() and #enableAnnotationInfo() before #scan()" ) ; } final ClassInfo classInfo = classNameToClassInfo . get ( annotationName ) ; return classInfo == null ? ClassInfoList . EMPTY_LIST : classInfo . getClassesWithAnnotation ( ) ; }
Get classes with the named class annotation or meta - annotation .
147
12
156,359
public static ScanResult fromJSON ( final String json ) { final Matcher matcher = Pattern . compile ( "\\{[\\n\\r ]*\"format\"[ ]?:[ ]?\"([^\"]+)\"" ) . matcher ( json ) ; if ( ! matcher . find ( ) ) { throw new IllegalArgumentException ( "JSON is not in correct format" ) ; } if ( ! CURRENT_SERIALIZATION_FORMAT . equals ( matcher . group ( 1 ) ) ) { throw new IllegalArgumentException ( "JSON was serialized in a different format from the format used by the current version of " + "ClassGraph -- please serialize and deserialize your ScanResult using " + "the same version of ClassGraph" ) ; } // Deserialize the JSON final SerializationFormat deserialized = JSONDeserializer . deserializeObject ( SerializationFormat . class , json ) ; if ( ! deserialized . format . equals ( CURRENT_SERIALIZATION_FORMAT ) ) { // Probably the deserialization failed before now anyway, if fields have changed, etc. throw new IllegalArgumentException ( "JSON was serialized by newer version of ClassGraph" ) ; } // Perform a new "scan" with performScan set to false, which resolves all the ClasspathElement objects // and scans classpath element paths (needed for classloading), but does not scan the actual classfiles final ClassGraph classGraph = new ClassGraph ( ) ; classGraph . scanSpec = deserialized . scanSpec ; classGraph . scanSpec . performScan = false ; if ( classGraph . scanSpec . overrideClasspath == null ) { // Use the same classpath as before, if classpath was not overridden classGraph . overrideClasspath ( deserialized . classpath ) ; } final ScanResult scanResult = classGraph . scan ( ) ; scanResult . rawClasspathEltOrderStrs = deserialized . classpath ; scanResult . scanSpec . performScan = true ; // Set the fields related to ClassInfo in the new ScanResult, based on the deserialized JSON scanResult . scanSpec = deserialized . scanSpec ; scanResult . classNameToClassInfo = new HashMap <> ( ) ; if ( deserialized . classInfo != null ) { for ( final ClassInfo ci : deserialized . classInfo ) { scanResult . classNameToClassInfo . put ( ci . getName ( ) , ci ) ; ci . setScanResult ( scanResult ) ; } } scanResult . moduleNameToModuleInfo = new HashMap <> ( ) ; if ( deserialized . moduleInfo != null ) { for ( final ModuleInfo mi : deserialized . moduleInfo ) { scanResult . moduleNameToModuleInfo . put ( mi . getName ( ) , mi ) ; } } scanResult . packageNameToPackageInfo = new HashMap <> ( ) ; if ( deserialized . packageInfo != null ) { for ( final PackageInfo pi : deserialized . packageInfo ) { scanResult . packageNameToPackageInfo . put ( pi . getName ( ) , pi ) ; } } // Index Resource and ClassInfo objects scanResult . indexResourcesAndClassInfo ( ) ; scanResult . isObtainedFromDeserialization = true ; return scanResult ; }
Deserialize a ScanResult from previously - serialized JSON .
718
13
156,360
public String toJSON ( final int indentWidth ) { if ( closed . get ( ) ) { throw new IllegalArgumentException ( "Cannot use a ScanResult after it has been closed" ) ; } if ( ! scanSpec . enableClassInfo ) { throw new IllegalArgumentException ( "Please call ClassGraph#enableClassInfo() before #scan()" ) ; } final List < ClassInfo > allClassInfo = new ArrayList <> ( classNameToClassInfo . values ( ) ) ; CollectionUtils . sortIfNotEmpty ( allClassInfo ) ; final List < PackageInfo > allPackageInfo = new ArrayList <> ( packageNameToPackageInfo . values ( ) ) ; CollectionUtils . sortIfNotEmpty ( allPackageInfo ) ; final List < ModuleInfo > allModuleInfo = new ArrayList <> ( moduleNameToModuleInfo . values ( ) ) ; CollectionUtils . sortIfNotEmpty ( allModuleInfo ) ; return JSONSerializer . serializeObject ( new SerializationFormat ( CURRENT_SERIALIZATION_FORMAT , scanSpec , allClassInfo , allPackageInfo , allModuleInfo , rawClasspathEltOrderStrs ) , indentWidth , false ) ; }
Serialize a ScanResult to JSON .
259
8
156,361
Type resolveTypeVariables ( final Type type ) { if ( type instanceof Class < ? > ) { // Arrays and non-generic classes have no type variables return type ; } else if ( type instanceof ParameterizedType ) { // Recursively resolve parameterized types final ParameterizedType parameterizedType = ( ParameterizedType ) type ; final Type [ ] typeArgs = parameterizedType . getActualTypeArguments ( ) ; Type [ ] typeArgsResolved = null ; for ( int i = 0 ; i < typeArgs . length ; i ++ ) { // Recursively revolve each parameter of the type final Type typeArgResolved = resolveTypeVariables ( typeArgs [ i ] ) ; // Only compare typeArgs to typeArgResolved until the first difference is found if ( typeArgsResolved == null ) { if ( ! typeArgResolved . equals ( typeArgs [ i ] ) ) { // After the first difference is found, lazily allocate typeArgsResolved typeArgsResolved = new Type [ typeArgs . length ] ; // Go back and copy all the previous args System . arraycopy ( typeArgs , 0 , typeArgsResolved , 0 , i ) ; // Insert the first different arg typeArgsResolved [ i ] = typeArgResolved ; } } else { // After the first difference is found, keep copying the resolved args into the array typeArgsResolved [ i ] = typeArgResolved ; } } if ( typeArgsResolved == null ) { // There were no type parameters to resolve return type ; } else { // Return new ParameterizedType that wraps the resolved type args return new ParameterizedTypeImpl ( ( Class < ? > ) parameterizedType . getRawType ( ) , typeArgsResolved , parameterizedType . getOwnerType ( ) ) ; } } else if ( type instanceof TypeVariable < ? > ) { // Look up concrete type for type variable final TypeVariable < ? > typeVariable = ( TypeVariable < ? > ) type ; for ( int i = 0 ; i < typeVariables . length ; i ++ ) { if ( typeVariables [ i ] . getName ( ) . equals ( typeVariable . getName ( ) ) ) { return resolvedTypeArguments [ i ] ; } } // Could not resolve type variable return type ; } else if ( type instanceof GenericArrayType ) { // Count the array dimensions, and resolve the innermost type of the array int numArrayDims = 0 ; Type t = type ; while ( t instanceof GenericArrayType ) { numArrayDims ++ ; t = ( ( GenericArrayType ) t ) . getGenericComponentType ( ) ; } final Type innermostType = t ; final Type innermostTypeResolved = resolveTypeVariables ( innermostType ) ; if ( ! ( innermostTypeResolved instanceof Class < ? > ) ) { throw new IllegalArgumentException ( "Could not resolve generic array type " + type ) ; } final Class < ? > innermostTypeResolvedClass = ( Class < ? > ) innermostTypeResolved ; // Build an array to hold the size of each dimension, filled with zeroes final int [ ] dims = ( int [ ] ) Array . newInstance ( int . class , numArrayDims ) ; // Build a zero-sized array of the required number of dimensions, using the resolved innermost class final Object arrayInstance = Array . newInstance ( innermostTypeResolvedClass , dims ) ; // Get the class of this array instance -- this is the resolved array type return arrayInstance . getClass ( ) ; } else if ( type instanceof WildcardType ) { // TODO: Support WildcardType throw ClassGraphException . newClassGraphException ( "WildcardType not yet supported: " + type ) ; } else { throw ClassGraphException . newClassGraphException ( "Got unexpected type: " + type ) ; } }
Resolve the type variables in a type using a type variable resolution list producing a resolved type .
832
19
156,362
private static void assignObjectIds ( final Object jsonVal , final Map < ReferenceEqualityKey < Object > , JSONObject > objToJSONVal , final ClassFieldCache classFieldCache , final Map < ReferenceEqualityKey < JSONReference > , CharSequence > jsonReferenceToId , final AtomicInteger objId , final boolean onlySerializePublicFields ) { if ( jsonVal instanceof JSONObject ) { for ( final Entry < String , Object > item : ( ( JSONObject ) jsonVal ) . items ) { assignObjectIds ( item . getValue ( ) , objToJSONVal , classFieldCache , jsonReferenceToId , objId , onlySerializePublicFields ) ; } } else if ( jsonVal instanceof JSONArray ) { for ( final Object item : ( ( JSONArray ) jsonVal ) . items ) { assignObjectIds ( item , objToJSONVal , classFieldCache , jsonReferenceToId , objId , onlySerializePublicFields ) ; } } else if ( jsonVal instanceof JSONReference ) { // Get the referenced (non-JSON) object final Object refdObj = ( ( JSONReference ) jsonVal ) . idObject ; if ( refdObj == null ) { // Should not happen throw ClassGraphException . newClassGraphException ( "Internal inconsistency" ) ; } // Look up the JSON object corresponding to the referenced object final ReferenceEqualityKey < Object > refdObjKey = new ReferenceEqualityKey <> ( refdObj ) ; final JSONObject refdJsonVal = objToJSONVal . get ( refdObjKey ) ; if ( refdJsonVal == null ) { // Should not happen throw ClassGraphException . newClassGraphException ( "Internal inconsistency" ) ; } // See if the JSON object has an @Id field // (for serialization, typeResolutions can be null) final Field annotatedField = classFieldCache . get ( refdObj . getClass ( ) ) . idField ; CharSequence idStr = null ; if ( annotatedField != null ) { // Get id value from field annotated with @Id try { final Object idObject = annotatedField . get ( refdObj ) ; if ( idObject != null ) { idStr = idObject . toString ( ) ; refdJsonVal . objectId = idStr ; } } catch ( IllegalArgumentException | IllegalAccessException e ) { // Should not happen throw new IllegalArgumentException ( "Could not access @Id-annotated field " + annotatedField , e ) ; } } if ( idStr == null ) { // No @Id field, or field value is null -- check if ref'd JSON Object already has an id if ( refdJsonVal . objectId == null ) { // Ref'd JSON object doesn't have an id yet -- generate unique integer id idStr = JSONUtils . ID_PREFIX + objId . getAndIncrement ( ) + JSONUtils . ID_SUFFIX ; refdJsonVal . objectId = idStr ; } else { idStr = refdJsonVal . objectId ; } } // Link both the JSON representation ob the object to the id jsonReferenceToId . put ( new ReferenceEqualityKey <> ( ( JSONReference ) jsonVal ) , idStr ) ; } // if (jsonVal == null) then do nothing }
Create a unique id for each referenced JSON object .
719
10
156,363
static void jsonValToJSONString ( final Object jsonVal , final Map < ReferenceEqualityKey < JSONReference > , CharSequence > jsonReferenceToId , final boolean includeNullValuedFields , final int depth , final int indentWidth , final StringBuilder buf ) { if ( jsonVal == null ) { buf . append ( "null" ) ; } else if ( jsonVal instanceof JSONObject ) { // Serialize JSONObject to string ( ( JSONObject ) jsonVal ) . toJSONString ( jsonReferenceToId , includeNullValuedFields , depth , indentWidth , buf ) ; } else if ( jsonVal instanceof JSONArray ) { // Serialize JSONArray to string ( ( JSONArray ) jsonVal ) . toJSONString ( jsonReferenceToId , includeNullValuedFields , depth , indentWidth , buf ) ; } else if ( jsonVal instanceof JSONReference ) { // Serialize JSONReference to string final Object referencedObjectId = jsonReferenceToId . get ( new ReferenceEqualityKey <> ( ( JSONReference ) jsonVal ) ) ; jsonValToJSONString ( referencedObjectId , jsonReferenceToId , includeNullValuedFields , depth , indentWidth , buf ) ; } else if ( jsonVal instanceof CharSequence || jsonVal instanceof Character || jsonVal . getClass ( ) . isEnum ( ) ) { // Serialize String, Character or enum val to quoted/escaped string buf . append ( ' ' ) ; JSONUtils . escapeJSONString ( jsonVal . toString ( ) , buf ) ; buf . append ( ' ' ) ; } else { // Serialize a numeric or Boolean type (Integer, Long, Short, Float, Double, Boolean, Byte) to string // (doesn't need quoting or escaping) buf . append ( jsonVal . toString ( ) ) ; } }
Serialize a JSON object array or value .
393
9
156,364
private void scheduleScanningIfExternalClass ( final String className , final String relationship ) { // Don't scan Object if ( className != null && ! className . equals ( "java.lang.Object" ) // Only schedule each external class once for scanning, across all threads && classNamesScheduledForScanning . add ( className ) ) { // Search for the named class' classfile among classpath elements, in classpath order (this is O(N) // for each class, but there shouldn't be too many cases of extending scanning upwards) final String classfilePath = JarUtils . classNameToClassfilePath ( className ) ; // First check current classpath element, to avoid iterating through other classpath elements Resource classResource = classpathElement . getResource ( classfilePath ) ; ClasspathElement foundInClasspathElt = null ; if ( classResource != null ) { // Found the classfile in the current classpath element foundInClasspathElt = classpathElement ; } else { // Didn't find the classfile in the current classpath element -- iterate through other elements for ( final ClasspathElement classpathOrderElt : classpathOrder ) { if ( classpathOrderElt != classpathElement ) { classResource = classpathOrderElt . getResource ( classfilePath ) ; if ( classResource != null ) { foundInClasspathElt = classpathOrderElt ; break ; } } } } if ( classResource != null ) { // Found class resource if ( log != null ) { log . log ( "Scheduling external class for scanning: " + relationship + " " + className + ( foundInClasspathElt == classpathElement ? "" : " -- found in classpath element " + foundInClasspathElt ) ) ; } if ( additionalWorkUnits == null ) { additionalWorkUnits = new ArrayList <> ( ) ; } // Schedule class resource for scanning additionalWorkUnits . add ( new ClassfileScanWorkUnit ( foundInClasspathElt , classResource , /* isExternalClass = */ true ) ) ; } else { if ( log != null ) { log . log ( "External " + relationship + " " + className + " was not found in " + "non-blacklisted packages -- cannot extend scanning to this class" ) ; } } } }
Extend scanning to a superclass interface or annotation .
502
11
156,365
private void extendScanningUpwards ( ) { // Check superclass if ( superclassName != null ) { scheduleScanningIfExternalClass ( superclassName , "superclass" ) ; } // Check implemented interfaces if ( implementedInterfaces != null ) { for ( final String interfaceName : implementedInterfaces ) { scheduleScanningIfExternalClass ( interfaceName , "interface" ) ; } } // Check class annotations if ( classAnnotations != null ) { for ( final AnnotationInfo annotationInfo : classAnnotations ) { scheduleScanningIfExternalClass ( annotationInfo . getName ( ) , "class annotation" ) ; } } // Check method annotations and method parameter annotations if ( methodInfoList != null ) { for ( final MethodInfo methodInfo : methodInfoList ) { if ( methodInfo . annotationInfo != null ) { for ( final AnnotationInfo methodAnnotationInfo : methodInfo . annotationInfo ) { scheduleScanningIfExternalClass ( methodAnnotationInfo . getName ( ) , "method annotation" ) ; } if ( methodInfo . parameterAnnotationInfo != null && methodInfo . parameterAnnotationInfo . length > 0 ) { for ( final AnnotationInfo [ ] paramAnns : methodInfo . parameterAnnotationInfo ) { if ( paramAnns != null && paramAnns . length > 0 ) { for ( final AnnotationInfo paramAnn : paramAnns ) { scheduleScanningIfExternalClass ( paramAnn . getName ( ) , "method parameter annotation" ) ; } } } } } } } // Check field annotations if ( fieldInfoList != null ) { for ( final FieldInfo fieldInfo : fieldInfoList ) { if ( fieldInfo . annotationInfo != null ) { for ( final AnnotationInfo fieldAnnotationInfo : fieldInfo . annotationInfo ) { scheduleScanningIfExternalClass ( fieldAnnotationInfo . getName ( ) , "field annotation" ) ; } } } } }
Check if scanning needs to be extended upwards to an external superclass interface or annotation .
405
17
156,366
private String intern ( final String str ) { if ( str == null ) { return null ; } final String interned = stringInternMap . putIfAbsent ( str , str ) ; if ( interned != null ) { return interned ; } return str ; }
Intern a string .
56
4
156,367
private int getConstantPoolStringOffset ( final int cpIdx , final int subFieldIdx ) throws ClassfileFormatException { if ( cpIdx < 1 || cpIdx >= cpCount ) { throw new ClassfileFormatException ( "Constant pool index " + cpIdx + ", should be in range [1, " + ( cpCount - 1 ) + "] -- cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues" ) ; } final int t = entryTag [ cpIdx ] ; if ( ( t != 12 && subFieldIdx != 0 ) || ( t == 12 && subFieldIdx != 0 && subFieldIdx != 1 ) ) { throw new ClassfileFormatException ( "Bad subfield index " + subFieldIdx + " for tag " + t + ", cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues" ) ; } int cpIdxToUse ; if ( t == 0 ) { // Assume this means null return 0 ; } else if ( t == 1 ) { // CONSTANT_Utf8 cpIdxToUse = cpIdx ; } else if ( t == 7 || t == 8 || t == 19 ) { // t == 7 => CONSTANT_Class, e.g. "[[I", "[Ljava/lang/Thread;"; t == 8 => CONSTANT_String; // t == 19 => CONSTANT_Method_Info final int indirIdx = indirectStringRefs [ cpIdx ] ; if ( indirIdx == - 1 ) { // Should not happen throw new ClassfileFormatException ( "Bad string indirection index, cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues" ) ; } if ( indirIdx == 0 ) { // I assume this represents a null string, since the zeroeth entry is unused return 0 ; } cpIdxToUse = indirIdx ; } else if ( t == 12 ) { // CONSTANT_NameAndType_info final int compoundIndirIdx = indirectStringRefs [ cpIdx ] ; if ( compoundIndirIdx == - 1 ) { // Should not happen throw new ClassfileFormatException ( "Bad string indirection index, cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues" ) ; } final int indirIdx = ( subFieldIdx == 0 ? ( compoundIndirIdx >> 16 ) : compoundIndirIdx ) & 0xffff ; if ( indirIdx == 0 ) { // Should not happen throw new ClassfileFormatException ( "Bad string indirection index, cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues" ) ; } cpIdxToUse = indirIdx ; } else { throw new ClassfileFormatException ( "Wrong tag number " + t + " at constant pool index " + cpIdx + ", " + "cannot continue reading class. Please report this at " + "https://github.com/classgraph/classgraph/issues" ) ; } if ( cpIdxToUse < 1 || cpIdxToUse >= cpCount ) { throw new ClassfileFormatException ( "Constant pool index " + cpIdx + ", should be in range [1, " + ( cpCount - 1 ) + "] -- cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues" ) ; } return entryOffset [ cpIdxToUse ] ; }
Get the byte offset within the buffer of a string from the constant pool or 0 for a null string .
811
21
156,368
private String getConstantPoolString ( final int cpIdx , final int subFieldIdx ) throws ClassfileFormatException , IOException { final int constantPoolStringOffset = getConstantPoolStringOffset ( cpIdx , subFieldIdx ) ; return constantPoolStringOffset == 0 ? null : intern ( inputStreamOrByteBuffer . readString ( constantPoolStringOffset , /* replaceSlashWithDot = */ false , /* stripLSemicolon = */ false ) ) ; }
Get a string from the constant pool .
103
8
156,369
private byte getConstantPoolStringFirstByte ( final int cpIdx ) throws ClassfileFormatException , IOException { final int constantPoolStringOffset = getConstantPoolStringOffset ( cpIdx , /* subFieldIdx = */ 0 ) ; if ( constantPoolStringOffset == 0 ) { return ' ' ; } final int utfLen = inputStreamOrByteBuffer . readUnsignedShort ( constantPoolStringOffset ) ; if ( utfLen == 0 ) { return ' ' ; } return inputStreamOrByteBuffer . buf [ constantPoolStringOffset + 2 ] ; }
Get the first UTF8 byte of a string in the constant pool or \ 0 if the string is null or empty .
123
24
156,370
private boolean constantPoolStringEquals ( final int cpIdx , final String asciiString ) throws ClassfileFormatException , IOException { final int strOffset = getConstantPoolStringOffset ( cpIdx , /* subFieldIdx = */ 0 ) ; if ( strOffset == 0 ) { return asciiString == null ; } else if ( asciiString == null ) { return false ; } final int strLen = inputStreamOrByteBuffer . readUnsignedShort ( strOffset ) ; final int otherLen = asciiString . length ( ) ; if ( strLen != otherLen ) { return false ; } final int strStart = strOffset + 2 ; for ( int i = 0 ; i < strLen ; i ++ ) { if ( ( char ) ( inputStreamOrByteBuffer . buf [ strStart + i ] & 0xff ) != asciiString . charAt ( i ) ) { return false ; } } return true ; }
Compare a string in the constant pool with a given ASCII string without constructing the constant pool String object .
206
20
156,371
private int cpReadUnsignedShort ( final int cpIdx ) throws IOException { if ( cpIdx < 1 || cpIdx >= cpCount ) { throw new ClassfileFormatException ( "Constant pool index " + cpIdx + ", should be in range [1, " + ( cpCount - 1 ) + "] -- cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues" ) ; } return inputStreamOrByteBuffer . readUnsignedShort ( entryOffset [ cpIdx ] ) ; }
Read an unsigned short from the constant pool .
123
9
156,372
private int cpReadInt ( final int cpIdx ) throws IOException { if ( cpIdx < 1 || cpIdx >= cpCount ) { throw new ClassfileFormatException ( "Constant pool index " + cpIdx + ", should be in range [1, " + ( cpCount - 1 ) + "] -- cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues" ) ; } return inputStreamOrByteBuffer . readInt ( entryOffset [ cpIdx ] ) ; }
Read an int from the constant pool .
119
8
156,373
private long cpReadLong ( final int cpIdx ) throws IOException { if ( cpIdx < 1 || cpIdx >= cpCount ) { throw new ClassfileFormatException ( "Constant pool index " + cpIdx + ", should be in range [1, " + ( cpCount - 1 ) + "] -- cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues" ) ; } return inputStreamOrByteBuffer . readLong ( entryOffset [ cpIdx ] ) ; }
Read a long from the constant pool .
119
8
156,374
private Object getFieldConstantPoolValue ( final int tag , final char fieldTypeDescriptorFirstChar , final int cpIdx ) throws ClassfileFormatException , IOException { switch ( tag ) { case 1 : // Modified UTF8 case 7 : // Class -- N.B. Unused? Class references do not seem to actually be stored as constant initalizers case 8 : // String // Forward or backward indirect reference to a modified UTF8 entry return getConstantPoolString ( cpIdx ) ; case 3 : // int, short, char, byte, boolean are all represented by Constant_INTEGER final int intVal = cpReadInt ( cpIdx ) ; switch ( fieldTypeDescriptorFirstChar ) { case ' ' : return intVal ; case ' ' : return ( short ) intVal ; case ' ' : return ( char ) intVal ; case ' ' : return ( byte ) intVal ; case ' ' : return intVal != 0 ; default : // Fall through } throw new ClassfileFormatException ( "Unknown Constant_INTEGER type " + fieldTypeDescriptorFirstChar + ", " + "cannot continue reading class. Please report this at " + "https://github.com/classgraph/classgraph/issues" ) ; case 4 : // float return Float . intBitsToFloat ( cpReadInt ( cpIdx ) ) ; case 5 : // long return cpReadLong ( cpIdx ) ; case 6 : // double return Double . longBitsToDouble ( cpReadLong ( cpIdx ) ) ; default : // ClassGraph doesn't expect other types // (N.B. in particular, enum values are not stored in the constant pool, so don't need to be handled) throw new ClassfileFormatException ( "Unknown constant pool tag " + tag + ", " + "cannot continue reading class. Please report this at " + "https://github.com/classgraph/classgraph/issues" ) ; } }
Get a field constant from the constant pool .
419
9
156,375
private AnnotationInfo readAnnotation ( ) throws IOException { // Lcom/xyz/Annotation; -> Lcom.xyz.Annotation; final String annotationClassName = getConstantPoolClassDescriptor ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) ; final int numElementValuePairs = inputStreamOrByteBuffer . readUnsignedShort ( ) ; AnnotationParameterValueList paramVals = null ; if ( numElementValuePairs > 0 ) { paramVals = new AnnotationParameterValueList ( numElementValuePairs ) ; for ( int i = 0 ; i < numElementValuePairs ; i ++ ) { final String paramName = getConstantPoolString ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) ; final Object paramValue = readAnnotationElementValue ( ) ; paramVals . add ( new AnnotationParameterValue ( paramName , paramValue ) ) ; } } return new AnnotationInfo ( annotationClassName , paramVals ) ; }
Read annotation entry from classfile .
218
7
156,376
private Object readAnnotationElementValue ( ) throws IOException { final int tag = ( char ) inputStreamOrByteBuffer . readUnsignedByte ( ) ; switch ( tag ) { case ' ' : return ( byte ) cpReadInt ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) ; case ' ' : return ( char ) cpReadInt ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) ; case ' ' : return Double . longBitsToDouble ( cpReadLong ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) ) ; case ' ' : return Float . intBitsToFloat ( cpReadInt ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) ) ; case ' ' : return cpReadInt ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) ; case ' ' : return cpReadLong ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) ; case ' ' : return ( short ) cpReadUnsignedShort ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) ; case ' ' : return cpReadInt ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) != 0 ; case ' ' : return getConstantPoolString ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) ; case ' ' : { // Return type is AnnotationEnumVal. final String annotationClassName = getConstantPoolClassDescriptor ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) ; final String annotationConstName = getConstantPoolString ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) ; return new AnnotationEnumValue ( annotationClassName , annotationConstName ) ; } case ' ' : // Return type is AnnotationClassRef (for class references in annotations) final String classRefTypeDescriptor = getConstantPoolString ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) ; return new AnnotationClassRef ( classRefTypeDescriptor ) ; case ' ' : // Complex (nested) annotation. Return type is AnnotationInfo. return readAnnotation ( ) ; case ' ' : // Return type is Object[] (of nested annotation element values) final int count = inputStreamOrByteBuffer . readUnsignedShort ( ) ; final Object [ ] arr = new Object [ count ] ; for ( int i = 0 ; i < count ; ++ i ) { // Nested annotation element value arr [ i ] = readAnnotationElementValue ( ) ; } return arr ; default : throw new ClassfileFormatException ( "Class " + className + " has unknown annotation element type tag '" + ( ( char ) tag ) + "': element size unknown, cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues" ) ; } }
Read annotation element value from classfile .
608
8
156,377
private void readBasicClassInfo ( ) throws IOException , ClassfileFormatException , SkipClassException { // Modifier flags classModifiers = inputStreamOrByteBuffer . readUnsignedShort ( ) ; isInterface = ( classModifiers & 0x0200 ) != 0 ; isAnnotation = ( classModifiers & 0x2000 ) != 0 ; // The fully-qualified class name of this class, with slashes replaced with dots final String classNamePath = getConstantPoolString ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) ; if ( classNamePath == null ) { throw new ClassfileFormatException ( "Class name is null" ) ; } className = classNamePath . replace ( ' ' , ' ' ) ; if ( "java.lang.Object" . equals ( className ) ) { // Don't process java.lang.Object (it has a null superclass), though you can still search for classes // that are subclasses of java.lang.Object (as an external class). throw new SkipClassException ( "No need to scan java.lang.Object" ) ; } // Check class visibility modifiers final boolean isModule = ( classModifiers & 0x8000 ) != 0 ; // Equivalently filename is "module-info.class" final boolean isPackage = relativePath . regionMatches ( relativePath . lastIndexOf ( ' ' ) + 1 , "package-info.class" , 0 , 18 ) ; if ( ! scanSpec . ignoreClassVisibility && ! Modifier . isPublic ( classModifiers ) && ! isModule && ! isPackage ) { throw new SkipClassException ( "Class is not public, and ignoreClassVisibility() was not called" ) ; } // Make sure classname matches relative path if ( ! relativePath . endsWith ( ".class" ) ) { // Should not happen throw new SkipClassException ( "Classfile filename " + relativePath + " does not end in \".class\"" ) ; } final int len = classNamePath . length ( ) ; if ( relativePath . length ( ) != len + 6 || ! classNamePath . regionMatches ( 0 , relativePath , 0 , len ) ) { throw new SkipClassException ( "Relative path " + relativePath + " does not match class name " + className ) ; } // Superclass name, with slashes replaced with dots final int superclassNameCpIdx = inputStreamOrByteBuffer . readUnsignedShort ( ) ; if ( superclassNameCpIdx > 0 ) { superclassName = getConstantPoolClassName ( superclassNameCpIdx ) ; } }
Read basic class information .
562
5
156,378
private void readInterfaces ( ) throws IOException { // Interfaces final int interfaceCount = inputStreamOrByteBuffer . readUnsignedShort ( ) ; for ( int i = 0 ; i < interfaceCount ; i ++ ) { final String interfaceName = getConstantPoolClassName ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) ; if ( implementedInterfaces == null ) { implementedInterfaces = new ArrayList <> ( ) ; } implementedInterfaces . add ( interfaceName ) ; } }
Read the class interfaces .
108
5
156,379
private void appendPath ( final StringBuilder buf ) { if ( parentZipFileSlice != null ) { parentZipFileSlice . appendPath ( buf ) ; if ( buf . length ( ) > 0 ) { buf . append ( "!/" ) ; } } buf . append ( pathWithinParentZipFileSlice ) ; }
Recursively append the path in top down ancestral order .
70
12
156,380
public void filterClasspathElements ( final ClasspathElementFilter classpathElementFilter ) { if ( this . classpathElementFilters == null ) { this . classpathElementFilters = new ArrayList <> ( 2 ) ; } this . classpathElementFilters . add ( classpathElementFilter ) ; }
Add a classpath element filter . The provided ClasspathElementFilter should return true if the path string passed to it is a path you want to scan .
67
31
156,381
private static boolean isModuleLayer ( final Object moduleLayer ) { if ( moduleLayer == null ) { throw new IllegalArgumentException ( "ModuleLayer references must not be null" ) ; } for ( Class < ? > currClass = moduleLayer . getClass ( ) ; currClass != null ; currClass = currClass . getSuperclass ( ) ) { if ( currClass . getName ( ) . equals ( "java.lang.ModuleLayer" ) ) { return true ; } } return false ; }
Return true if the argument is a ModuleLayer or a subclass of ModuleLayer .
112
16
156,382
public void addModuleLayer ( final Object moduleLayer ) { if ( ! isModuleLayer ( moduleLayer ) ) { throw new IllegalArgumentException ( "moduleLayer must be of type java.lang.ModuleLayer" ) ; } if ( this . addedModuleLayers == null ) { this . addedModuleLayers = new ArrayList <> ( ) ; } this . addedModuleLayers . add ( moduleLayer ) ; }
Add a ModuleLayer to the list of ModuleLayers to scan . Use this method if you define your own ModuleLayer but the scanning code is not running within that custom ModuleLayer .
90
37
156,383
public void log ( final LogNode log ) { if ( log != null ) { final LogNode scanSpecLog = log . log ( "ScanSpec:" ) ; for ( final Field field : ScanSpec . class . getDeclaredFields ( ) ) { try { scanSpecLog . log ( field . getName ( ) + ": " + field . get ( this ) ) ; } catch ( final ReflectiveOperationException e ) { // Ignore } } } }
Write to log .
98
4
156,384
private static Class < ? > [ ] getCallStackViaSecurityManager ( final LogNode log ) { try { return new CallerResolver ( ) . getClassContext ( ) ; } catch ( final SecurityException e ) { // Creating a SecurityManager can fail if the current SecurityManager does not allow // RuntimePermission("createSecurityManager") if ( log != null ) { log . log ( "Exception while trying to obtain call stack via SecurityManager" , e ) ; } return null ; } }
Get the call stack via the SecurityManager API .
103
10
156,385
static Class < ? > [ ] getClassContext ( final LogNode log ) { // For JRE 9+, use StackWalker to get call stack. // N.B. need to work around StackWalker bug fixed in JDK 13, and backported to 12.0.2 and 11.0.4 // (probably introduced in JDK 9, when StackWalker was introduced): // https://github.com/classgraph/classgraph/issues/341 // https://bugs.openjdk.java.net/browse/JDK-8210457 Class < ? > [ ] stackClasses = null ; if ( ( VersionFinder . JAVA_MAJOR_VERSION == 11 && ( VersionFinder . JAVA_MINOR_VERSION >= 1 || VersionFinder . JAVA_SUB_VERSION >= 4 ) && ! VersionFinder . JAVA_IS_EA_VERSION ) || ( VersionFinder . JAVA_MAJOR_VERSION == 12 && ( VersionFinder . JAVA_MINOR_VERSION >= 1 || VersionFinder . JAVA_SUB_VERSION >= 2 ) && ! VersionFinder . JAVA_IS_EA_VERSION ) || ( VersionFinder . JAVA_MAJOR_VERSION == 13 && ! VersionFinder . JAVA_IS_EA_VERSION ) || VersionFinder . JAVA_MAJOR_VERSION > 13 ) { // Invoke with doPrivileged -- see: // http://mail.openjdk.java.net/pipermail/jigsaw-dev/2018-October/013974.html stackClasses = AccessController . doPrivileged ( new PrivilegedAction < Class < ? > [ ] > ( ) { @ Override public Class < ? > [ ] run ( ) { return getCallStackViaStackWalker ( ) ; } } ) ; } // For JRE 7 and 8, use SecurityManager to get call stack if ( stackClasses == null || stackClasses . length == 0 ) { stackClasses = AccessController . doPrivileged ( new PrivilegedAction < Class < ? > [ ] > ( ) { @ Override public Class < ? > [ ] run ( ) { return getCallStackViaSecurityManager ( log ) ; } } ) ; } // As a fallback, use getStackTrace() to try to get the call stack if ( stackClasses == null || stackClasses . length == 0 ) { StackTraceElement [ ] stackTrace = Thread . currentThread ( ) . getStackTrace ( ) ; if ( stackTrace == null || stackTrace . length == 0 ) { try { throw new Exception ( ) ; } catch ( final Exception e ) { stackTrace = e . getStackTrace ( ) ; } } final List < Class < ? > > stackClassesList = new ArrayList <> ( ) ; for ( final StackTraceElement elt : stackTrace ) { try { stackClassesList . add ( Class . forName ( elt . getClassName ( ) ) ) ; } catch ( final ClassNotFoundException | LinkageError ignored ) { // Ignored } } if ( ! stackClassesList . isEmpty ( ) ) { stackClasses = stackClassesList . toArray ( new Class < ? > [ 0 ] ) ; } else { // Last-ditch effort -- include just this class in the call stack stackClasses = new Class < ? > [ ] { CallStackReader . class } ; } } return stackClasses ; }
Get the class context .
765
5
156,386
public List < V > values ( ) throws InterruptedException { final List < V > entries = new ArrayList <> ( map . size ( ) ) ; for ( final Entry < K , SingletonHolder < V > > ent : map . entrySet ( ) ) { final V entryValue = ent . getValue ( ) . get ( ) ; if ( entryValue != null ) { entries . add ( entryValue ) ; } } return entries ; }
Get all valid singleton values in the map .
96
10
156,387
protected void checkResourcePathWhiteBlackList ( final String relativePath , final LogNode log ) { // Whitelist/blacklist classpath elements based on file resource paths if ( ! scanSpec . classpathElementResourcePathWhiteBlackList . whitelistAndBlacklistAreEmpty ( ) ) { if ( scanSpec . classpathElementResourcePathWhiteBlackList . isBlacklisted ( relativePath ) ) { if ( log != null ) { log . log ( "Reached blacklisted classpath element resource path, stopping scanning: " + relativePath ) ; } skipClasspathElement = true ; return ; } if ( scanSpec . classpathElementResourcePathWhiteBlackList . isSpecificallyWhitelisted ( relativePath ) ) { if ( log != null ) { log . log ( "Reached specifically whitelisted classpath element resource path: " + relativePath ) ; } containsSpecificallyWhitelistedClasspathElementResourcePath = true ; } } }
Check relativePath against classpathElementResourcePathWhiteBlackList .
197
13
156,388
protected void addWhitelistedResource ( final Resource resource , final ScanSpecPathMatch parentMatchStatus , final LogNode log ) { final String path = resource . getPath ( ) ; final boolean isClassFile = FileUtils . isClassfile ( path ) ; boolean isWhitelisted = false ; if ( isClassFile ) { // Check classfile scanning is enabled, and classfile is not specifically blacklisted if ( scanSpec . enableClassInfo && ! scanSpec . classfilePathWhiteBlackList . isBlacklisted ( path ) ) { // ClassInfo is enabled, and found a whitelisted classfile whitelistedClassfileResources . add ( resource ) ; isWhitelisted = true ; } } else { // Resources are always whitelisted if found in whitelisted directories isWhitelisted = true ; } // Add resource to whitelistedResources, whether for a classfile or non-classfile resource whitelistedResources . add ( resource ) ; // Write to log if enabled, and as long as classfile scanning is not disabled, and this is not // a blacklisted classfile if ( log != null && isWhitelisted ) { final String type = isClassFile ? "classfile" : "resource" ; String logStr ; switch ( parentMatchStatus ) { case HAS_WHITELISTED_PATH_PREFIX : logStr = "Found " + type + " within subpackage of whitelisted package: " ; break ; case AT_WHITELISTED_PATH : logStr = "Found " + type + " within whitelisted package: " ; break ; case AT_WHITELISTED_CLASS_PACKAGE : logStr = "Found specifically-whitelisted " + type + ": " ; break ; default : logStr = "Found whitelisted " + type + ": " ; break ; } // Precede log entry sort key with "0:file:" so that file entries come before dir entries for // ClasspathElementDir classpath elements resource . scanLog = log . log ( "0:" + path , logStr + path + ( path . equals ( resource . getPathRelativeToClasspathElement ( ) ) ? "" : " ; full path: " + resource . getPathRelativeToClasspathElement ( ) ) ) ; } }
Add a resource discovered during the scan .
493
8
156,389
public URI getLocation ( ) { if ( locationURI == null ) { locationURI = moduleRef != null ? moduleRef . getLocation ( ) : null ; if ( locationURI == null ) { locationURI = classpathElement . getURI ( ) ; } } return locationURI ; }
The module location or null for modules whose location is unknown .
60
12
156,390
void addAnnotations ( final AnnotationInfoList moduleAnnotations ) { // Currently only class annotations are used in the module-info.class file if ( moduleAnnotations != null && ! moduleAnnotations . isEmpty ( ) ) { if ( this . annotationInfo == null ) { this . annotationInfo = new AnnotationInfoList ( moduleAnnotations ) ; } else { this . annotationInfo . addAll ( moduleAnnotations ) ; } } }
Add annotations found in a module descriptor classfile .
94
10
156,391
static TypeVariableSignature parse ( final Parser parser , final String definingClassName ) throws ParseException { final char peek = parser . peek ( ) ; if ( peek == ' ' ) { parser . next ( ) ; if ( ! TypeUtils . getIdentifierToken ( parser ) ) { throw new ParseException ( parser , "Could not parse type variable signature" ) ; } parser . expect ( ' ' ) ; final TypeVariableSignature typeVariableSignature = new TypeVariableSignature ( parser . currToken ( ) , definingClassName ) ; // Save type variable signatures in the parser state, so method and class type signatures can link // to type signatures @ SuppressWarnings ( "unchecked" ) List < TypeVariableSignature > typeVariableSignatures = ( List < TypeVariableSignature > ) parser . getState ( ) ; if ( typeVariableSignatures == null ) { parser . setState ( typeVariableSignatures = new ArrayList <> ( ) ) ; } typeVariableSignatures . add ( typeVariableSignature ) ; return typeVariableSignature ; } else { return null ; } }
Parse a TypeVariableSignature .
238
8
156,392
private void logJavaInfo ( ) { log ( "Operating system: " + VersionFinder . getProperty ( "os.name" ) + " " + VersionFinder . getProperty ( "os.version" ) + " " + VersionFinder . getProperty ( "os.arch" ) ) ; log ( "Java version: " + VersionFinder . getProperty ( "java.version" ) + " / " + VersionFinder . getProperty ( "java.runtime.version" ) + " (" + VersionFinder . getProperty ( "java.vendor" ) + ")" ) ; log ( "Java home: " + VersionFinder . getProperty ( "java.home" ) ) ; final String jreRtJarPath = SystemJarFinder . getJreRtJarPath ( ) ; if ( jreRtJarPath != null ) { log ( "JRE rt.jar:" ) . log ( jreRtJarPath ) ; } }
Log the Java version and the JRE paths that were found .
213
13
156,393
private void appendLine ( final String timeStampStr , final int indentLevel , final String line , final StringBuilder buf ) { buf . append ( timeStampStr ) ; buf . append ( ' ' ) ; buf . append ( ClassGraph . class . getSimpleName ( ) ) ; buf . append ( ' ' ) ; final int numDashes = 2 * ( indentLevel - 1 ) ; for ( int i = 0 ; i < numDashes ; i ++ ) { buf . append ( ' ' ) ; } if ( numDashes > 0 ) { buf . append ( ' ' ) ; } buf . append ( line ) ; buf . append ( ' ' ) ; }
Append a line to the log output indenting this log entry according to tree structure .
144
18
156,394
private LogNode addChild ( final String sortKey , final String msg , final long elapsedTimeNanos , final Throwable exception ) { final String newSortKey = sortKeyPrefix + "\t" + ( sortKey == null ? "" : sortKey ) + "\t" + String . format ( "%09d" , sortKeyUniqueSuffix . getAndIncrement ( ) ) ; final LogNode newChild = new LogNode ( newSortKey , msg , elapsedTimeNanos , exception ) ; newChild . parent = this ; // Make the sort key unique, so that log entries are not clobbered if keys are reused; increment unique // suffix with each new log entry, so that ties are broken in chronological order. children . put ( newSortKey , newChild ) ; return newChild ; }
Add a child log node .
171
6
156,395
private LogNode addChild ( final String sortKey , final String msg , final long elapsedTimeNanos ) { return addChild ( sortKey , msg , elapsedTimeNanos , null ) ; }
Add a child log node for a message .
41
9
156,396
public LogNode log ( final String sortKey , final String msg , final long elapsedTimeNanos ) { return addChild ( sortKey , msg , elapsedTimeNanos ) ; }
Add a log entry with sort key for deterministic ordering .
38
12
156,397
public LogNode log ( final String msg , final Throwable e ) { return addChild ( "" , msg , - 1L ) . addChild ( e ) ; }
Add a log entry .
35
5
156,398
public LogNode log ( final Collection < String > msgs ) { LogNode last = null ; for ( final String m : msgs ) { last = log ( m ) ; } return last ; }
Add a series of log entries . Returns the last LogNode created .
42
14
156,399
public void flush ( ) { if ( parent != null ) { throw new IllegalArgumentException ( "Only flush the toplevel LogNode" ) ; } if ( ! children . isEmpty ( ) ) { final String logOutput = this . toString ( ) ; this . children . clear ( ) ; log . info ( logOutput ) ; } }
Flush out the log to stderr and clear the log contents . Only call this on the toplevel log node when threads do not have access to references of internal log nodes so that they cannot add more log entries inside the tree otherwise log entries may be lost .
74
55