idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
32,900 | private void putObject ( String bucketName , String objectName , Long size , Object data , Map < String , String > headerMap , ServerSideEncryption sse ) throws InvalidBucketNameException , NoSuchAlgorithmException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException , InvalidArgumentException , InsufficientDataException { boolean unknownSize = false ; if ( headerMap . get ( "Content-Type" ) == null ) { headerMap . put ( "Content-Type" , "application/octet-stream" ) ; } if ( size == null ) { unknownSize = true ; size = MAX_OBJECT_SIZE ; } if ( size <= MIN_MULTIPART_SIZE ) { if ( sse != null ) { sse . marshal ( headerMap ) ; } putObject ( bucketName , objectName , size . intValue ( ) , data , null , 0 , headerMap ) ; return ; } int [ ] rv = calculateMultipartSize ( size ) ; int partSize = rv [ 0 ] ; int partCount = rv [ 1 ] ; int lastPartSize = rv [ 2 ] ; Part [ ] totalParts = new Part [ partCount ] ; if ( sse != null ) { sse . marshal ( headerMap ) ; } String uploadId = initMultipartUpload ( bucketName , objectName , headerMap ) ; try { int expectedReadSize = partSize ; for ( int partNumber = 1 ; partNumber <= partCount ; partNumber ++ ) { if ( partNumber == partCount ) { expectedReadSize = lastPartSize ; } int availableSize = 0 ; if ( unknownSize ) { availableSize = getAvailableSize ( data , expectedReadSize + 1 ) ; if ( availableSize <= expectedReadSize ) { if ( partNumber == 1 ) { putObject ( bucketName , objectName , availableSize , data , null , 0 , headerMap ) ; return ; } expectedReadSize = availableSize ; partCount = partNumber ; } } Map < String , String > encryptionHeaders = new HashMap < > ( ) ; if ( sse != null && sse . getType ( ) == ServerSideEncryption . Type . SSE_C ) { sse . marshal ( encryptionHeaders ) ; } String etag = putObject ( bucketName , objectName , expectedReadSize , data , uploadId , partNumber , encryptionHeaders ) ; totalParts [ partNumber - 1 ] = new Part ( partNumber , etag ) ; } completeMultipart ( bucketName , objectName , uploadId , totalParts ) ; } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { abortMultipartUpload ( bucketName , objectName , uploadId ) ; throw e ; } } | Executes put object . If size of object data is < = 5MiB single put object is used else multipart put object is used . |
32,901 | public String getBucketPolicy ( String bucketName ) throws InvalidBucketNameException , InvalidObjectPrefixException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException , BucketPolicyTooLargeException { Map < String , String > queryParamMap = new HashMap < > ( ) ; queryParamMap . put ( "policy" , "" ) ; HttpResponse response = null ; byte [ ] buf = new byte [ MAX_BUCKET_POLICY_SIZE ] ; int bytesRead = 0 ; try { response = executeGet ( bucketName , null , null , queryParamMap ) ; bytesRead = response . body ( ) . byteStream ( ) . read ( buf , 0 , MAX_BUCKET_POLICY_SIZE ) ; if ( bytesRead < 0 ) { throw new IOException ( "reached EOF when reading bucket policy" ) ; } if ( bytesRead == MAX_BUCKET_POLICY_SIZE ) { int byteRead = 0 ; while ( byteRead == 0 ) { byteRead = response . body ( ) . byteStream ( ) . read ( ) ; if ( byteRead < 0 ) { break ; } else if ( byteRead > 0 ) { throw new BucketPolicyTooLargeException ( bucketName ) ; } } } } catch ( ErrorResponseException e ) { if ( e . errorResponse ( ) . errorCode ( ) != ErrorCode . NO_SUCH_BUCKET_POLICY ) { throw e ; } } finally { if ( response != null && response . body ( ) != null ) { response . body ( ) . close ( ) ; } } return new String ( buf , 0 , bytesRead , StandardCharsets . UTF_8 ) ; } | Get JSON string of bucket policy of the given bucket . |
32,902 | public void setBucketPolicy ( String bucketName , String policy ) throws InvalidBucketNameException , InvalidObjectPrefixException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException { Map < String , String > headerMap = new HashMap < > ( ) ; headerMap . put ( "Content-Type" , "application/json" ) ; Map < String , String > queryParamMap = new HashMap < > ( ) ; queryParamMap . put ( "policy" , "" ) ; HttpResponse response = executePut ( bucketName , null , headerMap , queryParamMap , policy , 0 ) ; response . body ( ) . close ( ) ; } | Set JSON string of policy on given bucket . |
32,903 | public void deleteBucketLifeCycle ( String bucketName ) throws InvalidBucketNameException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException { Map < String , String > queryParamMap = new HashMap < > ( ) ; queryParamMap . put ( "lifecycle" , "" ) ; HttpResponse response = executeDelete ( bucketName , "" , queryParamMap ) ; response . body ( ) . close ( ) ; } | Delete the LifeCycle of bucket . |
32,904 | public String getBucketLifeCycle ( String bucketName ) throws InvalidBucketNameException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException { Map < String , String > queryParamMap = new HashMap < > ( ) ; queryParamMap . put ( "lifecycle" , "" ) ; HttpResponse response = null ; String bodyContent = "" ; Scanner scanner = null ; try { response = executeGet ( bucketName , "" , null , queryParamMap ) ; scanner = new Scanner ( response . body ( ) . charStream ( ) ) ; scanner . useDelimiter ( "\\A" ) ; if ( scanner . hasNext ( ) ) { bodyContent = scanner . next ( ) ; } } catch ( ErrorResponseException e ) { if ( e . errorResponse ( ) . errorCode ( ) != ErrorCode . NO_SUCH_LIFECYCLE_CONFIGURATION ) { throw e ; } } finally { if ( response != null && response . body ( ) != null ) { response . body ( ) . close ( ) ; } if ( scanner != null ) { scanner . close ( ) ; } } return bodyContent ; } | Get bucket life cycle configuration . |
32,905 | public NotificationConfiguration getBucketNotification ( String bucketName ) throws InvalidBucketNameException , InvalidObjectPrefixException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException { Map < String , String > queryParamMap = new HashMap < > ( ) ; queryParamMap . put ( "notification" , "" ) ; HttpResponse response = executeGet ( bucketName , null , null , queryParamMap ) ; NotificationConfiguration result = new NotificationConfiguration ( ) ; try { result . parseXml ( response . body ( ) . charStream ( ) ) ; } finally { response . body ( ) . close ( ) ; } return result ; } | Get bucket notification configuration |
32,906 | public void setBucketNotification ( String bucketName , NotificationConfiguration notificationConfiguration ) throws InvalidBucketNameException , InvalidObjectPrefixException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException { Map < String , String > queryParamMap = new HashMap < > ( ) ; queryParamMap . put ( "notification" , "" ) ; HttpResponse response = executePut ( bucketName , null , null , queryParamMap , notificationConfiguration . toString ( ) , 0 ) ; response . body ( ) . close ( ) ; } | Set bucket notification configuration |
32,907 | public void removeAllBucketNotification ( String bucketName ) throws InvalidBucketNameException , InvalidObjectPrefixException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException { NotificationConfiguration notificationConfiguration = new NotificationConfiguration ( ) ; setBucketNotification ( bucketName , notificationConfiguration ) ; } | Remove all bucket notification . |
32,908 | public Iterable < Result < Upload > > listIncompleteUploads ( String bucketName , String prefix ) throws XmlPullParserException { return listIncompleteUploads ( bucketName , prefix , true , true ) ; } | Lists incomplete uploads of objects in given bucket and prefix . |
32,909 | private String initMultipartUpload ( String bucketName , String objectName , Map < String , String > headerMap ) throws InvalidBucketNameException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException { if ( headerMap . get ( "Content-Type" ) == null ) { headerMap . put ( "Content-Type" , "application/octet-stream" ) ; } Map < String , String > queryParamMap = new HashMap < > ( ) ; queryParamMap . put ( "uploads" , "" ) ; HttpResponse response = executePost ( bucketName , objectName , headerMap , queryParamMap , "" ) ; InitiateMultipartUploadResult result = new InitiateMultipartUploadResult ( ) ; result . parseXml ( response . body ( ) . charStream ( ) ) ; response . body ( ) . close ( ) ; return result . uploadId ( ) ; } | Initializes new multipart upload for given bucket name object name and content type . |
32,910 | private void completeMultipart ( String bucketName , String objectName , String uploadId , Part [ ] parts ) throws InvalidBucketNameException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException { Map < String , String > queryParamMap = new HashMap < > ( ) ; queryParamMap . put ( UPLOAD_ID , uploadId ) ; CompleteMultipartUpload completeManifest = new CompleteMultipartUpload ( parts ) ; HttpResponse response = executePost ( bucketName , objectName , null , queryParamMap , completeManifest ) ; String bodyContent = "" ; Scanner scanner = new Scanner ( response . body ( ) . charStream ( ) ) ; try { scanner . useDelimiter ( "\\A" ) ; if ( scanner . hasNext ( ) ) { bodyContent = scanner . next ( ) ; } } finally { response . body ( ) . close ( ) ; scanner . close ( ) ; } bodyContent = bodyContent . trim ( ) ; if ( ! bodyContent . isEmpty ( ) ) { ErrorResponse errorResponse = new ErrorResponse ( new StringReader ( bodyContent ) ) ; if ( errorResponse . code ( ) != null ) { throw new ErrorResponseException ( errorResponse , response . response ( ) ) ; } } } | Executes complete multipart upload of given bucket name object name upload ID and parts . |
32,911 | private void abortMultipartUpload ( String bucketName , String objectName , String uploadId ) throws InvalidBucketNameException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException { Map < String , String > queryParamMap = new HashMap < > ( ) ; queryParamMap . put ( UPLOAD_ID , uploadId ) ; executeDelete ( bucketName , objectName , queryParamMap ) ; } | Aborts multipart upload of given bucket name object name and upload ID . |
32,912 | public void removeIncompleteUpload ( String bucketName , String objectName ) throws InvalidBucketNameException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException { for ( Result < Upload > r : listIncompleteUploads ( bucketName , objectName , true , false ) ) { Upload upload = r . get ( ) ; if ( objectName . equals ( upload . objectName ( ) ) ) { abortMultipartUpload ( bucketName , objectName , upload . uploadId ( ) ) ; return ; } } } | Removes incomplete multipart upload of given object . |
32,913 | public void listenBucketNotification ( String bucketName , String prefix , String suffix , String [ ] events , BucketEventListener eventCallback ) throws InvalidBucketNameException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException { Multimap < String , String > queryParamMap = HashMultimap . create ( ) ; queryParamMap . put ( "prefix" , prefix ) ; queryParamMap . put ( "suffix" , suffix ) ; for ( String event : events ) { queryParamMap . put ( "events" , event ) ; } String bodyContent = "" ; Scanner scanner = null ; HttpResponse response = null ; ObjectMapper mapper = new ObjectMapper ( ) ; try { response = executeReq ( Method . GET , getRegion ( bucketName ) , bucketName , "" , null , queryParamMap , null , 0 ) ; scanner = new Scanner ( response . body ( ) . charStream ( ) ) ; scanner . useDelimiter ( "\n" ) ; while ( scanner . hasNext ( ) ) { bodyContent = scanner . next ( ) . trim ( ) ; if ( bodyContent . equals ( "" ) ) { continue ; } NotificationInfo ni = mapper . readValue ( bodyContent , NotificationInfo . class ) ; eventCallback . updateEvent ( ni ) ; } } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { throw e ; } finally { if ( response != null ) { response . body ( ) . close ( ) ; } if ( scanner != null ) { scanner . close ( ) ; } } } | Listen to bucket notifications . |
32,914 | private static int [ ] calculateMultipartSize ( long size ) throws InvalidArgumentException { if ( size > MAX_OBJECT_SIZE ) { throw new InvalidArgumentException ( "size " + size + " is greater than allowed size 5TiB" ) ; } double partSize = Math . ceil ( ( double ) size / MAX_MULTIPART_COUNT ) ; partSize = Math . ceil ( partSize / MIN_MULTIPART_SIZE ) * MIN_MULTIPART_SIZE ; double partCount = Math . ceil ( size / partSize ) ; double lastPartSize = partSize - ( partSize * partCount - size ) ; if ( lastPartSize == 0.0 ) { lastPartSize = partSize ; } return new int [ ] { ( int ) partSize , ( int ) partCount , ( int ) lastPartSize } ; } | Calculates multipart size of given size and returns three element array contains part size part count and last part size . |
32,915 | private int getAvailableSize ( Object inputStream , int expectedReadSize ) throws IOException , InternalException { RandomAccessFile file = null ; BufferedInputStream stream = null ; if ( inputStream instanceof RandomAccessFile ) { file = ( RandomAccessFile ) inputStream ; } else if ( inputStream instanceof BufferedInputStream ) { stream = ( BufferedInputStream ) inputStream ; } else { throw new InternalException ( "Unknown input stream. This should not happen. " + "Please report to https://github.com/minio/minio-java/issues/" ) ; } long pos = 0 ; if ( file != null ) { pos = file . getFilePointer ( ) ; } else { stream . mark ( expectedReadSize ) ; } byte [ ] buf = new byte [ 16384 ] ; int bytesToRead = buf . length ; int bytesRead = 0 ; int totalBytesRead = 0 ; while ( totalBytesRead < expectedReadSize ) { if ( ( expectedReadSize - totalBytesRead ) < bytesToRead ) { bytesToRead = expectedReadSize - totalBytesRead ; } if ( file != null ) { bytesRead = file . read ( buf , 0 , bytesToRead ) ; } else { bytesRead = stream . read ( buf , 0 , bytesToRead ) ; } if ( bytesRead < 0 ) { break ; } totalBytesRead += bytesRead ; } if ( file != null ) { file . seek ( pos ) ; } else { stream . reset ( ) ; } return totalBytesRead ; } | Return available size of given input stream up to given expected read size . If less data is available than expected read size it returns how much data available to read . |
32,916 | public void traceOn ( OutputStream traceStream ) { if ( traceStream == null ) { throw new NullPointerException ( ) ; } else { this . traceStream = new PrintWriter ( new OutputStreamWriter ( traceStream , StandardCharsets . UTF_8 ) , true ) ; } } | Enables HTTP call tracing and written to traceStream . |
32,917 | public static void set ( Headers headers , Object destination ) { Field [ ] publicFields ; Field [ ] privateFields ; Field [ ] fields ; Class < ? > cls = destination . getClass ( ) ; publicFields = cls . getFields ( ) ; privateFields = cls . getDeclaredFields ( ) ; fields = new Field [ publicFields . length + privateFields . length ] ; System . arraycopy ( publicFields , 0 , fields , 0 , publicFields . length ) ; System . arraycopy ( privateFields , 0 , fields , publicFields . length , privateFields . length ) ; for ( Field field : fields ) { Annotation annotation = field . getAnnotation ( Header . class ) ; if ( annotation == null ) { continue ; } Header httpHeader = ( Header ) annotation ; String value = httpHeader . value ( ) ; String setter = httpHeader . setter ( ) ; if ( setter . isEmpty ( ) ) { String name = field . getName ( ) ; setter = "set" + name . substring ( 0 , 1 ) . toUpperCase ( Locale . US ) + name . substring ( 1 ) ; } try { Method setterMethod = cls . getMethod ( setter , new Class [ ] { String . class } ) ; String valueString = headers . get ( value ) ; if ( valueString != null ) { setterMethod . invoke ( destination , valueString ) ; } } catch ( NoSuchMethodException | IllegalAccessException | InvocationTargetException | IllegalArgumentException e ) { LOGGER . log ( Level . SEVERE , "exception occured: " , e ) ; LOGGER . log ( Level . INFO , "setter: " + setter ) ; LOGGER . log ( Level . INFO , "annotation: " + value ) ; LOGGER . log ( Level . INFO , "value: " + headers . get ( value ) ) ; } } } | Sets destination object from Headers object . |
32,918 | public static String encode ( String str ) { if ( str == null ) { return "" ; } return ESCAPER . escape ( str ) . replaceAll ( "\\!" , "%21" ) . replaceAll ( "\\$" , "%24" ) . replaceAll ( "\\&" , "%26" ) . replaceAll ( "\\'" , "%27" ) . replaceAll ( "\\(" , "%28" ) . replaceAll ( "\\)" , "%29" ) . replaceAll ( "\\*" , "%2A" ) . replaceAll ( "\\+" , "%2B" ) . replaceAll ( "\\," , "%2C" ) . replaceAll ( "\\/" , "%2F" ) . replaceAll ( "\\:" , "%3A" ) . replaceAll ( "\\;" , "%3B" ) . replaceAll ( "\\=" , "%3D" ) . replaceAll ( "\\@" , "%40" ) . replaceAll ( "\\[" , "%5B" ) . replaceAll ( "\\]" , "%5D" ) ; } | Returns S3 encoded string . |
32,919 | public static String getChunkSignature ( String chunkSha256 , DateTime date , String region , String secretKey , String prevSignature ) throws NoSuchAlgorithmException , InvalidKeyException { Signer signer = new Signer ( null , chunkSha256 , date , region , null , secretKey , prevSignature ) ; signer . setScope ( ) ; signer . setChunkStringToSign ( ) ; signer . setSigningKey ( ) ; signer . setSignature ( ) ; return signer . signature ; } | Returns chunk signature calculated using given arguments . |
32,920 | public static String getChunkSeedSignature ( Request request , String region , 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 , null , secretKey , null ) ; signer . setScope ( ) ; signer . setCanonicalRequest ( ) ; signer . setStringToSign ( ) ; signer . setSigningKey ( ) ; signer . setSignature ( ) ; return signer . signature ; } | Returns seed signature for given request . |
32,921 | 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 . |
32,922 | 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 . |
32,923 | 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 . |
32,924 | 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 . |
32,925 | 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 . |
32,926 | public void setContentType ( String contentType ) throws InvalidArgumentException { if ( Strings . isNullOrEmpty ( contentType ) ) { throw new InvalidArgumentException ( "empty content type" ) ; } this . contentType = contentType ; } | Sets content type . |
32,927 | public void setContentEncoding ( String contentEncoding ) throws InvalidArgumentException { if ( Strings . isNullOrEmpty ( contentEncoding ) ) { throw new InvalidArgumentException ( "empty content encoding" ) ; } this . contentEncoding = contentEncoding ; } | Sets content encoding . |
32,928 | 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 . |
32,929 | 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 . |
32,930 | 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 . |
32,931 | 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 . |
32,932 | 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 . |
32,933 | 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 . |
32,934 | 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 . |
32,935 | public int read ( ) throws IOException { if ( this . bytesRead == this . length ) { return - 1 ; } try { if ( this . streamBytesRead == 0 || this . chunkPos == this . chunkBody . length ) { if ( this . streamBytesRead != this . streamSize ) { 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 { byte [ ] chunk = new byte [ 0 ] ; createChunkBody ( chunk ) ; } } this . bytesRead ++ ; 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 . |
32,936 | 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 |
32,937 | 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 |
32,938 | @ 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 . |
32,939 | @ 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 . |
32,940 | @ 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 . |
32,941 | 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 |
32,942 | private int getAndParseHexChar ( ) throws ParseException { final char hexChar = getc ( ) ; if ( hexChar >= '0' && hexChar <= '9' ) { return hexChar - '0' ; } else if ( hexChar >= 'a' && hexChar <= 'f' ) { return hexChar - 'a' + 10 ; } else if ( hexChar >= 'A' && hexChar <= 'F' ) { return hexChar - 'A' + 10 ; } else { throw new ParseException ( this , "Invalid character in Unicode escape sequence: " + hexChar ) ; } } | Get and parse a hexadecimal digit character . |
32,943 | 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 < '0' || c > '9' ) { 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 < '0' || c > '9' ) { 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 < '0' || c > '9' ) { 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 ) { 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 . |
32,944 | private JSONObject parseJSONObject ( ) throws ParseException { expect ( '{' ) ; skipWhitespace ( ) ; if ( peek ( ) == '}' ) { 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 ( ) ; 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 . |
32,945 | 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 ) { final Class < ? > eltClass = instantiate ? ( Class < ? > ) getArrayValueClassOrName ( annotationClassInfo , paramName , true ) : null ; final Object annotationValueObjectArray = eltClass == null ? new Object [ objectArrayValue . length ] : Array . newInstance ( eltClass , objectArrayValue . length ) ; for ( int i = 0 ; i < objectArrayValue . length ; i ++ ) { if ( objectArrayValue [ i ] != null ) { final Object eltValue = objectArrayValue [ i ] . instantiateOrGet ( annotationClassInfo , paramName ) ; Array . set ( annotationValueObjectArray , i , eltValue ) ; } } return annotationValueObjectArray ; } else { return null ; } } | Instantiate or get the wrapped value . |
32,946 | private Object getArrayValueClassOrName ( final ClassInfo annotationClassInfo , final String paramName , final boolean getClass ) { final MethodInfoList annotationMethodList = annotationClassInfo . methodInfo == null ? null : annotationClassInfo . methodInfo . get ( paramName ) ; if ( annotationMethodList != null && annotationMethodList . size ( ) > 1 ) { throw new IllegalArgumentException ( "Duplicated annotation parameter method " + paramName + "() in annotation class " + annotationClassInfo . getName ( ) ) ; } else if ( annotationMethodList != null && annotationMethodList . size ( ) == 1 ) { final TypeSignature annotationMethodResultTypeSig = annotationMethodList . get ( 0 ) . getTypeSignatureOrTypeDescriptor ( ) . getResultType ( ) ; 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 ) { final ClassRefTypeSignature classRefTypeSignature = ( ClassRefTypeSignature ) elementTypeSig ; return getClass ? classRefTypeSignature . loadClass ( ) : classRefTypeSignature . getFullyQualifiedClassName ( ) ; } else if ( elementTypeSig instanceof BaseTypeSignature ) { final BaseTypeSignature baseTypeSignature = ( BaseTypeSignature ) elementTypeSig ; return getClass ? baseTypeSignature . getType ( ) : baseTypeSignature . getTypeStr ( ) ; } } else { 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 . |
32,947 | 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 . |
32,948 | 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 . |
32,949 | 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 ) ; } scanSpec . packageWhiteBlackList . addToWhitelist ( packageNameNormalized ) ; final String path = WhiteBlackList . packageNameToPath ( packageNameNormalized ) ; scanSpec . pathWhiteBlackList . addToWhitelist ( path + "/" ) ; if ( packageNameNormalized . isEmpty ( ) ) { scanSpec . pathWhiteBlackList . addToWhitelist ( "" ) ; } if ( ! packageNameNormalized . contains ( "*" ) ) { 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 . |
32,950 | public ClassGraph whitelistPaths ( final String ... paths ) { for ( final String path : paths ) { final String pathNormalized = WhiteBlackList . normalizePath ( path ) ; final String packageName = WhiteBlackList . pathToPackageName ( pathNormalized ) ; scanSpec . packageWhiteBlackList . addToWhitelist ( packageName ) ; scanSpec . pathWhiteBlackList . addToWhitelist ( pathNormalized + "/" ) ; if ( pathNormalized . isEmpty ( ) ) { scanSpec . pathWhiteBlackList . addToWhitelist ( "" ) ; } if ( ! pathNormalized . contains ( "*" ) ) { 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 . |
32,951 | 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 ) ; } 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 . |
32,952 | 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 ) ; 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 . |
32,953 | 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" ) ; } scanSpec . packageWhiteBlackList . addToBlacklist ( packageNameNormalized ) ; final String path = WhiteBlackList . packageNameToPath ( packageNameNormalized ) ; scanSpec . pathWhiteBlackList . addToBlacklist ( path + "/" ) ; if ( ! packageNameNormalized . contains ( "*" ) ) { scanSpec . packagePrefixWhiteBlackList . addToBlacklist ( packageNameNormalized + "." ) ; scanSpec . pathPrefixWhiteBlackList . addToBlacklist ( path + "/" ) ; } } return this ; } | Prevent the scanning of one or more specific packages and their sub - packages . |
32,954 | 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 ) ; scanSpec . classWhiteBlackList . addToWhitelist ( classNameNormalized ) ; scanSpec . classfilePathWhiteBlackList . addToWhitelist ( WhiteBlackList . classNameToClassfilePath ( classNameNormalized ) ) ; final String packageName = PackageInfo . getParentPackageName ( classNameNormalized ) ; 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 . |
32,955 | 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 . |
32,956 | 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 . |
32,957 | 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 . |
32,958 | private void whitelistOrBlacklistLibOrExtJars ( final boolean whitelist , final String ... jarLeafNames ) { if ( jarLeafNames . length == 0 ) { 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 ( "*" ) ) { 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 ( ) ) { 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 { 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 . |
32,959 | 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 . |
32,960 | 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 . |
32,961 | 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 . |
32,962 | 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 . |
32,963 | public T acquire ( ) throws E { final T instance ; final T recycledInstance = unusedInstances . poll ( ) ; if ( recycledInstance == null ) { final T newInstance = newInstance ( ) ; if ( newInstance == null ) { throw new NullPointerException ( "Failed to allocate a new recyclable instance" ) ; } instance = newInstance ; } else { 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 . |
32,964 | 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 ) { } } return classpathElementOrderURIs ; } | Returns an ordered list of unique classpath element and module URIs . |
32,965 | public ResourceList getAllResources ( ) { if ( allWhitelistedResourcesCached == null ) { final ResourceList whitelistedResourcesList = new ResourceList ( ) ; for ( final ClasspathElement classpathElt : classpathOrder ) { if ( classpathElt . whitelistedResources != null ) { whitelistedResourcesList . addAll ( classpathElt . whitelistedResources ) ; } } allWhitelistedResourcesCached = whitelistedResourcesList ; } return allWhitelistedResourcesCached ; } | Get the list of all resources . |
32,966 | 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 , 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 . |
32,967 | 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 . |
32,968 | 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 . |
32,969 | 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 . |
32,970 | 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 . |
32,971 | 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 . |
32,972 | 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 . |
32,973 | 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 getAllStandardClasses ( ) ; } else { final ClassInfo superclass = classNameToClassInfo . get ( superclassName ) ; return superclass == null ? ClassInfoList . EMPTY_LIST : superclass . getSubclasses ( ) ; } } | Get all subclasses of the named superclass . |
32,974 | 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 . |
32,975 | 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 . |
32,976 | 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 . |
32,977 | 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 . |
32,978 | 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 . |
32,979 | 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 . |
32,980 | 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" ) ; } final SerializationFormat deserialized = JSONDeserializer . deserializeObject ( SerializationFormat . class , json ) ; if ( ! deserialized . format . equals ( CURRENT_SERIALIZATION_FORMAT ) ) { throw new IllegalArgumentException ( "JSON was serialized by newer version of ClassGraph" ) ; } final ClassGraph classGraph = new ClassGraph ( ) ; classGraph . scanSpec = deserialized . scanSpec ; classGraph . scanSpec . performScan = false ; if ( classGraph . scanSpec . overrideClasspath == null ) { classGraph . overrideClasspath ( deserialized . classpath ) ; } final ScanResult scanResult = classGraph . scan ( ) ; scanResult . rawClasspathEltOrderStrs = deserialized . classpath ; scanResult . scanSpec . performScan = true ; 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 ) ; } } scanResult . indexResourcesAndClassInfo ( ) ; scanResult . isObtainedFromDeserialization = true ; return scanResult ; } | Deserialize a ScanResult from previously - serialized JSON . |
32,981 | 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 . |
32,982 | Type resolveTypeVariables ( final Type type ) { if ( type instanceof Class < ? > ) { return type ; } else if ( type instanceof ParameterizedType ) { final ParameterizedType parameterizedType = ( ParameterizedType ) type ; final Type [ ] typeArgs = parameterizedType . getActualTypeArguments ( ) ; Type [ ] typeArgsResolved = null ; for ( int i = 0 ; i < typeArgs . length ; i ++ ) { final Type typeArgResolved = resolveTypeVariables ( typeArgs [ i ] ) ; if ( typeArgsResolved == null ) { if ( ! typeArgResolved . equals ( typeArgs [ i ] ) ) { typeArgsResolved = new Type [ typeArgs . length ] ; System . arraycopy ( typeArgs , 0 , typeArgsResolved , 0 , i ) ; typeArgsResolved [ i ] = typeArgResolved ; } } else { typeArgsResolved [ i ] = typeArgResolved ; } } if ( typeArgsResolved == null ) { return type ; } else { return new ParameterizedTypeImpl ( ( Class < ? > ) parameterizedType . getRawType ( ) , typeArgsResolved , parameterizedType . getOwnerType ( ) ) ; } } else if ( type instanceof TypeVariable < ? > ) { final TypeVariable < ? > typeVariable = ( TypeVariable < ? > ) type ; for ( int i = 0 ; i < typeVariables . length ; i ++ ) { if ( typeVariables [ i ] . getName ( ) . equals ( typeVariable . getName ( ) ) ) { return resolvedTypeArguments [ i ] ; } } return type ; } else if ( type instanceof GenericArrayType ) { 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 ; final int [ ] dims = ( int [ ] ) Array . newInstance ( int . class , numArrayDims ) ; final Object arrayInstance = Array . newInstance ( innermostTypeResolvedClass , dims ) ; return arrayInstance . getClass ( ) ; } else if ( type instanceof 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 . |
32,983 | 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 ) { final Object refdObj = ( ( JSONReference ) jsonVal ) . idObject ; if ( refdObj == null ) { throw ClassGraphException . newClassGraphException ( "Internal inconsistency" ) ; } final ReferenceEqualityKey < Object > refdObjKey = new ReferenceEqualityKey < > ( refdObj ) ; final JSONObject refdJsonVal = objToJSONVal . get ( refdObjKey ) ; if ( refdJsonVal == null ) { throw ClassGraphException . newClassGraphException ( "Internal inconsistency" ) ; } final Field annotatedField = classFieldCache . get ( refdObj . getClass ( ) ) . idField ; CharSequence idStr = null ; if ( annotatedField != null ) { try { final Object idObject = annotatedField . get ( refdObj ) ; if ( idObject != null ) { idStr = idObject . toString ( ) ; refdJsonVal . objectId = idStr ; } } catch ( IllegalArgumentException | IllegalAccessException e ) { throw new IllegalArgumentException ( "Could not access @Id-annotated field " + annotatedField , e ) ; } } if ( idStr == null ) { if ( refdJsonVal . objectId == null ) { idStr = JSONUtils . ID_PREFIX + objId . getAndIncrement ( ) + JSONUtils . ID_SUFFIX ; refdJsonVal . objectId = idStr ; } else { idStr = refdJsonVal . objectId ; } } jsonReferenceToId . put ( new ReferenceEqualityKey < > ( ( JSONReference ) jsonVal ) , idStr ) ; } } | Create a unique id for each referenced JSON object . |
32,984 | 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 ) { ( ( JSONObject ) jsonVal ) . toJSONString ( jsonReferenceToId , includeNullValuedFields , depth , indentWidth , buf ) ; } else if ( jsonVal instanceof JSONArray ) { ( ( JSONArray ) jsonVal ) . toJSONString ( jsonReferenceToId , includeNullValuedFields , depth , indentWidth , buf ) ; } else if ( jsonVal instanceof JSONReference ) { 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 ( ) ) { buf . append ( '"' ) ; JSONUtils . escapeJSONString ( jsonVal . toString ( ) , buf ) ; buf . append ( '"' ) ; } else { buf . append ( jsonVal . toString ( ) ) ; } } | Serialize a JSON object array or value . |
32,985 | private void scheduleScanningIfExternalClass ( final String className , final String relationship ) { if ( className != null && ! className . equals ( "java.lang.Object" ) && classNamesScheduledForScanning . add ( className ) ) { final String classfilePath = JarUtils . classNameToClassfilePath ( className ) ; Resource classResource = classpathElement . getResource ( classfilePath ) ; ClasspathElement foundInClasspathElt = null ; if ( classResource != null ) { foundInClasspathElt = classpathElement ; } else { for ( final ClasspathElement classpathOrderElt : classpathOrder ) { if ( classpathOrderElt != classpathElement ) { classResource = classpathOrderElt . getResource ( classfilePath ) ; if ( classResource != null ) { foundInClasspathElt = classpathOrderElt ; break ; } } } } if ( classResource != null ) { 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 < > ( ) ; } additionalWorkUnits . add ( new ClassfileScanWorkUnit ( foundInClasspathElt , classResource , 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 . |
32,986 | private void extendScanningUpwards ( ) { if ( superclassName != null ) { scheduleScanningIfExternalClass ( superclassName , "superclass" ) ; } if ( implementedInterfaces != null ) { for ( final String interfaceName : implementedInterfaces ) { scheduleScanningIfExternalClass ( interfaceName , "interface" ) ; } } if ( classAnnotations != null ) { for ( final AnnotationInfo annotationInfo : classAnnotations ) { scheduleScanningIfExternalClass ( annotationInfo . getName ( ) , "class annotation" ) ; } } 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" ) ; } } } } } } } 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 . |
32,987 | void link ( final Map < String , ClassInfo > classNameToClassInfo , final Map < String , PackageInfo > packageNameToPackageInfo , final Map < String , ModuleInfo > moduleNameToModuleInfo ) { boolean isModuleDescriptor = false ; boolean isPackageDescriptor = false ; ClassInfo classInfo = null ; if ( className . equals ( "module-info" ) ) { isModuleDescriptor = true ; } else if ( className . equals ( "package-info" ) || className . endsWith ( ".package-info" ) ) { isPackageDescriptor = true ; } else { classInfo = ClassInfo . addScannedClass ( className , classModifiers , isExternalClass , classNameToClassInfo , classpathElement , classfileResource ) ; classInfo . setModifiers ( classModifiers ) ; classInfo . setIsInterface ( isInterface ) ; classInfo . setIsAnnotation ( isAnnotation ) ; if ( superclassName != null ) { classInfo . addSuperclass ( superclassName , classNameToClassInfo ) ; } if ( implementedInterfaces != null ) { for ( final String interfaceName : implementedInterfaces ) { classInfo . addImplementedInterface ( interfaceName , classNameToClassInfo ) ; } } if ( classAnnotations != null ) { for ( final AnnotationInfo classAnnotation : classAnnotations ) { classInfo . addClassAnnotation ( classAnnotation , classNameToClassInfo ) ; } } if ( classContainmentEntries != null ) { ClassInfo . addClassContainment ( classContainmentEntries , classNameToClassInfo ) ; } if ( annotationParamDefaultValues != null ) { classInfo . addAnnotationParamDefaultValues ( annotationParamDefaultValues ) ; } if ( fullyQualifiedDefiningMethodName != null ) { classInfo . addFullyQualifiedDefiningMethodName ( fullyQualifiedDefiningMethodName ) ; } if ( fieldInfoList != null ) { classInfo . addFieldInfo ( fieldInfoList , classNameToClassInfo ) ; } if ( methodInfoList != null ) { classInfo . addMethodInfo ( methodInfoList , classNameToClassInfo ) ; } if ( typeSignature != null ) { classInfo . setTypeSignature ( typeSignature ) ; } if ( refdClassNames != null ) { classInfo . addReferencedClassNames ( refdClassNames ) ; } } PackageInfo packageInfo = null ; if ( ! isModuleDescriptor ) { packageInfo = PackageInfo . getOrCreatePackage ( PackageInfo . getParentPackageName ( className ) , packageNameToPackageInfo ) ; if ( isPackageDescriptor ) { packageInfo . addAnnotations ( classAnnotations ) ; } else if ( classInfo != null ) { packageInfo . addClassInfo ( classInfo ) ; classInfo . packageInfo = packageInfo ; } } final String moduleName = classpathElement . getModuleName ( ) ; if ( moduleName != null ) { ModuleInfo moduleInfo = moduleNameToModuleInfo . get ( moduleName ) ; if ( moduleInfo == null ) { moduleNameToModuleInfo . put ( moduleName , moduleInfo = new ModuleInfo ( classfileResource . getModuleRef ( ) , classpathElement ) ) ; } if ( isModuleDescriptor ) { moduleInfo . addAnnotations ( classAnnotations ) ; } if ( classInfo != null ) { moduleInfo . addClassInfo ( classInfo ) ; classInfo . moduleInfo = moduleInfo ; } if ( packageInfo != null ) { moduleInfo . addPackageInfo ( packageInfo ) ; } } } | Link classes . Not threadsafe should be run in a single - threaded context . |
32,988 | 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 . |
32,989 | 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 ) { return 0 ; } else if ( t == 1 ) { cpIdxToUse = cpIdx ; } else if ( t == 7 || t == 8 || t == 19 ) { final int indirIdx = indirectStringRefs [ cpIdx ] ; if ( indirIdx == - 1 ) { throw new ClassfileFormatException ( "Bad string indirection index, cannot continue reading class. " + "Please report this at https://github.com/classgraph/classgraph/issues" ) ; } if ( indirIdx == 0 ) { return 0 ; } cpIdxToUse = indirIdx ; } else if ( t == 12 ) { final int compoundIndirIdx = indirectStringRefs [ cpIdx ] ; if ( compoundIndirIdx == - 1 ) { 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 ) { 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 . |
32,990 | 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 , false , false ) ) ; } | Get a string from the constant pool . |
32,991 | private byte getConstantPoolStringFirstByte ( final int cpIdx ) throws ClassfileFormatException , IOException { final int constantPoolStringOffset = getConstantPoolStringOffset ( cpIdx , 0 ) ; if ( constantPoolStringOffset == 0 ) { return '\0' ; } final int utfLen = inputStreamOrByteBuffer . readUnsignedShort ( constantPoolStringOffset ) ; if ( utfLen == 0 ) { return '\0' ; } 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 . |
32,992 | private boolean constantPoolStringEquals ( final int cpIdx , final String asciiString ) throws ClassfileFormatException , IOException { final int strOffset = getConstantPoolStringOffset ( cpIdx , 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 . |
32,993 | 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 . |
32,994 | 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 . |
32,995 | 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 . |
32,996 | private Object getFieldConstantPoolValue ( final int tag , final char fieldTypeDescriptorFirstChar , final int cpIdx ) throws ClassfileFormatException , IOException { switch ( tag ) { case 1 : case 7 : case 8 : return getConstantPoolString ( cpIdx ) ; case 3 : final int intVal = cpReadInt ( cpIdx ) ; switch ( fieldTypeDescriptorFirstChar ) { case 'I' : return intVal ; case 'S' : return ( short ) intVal ; case 'C' : return ( char ) intVal ; case 'B' : return ( byte ) intVal ; case 'Z' : return intVal != 0 ; default : } throw new ClassfileFormatException ( "Unknown Constant_INTEGER type " + fieldTypeDescriptorFirstChar + ", " + "cannot continue reading class. Please report this at " + "https://github.com/classgraph/classgraph/issues" ) ; case 4 : return Float . intBitsToFloat ( cpReadInt ( cpIdx ) ) ; case 5 : return cpReadLong ( cpIdx ) ; case 6 : return Double . longBitsToDouble ( cpReadLong ( cpIdx ) ) ; default : 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 . |
32,997 | private AnnotationInfo readAnnotation ( ) throws IOException { 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 . |
32,998 | private Object readAnnotationElementValue ( ) throws IOException { final int tag = ( char ) inputStreamOrByteBuffer . readUnsignedByte ( ) ; switch ( tag ) { case 'B' : return ( byte ) cpReadInt ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) ; case 'C' : return ( char ) cpReadInt ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) ; case 'D' : return Double . longBitsToDouble ( cpReadLong ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) ) ; case 'F' : return Float . intBitsToFloat ( cpReadInt ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) ) ; case 'I' : return cpReadInt ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) ; case 'J' : return cpReadLong ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) ; case 'S' : return ( short ) cpReadUnsignedShort ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) ; case 'Z' : return cpReadInt ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) != 0 ; case 's' : return getConstantPoolString ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) ; case 'e' : { final String annotationClassName = getConstantPoolClassDescriptor ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) ; final String annotationConstName = getConstantPoolString ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) ; return new AnnotationEnumValue ( annotationClassName , annotationConstName ) ; } case 'c' : final String classRefTypeDescriptor = getConstantPoolString ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) ; return new AnnotationClassRef ( classRefTypeDescriptor ) ; case '@' : return readAnnotation ( ) ; case '[' : final int count = inputStreamOrByteBuffer . readUnsignedShort ( ) ; final Object [ ] arr = new Object [ count ] ; for ( int i = 0 ; i < count ; ++ i ) { 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 . |
32,999 | private void readBasicClassInfo ( ) throws IOException , ClassfileFormatException , SkipClassException { classModifiers = inputStreamOrByteBuffer . readUnsignedShort ( ) ; isInterface = ( classModifiers & 0x0200 ) != 0 ; isAnnotation = ( classModifiers & 0x2000 ) != 0 ; 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 ) ) { throw new SkipClassException ( "No need to scan java.lang.Object" ) ; } final boolean isModule = ( classModifiers & 0x8000 ) != 0 ; 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" ) ; } if ( ! relativePath . endsWith ( ".class" ) ) { 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 ) ; } final int superclassNameCpIdx = inputStreamOrByteBuffer . readUnsignedShort ( ) ; if ( superclassNameCpIdx > 0 ) { superclassName = getConstantPoolClassName ( superclassNameCpIdx ) ; } } | Read basic class information . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.