idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
33,000
private void readInterfaces ( ) throws IOException { 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 .
33,001
private void readClassAttributes ( ) throws IOException , ClassfileFormatException { final int attributesCount = inputStreamOrByteBuffer . readUnsignedShort ( ) ; for ( int i = 0 ; i < attributesCount ; i ++ ) { final int attributeNameCpIdx = inputStreamOrByteBuffer . readUnsignedShort ( ) ; final int attributeLength = inputStreamOrByteBuffer . readInt ( ) ; if ( scanSpec . enableAnnotationInfo && ( constantPoolStringEquals ( attributeNameCpIdx , "RuntimeVisibleAnnotations" ) || ( ! scanSpec . disableRuntimeInvisibleAnnotations && constantPoolStringEquals ( attributeNameCpIdx , "RuntimeInvisibleAnnotations" ) ) ) ) { final int annotationCount = inputStreamOrByteBuffer . readUnsignedShort ( ) ; if ( annotationCount > 0 ) { if ( classAnnotations == null ) { classAnnotations = new AnnotationInfoList ( ) ; } for ( int m = 0 ; m < annotationCount ; m ++ ) { classAnnotations . add ( readAnnotation ( ) ) ; } } } else if ( constantPoolStringEquals ( attributeNameCpIdx , "InnerClasses" ) ) { final int numInnerClasses = inputStreamOrByteBuffer . readUnsignedShort ( ) ; for ( int j = 0 ; j < numInnerClasses ; j ++ ) { final int innerClassInfoCpIdx = inputStreamOrByteBuffer . readUnsignedShort ( ) ; final int outerClassInfoCpIdx = inputStreamOrByteBuffer . readUnsignedShort ( ) ; if ( innerClassInfoCpIdx != 0 && outerClassInfoCpIdx != 0 ) { if ( classContainmentEntries == null ) { classContainmentEntries = new ArrayList < > ( ) ; } classContainmentEntries . add ( new SimpleEntry < > ( getConstantPoolClassName ( innerClassInfoCpIdx ) , getConstantPoolClassName ( outerClassInfoCpIdx ) ) ) ; } inputStreamOrByteBuffer . skip ( 2 ) ; inputStreamOrByteBuffer . skip ( 2 ) ; } } else if ( constantPoolStringEquals ( attributeNameCpIdx , "Signature" ) ) { typeSignature = getConstantPoolString ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) ; } else if ( constantPoolStringEquals ( attributeNameCpIdx , "EnclosingMethod" ) ) { final String innermostEnclosingClassName = getConstantPoolClassName ( inputStreamOrByteBuffer . readUnsignedShort ( ) ) ; final int enclosingMethodCpIdx = inputStreamOrByteBuffer . readUnsignedShort ( ) ; String definingMethodName ; if ( enclosingMethodCpIdx == 0 ) { definingMethodName = "<clinit>" ; } else { definingMethodName = getConstantPoolString ( enclosingMethodCpIdx , 0 ) ; } if ( classContainmentEntries == null ) { classContainmentEntries = new ArrayList < > ( ) ; } classContainmentEntries . add ( new SimpleEntry < > ( className , innermostEnclosingClassName ) ) ; this . fullyQualifiedDefiningMethodName = innermostEnclosingClassName + "." + definingMethodName ; } else if ( constantPoolStringEquals ( attributeNameCpIdx , "Module" ) ) { final int moduleNameCpIdx = inputStreamOrByteBuffer . readUnsignedShort ( ) ; classpathElement . moduleNameFromModuleDescriptor = getConstantPoolString ( moduleNameCpIdx ) ; inputStreamOrByteBuffer . skip ( attributeLength - 2 ) ; } else { inputStreamOrByteBuffer . skip ( attributeLength ) ; } } }
Read class attributes .
33,002
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 .
33,003
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 .
33,004
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 .
33,005
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 .
33,006
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 ) { } } } }
Write to log .
33,007
private static Class < ? > [ ] getCallStackViaSecurityManager ( final LogNode log ) { try { return new CallerResolver ( ) . getClassContext ( ) ; } catch ( final SecurityException e ) { 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 .
33,008
static Class < ? > [ ] getClassContext ( final LogNode log ) { 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 ) { stackClasses = AccessController . doPrivileged ( new PrivilegedAction < Class < ? > [ ] > ( ) { public Class < ? > [ ] run ( ) { return getCallStackViaStackWalker ( ) ; } } ) ; } if ( stackClasses == null || stackClasses . length == 0 ) { stackClasses = AccessController . doPrivileged ( new PrivilegedAction < Class < ? > [ ] > ( ) { public Class < ? > [ ] run ( ) { return getCallStackViaSecurityManager ( log ) ; } } ) ; } 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 ) { } } if ( ! stackClassesList . isEmpty ( ) ) { stackClasses = stackClassesList . toArray ( new Class < ? > [ 0 ] ) ; } else { stackClasses = new Class < ? > [ ] { CallStackReader . class } ; } } return stackClasses ; }
Get the class context .
33,009
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 .
33,010
protected void checkResourcePathWhiteBlackList ( final String relativePath , final LogNode log ) { 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 .
33,011
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 ) { if ( scanSpec . enableClassInfo && ! scanSpec . classfilePathWhiteBlackList . isBlacklisted ( path ) ) { whitelistedClassfileResources . add ( resource ) ; isWhitelisted = true ; } } else { isWhitelisted = true ; } whitelistedResources . add ( resource ) ; 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 ; } resource . scanLog = log . log ( "0:" + path , logStr + path + ( path . equals ( resource . getPathRelativeToClasspathElement ( ) ) ? "" : " ; full path: " + resource . getPathRelativeToClasspathElement ( ) ) ) ; } }
Add a resource discovered during the scan .
33,012
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 .
33,013
void addAnnotations ( final AnnotationInfoList moduleAnnotations ) { 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 .
33,014
static TypeVariableSignature parse ( final Parser parser , final String definingClassName ) throws ParseException { final char peek = parser . peek ( ) ; if ( peek == 'T' ) { 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 ) ; @ 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 .
33,015
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 .
33,016
private void appendLine ( final String timeStampStr , final int indentLevel , final String line , final StringBuilder buf ) { buf . append ( timeStampStr ) ; buf . append ( '\t' ) ; buf . append ( ClassGraph . class . getSimpleName ( ) ) ; buf . append ( '\t' ) ; 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 ( '\n' ) ; }
Append a line to the log output indenting this log entry according to tree structure .
33,017
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 ; children . put ( newSortKey , newChild ) ; return newChild ; }
Add a child log node .
33,018
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 .
33,019
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 .
33,020
public LogNode log ( final String msg , final Throwable e ) { return addChild ( "" , msg , - 1L ) . addChild ( e ) ; }
Add a log entry .
33,021
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 .
33,022
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 .
33,023
public boolean checkAndReturn ( ) { if ( interrupted . get ( ) ) { interrupt ( ) ; return true ; } if ( Thread . currentThread ( ) . isInterrupted ( ) ) { interrupted . set ( true ) ; return true ; } return false ; }
Check for interruption and return interruption status .
33,024
public void check ( ) throws InterruptedException , ExecutionException { final ExecutionException executionException = getExecutionException ( ) ; if ( executionException != null ) { throw executionException ; } if ( checkAndReturn ( ) ) { throw new InterruptedException ( ) ; } }
Check if this thread or any other thread that shares this InterruptionChecker instance has been interrupted or has thrown an exception and if so throw InterruptedException .
33,025
public boolean isSystemModule ( ) { if ( name == null || name . isEmpty ( ) ) { return false ; } return name . startsWith ( "java." ) || name . startsWith ( "jdk." ) || name . startsWith ( "javafx." ) || name . startsWith ( "oracle." ) ; }
Checks if this module is a system module .
33,026
static MethodTypeSignature parse ( final String typeDescriptor , final String definingClassName ) throws ParseException { if ( typeDescriptor . equals ( "<init>" ) ) { return new MethodTypeSignature ( Collections . < TypeParameter > emptyList ( ) , Collections . < TypeSignature > emptyList ( ) , new BaseTypeSignature ( "void" ) , Collections . < ClassRefOrTypeVariableSignature > emptyList ( ) ) ; } final Parser parser = new Parser ( typeDescriptor ) ; final List < TypeParameter > typeParameters = TypeParameter . parseList ( parser , definingClassName ) ; parser . expect ( '(' ) ; final List < TypeSignature > paramTypes = new ArrayList < > ( ) ; while ( parser . peek ( ) != ')' ) { if ( ! parser . hasMore ( ) ) { throw new ParseException ( parser , "Ran out of input while parsing method signature" ) ; } final TypeSignature paramType = TypeSignature . parse ( parser , definingClassName ) ; if ( paramType == null ) { throw new ParseException ( parser , "Missing method parameter type signature" ) ; } paramTypes . add ( paramType ) ; } parser . expect ( ')' ) ; final TypeSignature resultType = TypeSignature . parse ( parser , definingClassName ) ; if ( resultType == null ) { throw new ParseException ( parser , "Missing method result type signature" ) ; } List < ClassRefOrTypeVariableSignature > throwsSignatures ; if ( parser . peek ( ) == '^' ) { throwsSignatures = new ArrayList < > ( ) ; while ( parser . peek ( ) == '^' ) { parser . expect ( '^' ) ; final ClassRefTypeSignature classTypeSignature = ClassRefTypeSignature . parse ( parser , definingClassName ) ; if ( classTypeSignature != null ) { throwsSignatures . add ( classTypeSignature ) ; } else { final TypeVariableSignature typeVariableSignature = TypeVariableSignature . parse ( parser , definingClassName ) ; if ( typeVariableSignature != null ) { throwsSignatures . add ( typeVariableSignature ) ; } else { throw new ParseException ( parser , "Missing type variable signature" ) ; } } } } else { throwsSignatures = Collections . emptyList ( ) ; } if ( parser . hasMore ( ) ) { throw new ParseException ( parser , "Extra characters at end of type descriptor" ) ; } final MethodTypeSignature methodSignature = new MethodTypeSignature ( typeParameters , paramTypes , resultType , throwsSignatures ) ; @ SuppressWarnings ( "unchecked" ) final List < TypeVariableSignature > typeVariableSignatures = ( List < TypeVariableSignature > ) parser . getState ( ) ; if ( typeVariableSignatures != null ) { for ( final TypeVariableSignature typeVariableSignature : typeVariableSignatures ) { typeVariableSignature . containingMethodSignature = methodSignature ; } } return methodSignature ; }
Parse a method signature .
33,027
void toJSONString ( final Map < ReferenceEqualityKey < JSONReference > , CharSequence > jsonReferenceToId , final boolean includeNullValuedFields , final int depth , final int indentWidth , final StringBuilder buf ) { final boolean prettyPrint = indentWidth > 0 ; final int n = items . size ( ) ; if ( n == 0 ) { buf . append ( "[]" ) ; } else { buf . append ( '[' ) ; if ( prettyPrint ) { buf . append ( '\n' ) ; } for ( int i = 0 ; i < n ; i ++ ) { final Object item = items . get ( i ) ; if ( prettyPrint ) { JSONUtils . indent ( depth + 1 , indentWidth , buf ) ; } JSONSerializer . jsonValToJSONString ( item , jsonReferenceToId , includeNullValuedFields , depth + 1 , indentWidth , buf ) ; if ( i < n - 1 ) { buf . append ( ',' ) ; } if ( prettyPrint ) { buf . append ( '\n' ) ; } } if ( prettyPrint ) { JSONUtils . indent ( depth , indentWidth , buf ) ; } buf . append ( ']' ) ; } }
Serialize this JSONArray to a string .
33,028
boolean addRelatedClass ( final RelType relType , final ClassInfo classInfo ) { Set < ClassInfo > classInfoSet = relatedClasses . get ( relType ) ; if ( classInfoSet == null ) { relatedClasses . put ( relType , classInfoSet = new LinkedHashSet < > ( 4 ) ) ; } return classInfoSet . add ( classInfo ) ; }
Add a class with a given relationship type . Return whether the collection changed as a result of the call .
33,029
static ClassInfo getOrCreateClassInfo ( final String className , final int classModifiers , final Map < String , ClassInfo > classNameToClassInfo ) { ClassInfo classInfo = classNameToClassInfo . get ( className ) ; if ( classInfo == null ) { classNameToClassInfo . put ( className , classInfo = new ClassInfo ( className , classModifiers , null ) ) ; } classInfo . setModifiers ( classModifiers ) ; return classInfo ; }
Get a ClassInfo object or create it if it doesn t exist . N . B . not threadsafe so ClassInfo objects should only ever be constructed by a single thread .
33,030
void setModifiers ( final int modifiers ) { this . modifiers |= modifiers ; if ( ( modifiers & ANNOTATION_CLASS_MODIFIER ) != 0 ) { this . isAnnotation = true ; } if ( ( modifiers & Modifier . INTERFACE ) != 0 ) { this . isInterface = true ; } }
Set class modifiers .
33,031
void addSuperclass ( final String superclassName , final Map < String , ClassInfo > classNameToClassInfo ) { if ( superclassName != null && ! superclassName . equals ( "java.lang.Object" ) ) { final ClassInfo superclassClassInfo = getOrCreateClassInfo ( superclassName , 0 , classNameToClassInfo ) ; this . addRelatedClass ( RelType . SUPERCLASSES , superclassClassInfo ) ; superclassClassInfo . addRelatedClass ( RelType . SUBCLASSES , this ) ; } }
Add a superclass to this class .
33,032
void addImplementedInterface ( final String interfaceName , final Map < String , ClassInfo > classNameToClassInfo ) { final ClassInfo interfaceClassInfo = getOrCreateClassInfo ( interfaceName , Modifier . INTERFACE , classNameToClassInfo ) ; interfaceClassInfo . isInterface = true ; interfaceClassInfo . modifiers |= Modifier . INTERFACE ; this . addRelatedClass ( RelType . IMPLEMENTED_INTERFACES , interfaceClassInfo ) ; interfaceClassInfo . addRelatedClass ( RelType . CLASSES_IMPLEMENTING , this ) ; }
Add an implemented interface to this class .
33,033
static void addClassContainment ( final List < SimpleEntry < String , String > > classContainmentEntries , final Map < String , ClassInfo > classNameToClassInfo ) { for ( final SimpleEntry < String , String > ent : classContainmentEntries ) { final String innerClassName = ent . getKey ( ) ; final ClassInfo innerClassInfo = ClassInfo . getOrCreateClassInfo ( innerClassName , 0 , classNameToClassInfo ) ; final String outerClassName = ent . getValue ( ) ; final ClassInfo outerClassInfo = ClassInfo . getOrCreateClassInfo ( outerClassName , 0 , classNameToClassInfo ) ; innerClassInfo . addRelatedClass ( RelType . CONTAINED_WITHIN_OUTER_CLASS , outerClassInfo ) ; outerClassInfo . addRelatedClass ( RelType . CONTAINS_INNER_CLASS , innerClassInfo ) ; } }
Add class containment info .
33,034
void addClassAnnotation ( final AnnotationInfo classAnnotationInfo , final Map < String , ClassInfo > classNameToClassInfo ) { final ClassInfo annotationClassInfo = getOrCreateClassInfo ( classAnnotationInfo . getName ( ) , ANNOTATION_CLASS_MODIFIER , classNameToClassInfo ) ; if ( this . annotationInfo == null ) { this . annotationInfo = new AnnotationInfoList ( 2 ) ; } this . annotationInfo . add ( classAnnotationInfo ) ; this . addRelatedClass ( RelType . CLASS_ANNOTATIONS , annotationClassInfo ) ; annotationClassInfo . addRelatedClass ( RelType . CLASSES_WITH_ANNOTATION , this ) ; if ( classAnnotationInfo . getName ( ) . equals ( Inherited . class . getName ( ) ) ) { isInherited = true ; } }
Add an annotation to this class .
33,035
private void addFieldOrMethodAnnotationInfo ( final AnnotationInfoList annotationInfoList , final boolean isField , final Map < String , ClassInfo > classNameToClassInfo ) { if ( annotationInfoList != null ) { for ( final AnnotationInfo fieldAnnotationInfo : annotationInfoList ) { final ClassInfo annotationClassInfo = getOrCreateClassInfo ( fieldAnnotationInfo . getName ( ) , ANNOTATION_CLASS_MODIFIER , classNameToClassInfo ) ; this . addRelatedClass ( isField ? RelType . FIELD_ANNOTATIONS : RelType . METHOD_ANNOTATIONS , annotationClassInfo ) ; annotationClassInfo . addRelatedClass ( isField ? RelType . CLASSES_WITH_FIELD_ANNOTATION : RelType . CLASSES_WITH_METHOD_ANNOTATION , this ) ; } } }
Add field or method annotation cross - links .
33,036
void addFieldInfo ( final FieldInfoList fieldInfoList , final Map < String , ClassInfo > classNameToClassInfo ) { for ( final FieldInfo fi : fieldInfoList ) { addFieldOrMethodAnnotationInfo ( fi . annotationInfo , true , classNameToClassInfo ) ; } if ( this . fieldInfo == null ) { this . fieldInfo = fieldInfoList ; } else { this . fieldInfo . addAll ( fieldInfoList ) ; } }
Add field info .
33,037
void addMethodInfo ( final MethodInfoList methodInfoList , final Map < String , ClassInfo > classNameToClassInfo ) { for ( final MethodInfo mi : methodInfoList ) { addFieldOrMethodAnnotationInfo ( mi . annotationInfo , false , classNameToClassInfo ) ; if ( mi . parameterAnnotationInfo != null ) { for ( int i = 0 ; i < mi . parameterAnnotationInfo . length ; i ++ ) { final AnnotationInfo [ ] paramAnnotationInfoArr = mi . parameterAnnotationInfo [ i ] ; if ( paramAnnotationInfoArr != null ) { for ( int j = 0 ; j < paramAnnotationInfoArr . length ; j ++ ) { final AnnotationInfo methodParamAnnotationInfo = paramAnnotationInfoArr [ j ] ; final ClassInfo annotationClassInfo = getOrCreateClassInfo ( methodParamAnnotationInfo . getName ( ) , ANNOTATION_CLASS_MODIFIER , classNameToClassInfo ) ; annotationClassInfo . addRelatedClass ( RelType . CLASSES_WITH_METHOD_PARAMETER_ANNOTATION , this ) ; this . addRelatedClass ( RelType . METHOD_PARAMETER_ANNOTATIONS , annotationClassInfo ) ; } } } } } if ( this . methodInfo == null ) { this . methodInfo = methodInfoList ; } else { this . methodInfo . addAll ( methodInfoList ) ; } }
Add method info .
33,038
private static Set < ClassInfo > filterClassInfo ( final Collection < ClassInfo > classes , final ScanSpec scanSpec , final boolean strictWhitelist , final ClassType ... classTypes ) { if ( classes == null ) { return Collections . < ClassInfo > emptySet ( ) ; } boolean includeAllTypes = classTypes . length == 0 ; boolean includeStandardClasses = false ; boolean includeImplementedInterfaces = false ; boolean includeAnnotations = false ; for ( final ClassType classType : classTypes ) { switch ( classType ) { case ALL : includeAllTypes = true ; break ; case STANDARD_CLASS : includeStandardClasses = true ; break ; case IMPLEMENTED_INTERFACE : includeImplementedInterfaces = true ; break ; case ANNOTATION : includeAnnotations = true ; break ; case INTERFACE_OR_ANNOTATION : includeImplementedInterfaces = includeAnnotations = true ; break ; default : throw new IllegalArgumentException ( "Unknown ClassType: " + classType ) ; } } if ( includeStandardClasses && includeImplementedInterfaces && includeAnnotations ) { includeAllTypes = true ; } final Set < ClassInfo > classInfoSetFiltered = new LinkedHashSet < > ( classes . size ( ) ) ; for ( final ClassInfo classInfo : classes ) { if ( ( includeAllTypes || includeStandardClasses && classInfo . isStandardClass ( ) || includeImplementedInterfaces && classInfo . isImplementedInterface ( ) || includeAnnotations && classInfo . isAnnotation ( ) ) && ! scanSpec . classOrPackageIsBlacklisted ( classInfo . name ) && ( ! classInfo . isExternalClass || scanSpec . enableExternalClasses || ! strictWhitelist ) ) { classInfoSetFiltered . add ( classInfo ) ; } } return classInfoSetFiltered ; }
Filter classes according to scan spec and class type .
33,039
static ClassInfoList getAllClasses ( final Collection < ClassInfo > classes , final ScanSpec scanSpec ) { return new ClassInfoList ( ClassInfo . filterClassInfo ( classes , scanSpec , true , ClassType . ALL ) , true ) ; }
Get all classes found during the scan .
33,040
static ClassInfoList getAllStandardClasses ( final Collection < ClassInfo > classes , final ScanSpec scanSpec ) { return new ClassInfoList ( ClassInfo . filterClassInfo ( classes , scanSpec , true , ClassType . STANDARD_CLASS ) , true ) ; }
Get all standard classes found during the scan .
33,041
public String getModifiersStr ( ) { final StringBuilder buf = new StringBuilder ( ) ; TypeUtils . modifiersToString ( modifiers , ModifierType . CLASS , false , buf ) ; return buf . toString ( ) ; }
Get the class modifiers as a String .
33,042
public boolean hasField ( final String fieldName ) { for ( final ClassInfo ci : getOverrideOrder ( ) ) { if ( ci . hasDeclaredField ( fieldName ) ) { return true ; } } return false ; }
Checks whether this class or one of its superclasses has the named field .
33,043
public boolean hasDeclaredFieldAnnotation ( final String fieldAnnotationName ) { for ( final FieldInfo fi : getDeclaredFieldInfo ( ) ) { if ( fi . hasAnnotation ( fieldAnnotationName ) ) { return true ; } } return false ; }
Checks whether this class declares a field with the named annotation .
33,044
public boolean hasFieldAnnotation ( final String fieldAnnotationName ) { for ( final ClassInfo ci : getOverrideOrder ( ) ) { if ( ci . hasDeclaredFieldAnnotation ( fieldAnnotationName ) ) { return true ; } } return false ; }
Checks whether this class or one of its superclasses declares a field with the named annotation .
33,045
public boolean hasMethod ( final String methodName ) { for ( final ClassInfo ci : getOverrideOrder ( ) ) { if ( ci . hasDeclaredMethod ( methodName ) ) { return true ; } } return false ; }
Checks whether this class or one of its superclasses or interfaces declares a method of the given name .
33,046
public boolean hasMethodAnnotation ( final String methodAnnotationName ) { for ( final ClassInfo ci : getOverrideOrder ( ) ) { if ( ci . hasDeclaredMethodAnnotation ( methodAnnotationName ) ) { return true ; } } return false ; }
Checks whether this class or one of its superclasses or interfaces declares a method with the named annotation .
33,047
public boolean hasMethodParameterAnnotation ( final String methodParameterAnnotationName ) { for ( final ClassInfo ci : getOverrideOrder ( ) ) { if ( ci . hasDeclaredMethodParameterAnnotation ( methodParameterAnnotationName ) ) { return true ; } } return false ; }
Checks whether this class or one of its superclasses or interfaces has a method with the named annotation .
33,048
private List < ClassInfo > getOverrideOrder ( final Set < ClassInfo > visited , final List < ClassInfo > overrideOrderOut ) { if ( visited . add ( this ) ) { overrideOrderOut . add ( this ) ; for ( final ClassInfo iface : getInterfaces ( ) ) { iface . getOverrideOrder ( visited , overrideOrderOut ) ; } final ClassInfo superclass = getSuperclass ( ) ; if ( superclass != null ) { superclass . getOverrideOrder ( visited , overrideOrderOut ) ; } } return overrideOrderOut ; }
Recurse to interfaces and superclasses to get the order that fields and methods are overridden in .
33,049
public ClassInfoList getInterfaces ( ) { final ReachableAndDirectlyRelatedClasses implementedInterfaces = this . filterClassInfo ( RelType . IMPLEMENTED_INTERFACES , false ) ; final Set < ClassInfo > allInterfaces = new LinkedHashSet < > ( implementedInterfaces . reachableClasses ) ; for ( final ClassInfo superclass : this . filterClassInfo ( RelType . SUPERCLASSES , false ) . reachableClasses ) { final Set < ClassInfo > superclassImplementedInterfaces = superclass . filterClassInfo ( RelType . IMPLEMENTED_INTERFACES , false ) . reachableClasses ; allInterfaces . addAll ( superclassImplementedInterfaces ) ; } return new ClassInfoList ( allInterfaces , implementedInterfaces . directlyRelatedClasses , true ) ; }
Get the interfaces implemented by this 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 .
33,050
private ClassInfoList getClassesWithFieldOrMethodAnnotation ( final RelType relType ) { final boolean isField = relType == RelType . CLASSES_WITH_FIELD_ANNOTATION ; if ( ! ( isField ? scanResult . scanSpec . enableFieldInfo : scanResult . scanSpec . enableMethodInfo ) || ! scanResult . scanSpec . enableAnnotationInfo ) { throw new IllegalArgumentException ( "Please call ClassGraph#enable" + ( isField ? "Field" : "Method" ) + "Info() and " + "#enableAnnotationInfo() before #scan()" ) ; } final ReachableAndDirectlyRelatedClasses classesWithDirectlyAnnotatedFieldsOrMethods = this . filterClassInfo ( relType , ! isExternalClass ) ; final ReachableAndDirectlyRelatedClasses annotationsWithThisMetaAnnotation = this . filterClassInfo ( RelType . CLASSES_WITH_ANNOTATION , ! isExternalClass , ClassType . ANNOTATION ) ; if ( annotationsWithThisMetaAnnotation . reachableClasses . isEmpty ( ) ) { return new ClassInfoList ( classesWithDirectlyAnnotatedFieldsOrMethods , true ) ; } else { final Set < ClassInfo > allClassesWithAnnotatedOrMetaAnnotatedFieldsOrMethods = new LinkedHashSet < > ( classesWithDirectlyAnnotatedFieldsOrMethods . reachableClasses ) ; for ( final ClassInfo metaAnnotatedAnnotation : annotationsWithThisMetaAnnotation . reachableClasses ) { allClassesWithAnnotatedOrMetaAnnotatedFieldsOrMethods . addAll ( metaAnnotatedAnnotation . filterClassInfo ( relType , ! metaAnnotatedAnnotation . isExternalClass ) . reachableClasses ) ; } return new ClassInfoList ( allClassesWithAnnotatedOrMetaAnnotatedFieldsOrMethods , classesWithDirectlyAnnotatedFieldsOrMethods . directlyRelatedClasses , true ) ; } }
Get the classes that have this class as a field method or method parameter annotation .
33,051
public AnnotationParameterValueList getAnnotationDefaultParameterValues ( ) { if ( ! scanResult . scanSpec . enableAnnotationInfo ) { throw new IllegalArgumentException ( "Please call ClassGraph#enableAnnotationInfo() before #scan()" ) ; } if ( ! isAnnotation ) { throw new IllegalArgumentException ( "Class is not an annotation: " + getName ( ) ) ; } if ( annotationDefaultParamValues == null ) { return AnnotationParameterValueList . EMPTY_LIST ; } if ( ! annotationDefaultParamValuesHasBeenConvertedToPrimitive ) { annotationDefaultParamValues . convertWrapperArraysToPrimitiveArrays ( this ) ; annotationDefaultParamValuesHasBeenConvertedToPrimitive = true ; } return annotationDefaultParamValues ; }
Get the default parameter values for this annotation if this is an annotation class .
33,052
public ClassInfoList getClassesWithAnnotation ( ) { if ( ! scanResult . scanSpec . enableAnnotationInfo ) { throw new IllegalArgumentException ( "Please call ClassGraph#enableAnnotationInfo() before #scan()" ) ; } if ( ! isAnnotation ) { throw new IllegalArgumentException ( "Class is not an annotation: " + getName ( ) ) ; } final ReachableAndDirectlyRelatedClasses classesWithAnnotation = this . filterClassInfo ( RelType . CLASSES_WITH_ANNOTATION , ! isExternalClass ) ; if ( isInherited ) { final Set < ClassInfo > classesWithAnnotationAndTheirSubclasses = new LinkedHashSet < > ( classesWithAnnotation . reachableClasses ) ; for ( final ClassInfo classWithAnnotation : classesWithAnnotation . reachableClasses ) { classesWithAnnotationAndTheirSubclasses . addAll ( classWithAnnotation . getSubclasses ( ) ) ; } return new ClassInfoList ( classesWithAnnotationAndTheirSubclasses , classesWithAnnotation . directlyRelatedClasses , true ) ; } else { return new ClassInfoList ( classesWithAnnotation , true ) ; } }
Get the classes that have this class as an annotation .
33,053
public ClassTypeSignature getTypeSignature ( ) { if ( typeSignatureStr == null ) { return null ; } if ( typeSignature == null ) { try { typeSignature = ClassTypeSignature . parse ( typeSignatureStr , this ) ; typeSignature . setScanResult ( scanResult ) ; } catch ( final ParseException e ) { throw new IllegalArgumentException ( e ) ; } } return typeSignature ; }
Get the type signature of the class .
33,054
void addReferencedClassNames ( final Set < String > refdClassNames ) { if ( this . referencedClassNames == null ) { this . referencedClassNames = refdClassNames ; } else { this . referencedClassNames . addAll ( refdClassNames ) ; } }
Add names of classes referenced by this class .
33,055
protected void findReferencedClassNames ( final Set < String > referencedClassNames ) { if ( this . referencedClassNames != null ) { referencedClassNames . addAll ( this . referencedClassNames ) ; } getMethodInfo ( ) . findReferencedClassNames ( referencedClassNames ) ; getFieldInfo ( ) . findReferencedClassNames ( referencedClassNames ) ; getAnnotationInfo ( ) . findReferencedClassNames ( referencedClassNames ) ; if ( annotationDefaultParamValues != null ) { annotationDefaultParamValues . findReferencedClassNames ( referencedClassNames ) ; } final ClassTypeSignature classSig = getTypeSignature ( ) ; if ( classSig != null ) { classSig . findReferencedClassNames ( referencedClassNames ) ; } referencedClassNames . remove ( name ) ; }
Get the names of any classes referenced in this class type descriptor or the type descriptors of fields methods or annotations .
33,056
public ClassInfoList getClassDependencies ( ) { if ( ! scanResult . scanSpec . enableInterClassDependencies ) { throw new IllegalArgumentException ( "Please call ClassGraph#enableInterClassDependencies() before #scan()" ) ; } return referencedClasses == null ? ClassInfoList . EMPTY_LIST : referencedClasses ; }
Get the class dependencies .
33,057
private static void translateSeparator ( final String path , final int startIdx , final int endIdx , final boolean stripFinalSeparator , final StringBuilder buf ) { for ( int i = startIdx ; i < endIdx ; i ++ ) { final char c = path . charAt ( i ) ; if ( c == '\\' || c == '/' ) { if ( i < endIdx - 1 || ! stripFinalSeparator ) { final char prevChar = buf . length ( ) == 0 ? '\0' : buf . charAt ( buf . length ( ) - 1 ) ; if ( prevChar != '/' ) { buf . append ( '/' ) ; } } } else { buf . append ( c ) ; } } }
Translate backslashes to forward slashes optionally removing trailing separator .
33,058
private TypeSignature getTypeSignature ( ) { if ( typeSignature == null ) { try { typeSignature = TypeSignature . parse ( typeDescriptorStr , null ) ; typeSignature . setScanResult ( scanResult ) ; } catch ( final ParseException e ) { throw new IllegalArgumentException ( e ) ; } } return typeSignature ; }
Get the type signature .
33,059
private String sanitizeFilename ( final String filename ) { return filename . replace ( '/' , '_' ) . replace ( '\\' , '_' ) . replace ( ':' , '_' ) . replace ( '?' , '_' ) . replace ( '&' , '_' ) . replace ( '=' , '_' ) . replace ( ' ' , '_' ) ; }
Sanitize filename .
33,060
private File makeTempFile ( final String filePath , final boolean onlyUseLeafname ) throws IOException { final File tempFile = File . createTempFile ( "ClassGraph--" , TEMP_FILENAME_LEAF_SEPARATOR + sanitizeFilename ( onlyUseLeafname ? leafname ( filePath ) : filePath ) ) ; tempFile . deleteOnExit ( ) ; tempFiles . add ( tempFile ) ; return tempFile ; }
Create a temporary file and mark it for deletion on exit .
33,061
private File downloadTempFile ( final String jarURL , final LogNode log ) { final LogNode subLog = log == null ? null : log . log ( jarURL , "Downloading URL " + jarURL ) ; File tempFile ; try { tempFile = makeTempFile ( jarURL , true ) ; final URL url = new URL ( jarURL ) ; try ( InputStream inputStream = url . openStream ( ) ) { Files . copy ( inputStream , tempFile . toPath ( ) , StandardCopyOption . REPLACE_EXISTING ) ; } if ( subLog != null ) { subLog . addElapsedTime ( ) ; } } catch ( final IOException | SecurityException e ) { if ( subLog != null ) { subLog . log ( "Could not download " + jarURL , e ) ; } return null ; } if ( subLog != null ) { subLog . log ( "Downloaded to temporary file " + tempFile ) ; subLog . log ( "***** Note that it is time-consuming to scan jars at http(s) addresses, " + "they must be downloaded for every scan, and the same jars must also be " + "separately downloaded by the ClassLoader *****" ) ; } return tempFile ; }
Download a jar from a URL to a temporary file .
33,062
public String generateGraphVizDotFile ( final float sizeX , final float sizeY ) { return generateGraphVizDotFile ( sizeX , sizeY , true , true , true , true , true ) ; }
Generate a . dot file which can be fed into GraphViz for layout and visualization of the class graph .
33,063
public void generateGraphVizDotFile ( final File file ) throws IOException { try ( PrintWriter writer = new PrintWriter ( file ) ) { writer . print ( generateGraphVizDotFile ( ) ) ; } }
Generate a and save a . dot file which can be fed into GraphViz for layout and visualization of the class graph .
33,064
public boolean containsName ( final String name ) { for ( final T i : this ) { if ( i . getName ( ) . equals ( name ) ) { return true ; } } return false ; }
Check if this list contains an item with the given name .
33,065
public T get ( final String name ) { for ( final T i : this ) { if ( i . getName ( ) . equals ( name ) ) { return i ; } } return null ; }
Get the list item with the given name or null if not found .
33,066
public static < U > void runWorkQueue ( final Collection < U > elements , final ExecutorService executorService , final InterruptionChecker interruptionChecker , final int numParallelTasks , final LogNode log , final WorkUnitProcessor < U > workUnitProcessor ) throws InterruptedException , ExecutionException { if ( elements . isEmpty ( ) ) { return ; } try ( WorkQueue < U > workQueue = new WorkQueue < > ( elements , workUnitProcessor , numParallelTasks , interruptionChecker , log ) ) { workQueue . startWorkers ( executorService , numParallelTasks - 1 ) ; workQueue . runWorkLoop ( ) ; } }
Start a work queue on the elements in the provided collection blocking until all work units have been completed .
33,067
private void startWorkers ( final ExecutorService executorService , final int numTasks ) { for ( int i = 0 ; i < numTasks ; i ++ ) { workerFutures . add ( executorService . submit ( new Callable < Void > ( ) { public Void call ( ) throws Exception { runWorkLoop ( ) ; return null ; } } ) ) ; } }
Start worker threads with a shared log .
33,068
private void sendPoisonPills ( ) { for ( int i = 0 ; i < numWorkers ; i ++ ) { workUnits . add ( new WorkUnitWrapper < T > ( null ) ) ; } }
Send poison pills to workers .
33,069
public void addWorkUnit ( final T workUnit ) { if ( workUnit == null ) { throw new NullPointerException ( "workUnit cannot be null" ) ; } numIncompleteWorkUnits . incrementAndGet ( ) ; workUnits . add ( new WorkUnitWrapper < > ( workUnit ) ) ; }
Add a unit of work . May be called by workers to add more work units to the tail of the queue .
33,070
ClassFields get ( final Class < ? > cls ) { ClassFields classFields = classToClassFields . get ( cls ) ; if ( classFields == null ) { classToClassFields . put ( cls , classFields = new ClassFields ( cls , resolveTypes , onlySerializePublicFields , this ) ) ; } return classFields ; }
For a given resolved type find the visible and accessible fields resolve the types of any generically typed fields and return the resolved fields .
33,071
private static Class < ? > getConcreteType ( final Class < ? > rawType , final boolean returnNullIfNotMapOrCollection ) { if ( rawType == Map . class || rawType == AbstractMap . class || rawType == HashMap . class ) { return HashMap . class ; } else if ( rawType == ConcurrentMap . class || rawType == ConcurrentHashMap . class ) { return ConcurrentHashMap . class ; } else if ( rawType == SortedMap . class || rawType == NavigableMap . class || rawType == TreeMap . class ) { return TreeMap . class ; } else if ( rawType == ConcurrentNavigableMap . class || rawType == ConcurrentSkipListMap . class ) { return ConcurrentSkipListMap . class ; } else if ( rawType == List . class || rawType == AbstractList . class || rawType == ArrayList . class || rawType == Collection . class ) { return ArrayList . class ; } else if ( rawType == AbstractSequentialList . class || rawType == LinkedList . class ) { return LinkedList . class ; } else if ( rawType == Set . class || rawType == AbstractSet . class || rawType == HashSet . class ) { return HashSet . class ; } else if ( rawType == SortedSet . class || rawType == TreeSet . class ) { return TreeSet . class ; } else if ( rawType == Queue . class || rawType == AbstractQueue . class || rawType == Deque . class || rawType == ArrayDeque . class ) { return ArrayDeque . class ; } else if ( rawType == BlockingQueue . class || rawType == LinkedBlockingQueue . class ) { return LinkedBlockingQueue . class ; } else if ( rawType == BlockingDeque . class || rawType == LinkedBlockingDeque . class ) { return LinkedBlockingDeque . class ; } else if ( rawType == TransferQueue . class || rawType == LinkedTransferQueue . class ) { return LinkedTransferQueue . class ; } else { return returnNullIfNotMapOrCollection ? null : rawType ; } }
Get the concrete type for a map or collection whose raw type is an interface or abstract class .
33,072
Constructor < ? > getDefaultConstructorForConcreteTypeOf ( final Class < ? > cls ) { if ( cls == null ) { throw new IllegalArgumentException ( "Class reference cannot be null" ) ; } final Constructor < ? > constructor = defaultConstructorForConcreteType . get ( cls ) ; if ( constructor != null ) { return constructor ; } final Class < ? > concreteType = getConcreteType ( cls , false ) ; for ( Class < ? > c = concreteType ; c != null && ( c != Object . class || cls == Object . class ) ; c = c . getSuperclass ( ) ) { try { final Constructor < ? > defaultConstructor = c . getDeclaredConstructor ( ) ; JSONUtils . isAccessibleOrMakeAccessible ( defaultConstructor ) ; defaultConstructorForConcreteType . put ( cls , defaultConstructor ) ; return defaultConstructor ; } catch ( final ReflectiveOperationException | SecurityException e ) { } } throw new IllegalArgumentException ( "Class " + cls . getName ( ) + " does not have an accessible default (no-arg) constructor" ) ; }
Get the concrete type of the given class then return the default constructor for that type .
33,073
static Object getFieldValue ( final Object containingObj , final Field field ) throws IllegalArgumentException , IllegalAccessException { final Class < ? > fieldType = field . getType ( ) ; if ( fieldType == Integer . TYPE ) { return field . getInt ( containingObj ) ; } else if ( fieldType == Long . TYPE ) { return field . getLong ( containingObj ) ; } else if ( fieldType == Short . TYPE ) { return field . getShort ( containingObj ) ; } else if ( fieldType == Double . TYPE ) { return field . getDouble ( containingObj ) ; } else if ( fieldType == Float . TYPE ) { return field . getFloat ( containingObj ) ; } else if ( fieldType == Boolean . TYPE ) { return field . getBoolean ( containingObj ) ; } else if ( fieldType == Byte . TYPE ) { return field . getByte ( containingObj ) ; } else if ( fieldType == Character . TYPE ) { return field . getChar ( containingObj ) ; } else { return field . get ( containingObj ) ; } }
Get a field value appropriately handling primitive - typed fields .
33,074
static boolean isBasicValueType ( final Type type ) { if ( type instanceof Class < ? > ) { return isBasicValueType ( ( Class < ? > ) type ) ; } else if ( type instanceof ParameterizedType ) { return isBasicValueType ( ( ( ParameterizedType ) type ) . getRawType ( ) ) ; } else { return false ; } }
Return true for types that can be converted directly to and from string representation .
33,075
static boolean isBasicValueType ( final Object obj ) { return obj == null || obj instanceof String || obj instanceof Integer || obj instanceof Boolean || obj instanceof Long || obj instanceof Float || obj instanceof Double || obj instanceof Short || obj instanceof Byte || obj instanceof Character || obj . getClass ( ) . isEnum ( ) ; }
Return true for objects that can be converted directly to and from string representation .
33,076
static boolean fieldIsSerializable ( final Field field , final boolean onlySerializePublicFields ) { final int modifiers = field . getModifiers ( ) ; if ( ( ! onlySerializePublicFields || Modifier . isPublic ( modifiers ) ) && ! Modifier . isTransient ( modifiers ) && ! Modifier . isFinal ( modifiers ) && ( ( modifiers & 0x1000 ) == 0 ) ) { return JSONUtils . isAccessibleOrMakeAccessible ( field ) ; } return false ; }
Check if a field is serializable . Don t serialize transient final synthetic or inaccessible fields .
33,077
public AnnotationParameterValueList getParameterValues ( ) { if ( annotationParamValuesWithDefaults == null ) { final ClassInfo classInfo = getClassInfo ( ) ; if ( classInfo == null ) { return annotationParamValues == null ? AnnotationParameterValueList . EMPTY_LIST : annotationParamValues ; } if ( annotationParamValues != null && ! annotationParamValuesHasBeenConvertedToPrimitive ) { annotationParamValues . convertWrapperArraysToPrimitiveArrays ( classInfo ) ; annotationParamValuesHasBeenConvertedToPrimitive = true ; } if ( classInfo . annotationDefaultParamValues != null && ! classInfo . annotationDefaultParamValuesHasBeenConvertedToPrimitive ) { classInfo . annotationDefaultParamValues . convertWrapperArraysToPrimitiveArrays ( classInfo ) ; classInfo . annotationDefaultParamValuesHasBeenConvertedToPrimitive = true ; } final AnnotationParameterValueList defaultParamValues = classInfo . annotationDefaultParamValues ; if ( defaultParamValues == null && annotationParamValues == null ) { return AnnotationParameterValueList . EMPTY_LIST ; } else if ( defaultParamValues == null ) { return annotationParamValues ; } else if ( annotationParamValues == null ) { return defaultParamValues ; } final Map < String , Object > allParamValues = new HashMap < > ( ) ; for ( final AnnotationParameterValue defaultParamValue : defaultParamValues ) { allParamValues . put ( defaultParamValue . getName ( ) , defaultParamValue . getValue ( ) ) ; } for ( final AnnotationParameterValue annotationParamValue : this . annotationParamValues ) { allParamValues . put ( annotationParamValue . getName ( ) , annotationParamValue . getValue ( ) ) ; } if ( classInfo . methodInfo == null ) { throw new IllegalArgumentException ( "Could not find methods for annotation " + classInfo . getName ( ) ) ; } annotationParamValuesWithDefaults = new AnnotationParameterValueList ( ) ; for ( final MethodInfo mi : classInfo . methodInfo ) { final String paramName = mi . getName ( ) ; switch ( paramName ) { case "<init>" : case "<clinit>" : case "hashCode" : case "equals" : case "toString" : case "annotationType" : break ; default : final Object paramValue = allParamValues . get ( paramName ) ; if ( paramValue != null ) { annotationParamValuesWithDefaults . add ( new AnnotationParameterValue ( paramName , paramValue ) ) ; } break ; } } } return annotationParamValuesWithDefaults ; }
Get the parameter values .
33,078
public AnnotationInfoList getAnnotationInfo ( ) { if ( ! scanResult . scanSpec . enableAnnotationInfo ) { throw new IllegalArgumentException ( "Please call ClassGraph#enableAnnotationInfo() before #scan()" ) ; } return annotationInfo == null ? AnnotationInfoList . EMPTY_LIST : AnnotationInfoList . getIndirectAnnotations ( annotationInfo , null ) ; }
Get a list of annotations on this method along with any annotation parameter values .
33,079
public boolean hasParameterAnnotation ( final String annotationName ) { for ( final MethodParameterInfo methodParameterInfo : getParameterInfo ( ) ) { if ( methodParameterInfo . hasAnnotation ( annotationName ) ) { return true ; } } return false ; }
Check if this method has a parameter with the named annotation .
33,080
public int compareTo ( final MethodInfo other ) { final int diff0 = declaringClassName . compareTo ( other . declaringClassName ) ; if ( diff0 != 0 ) { return diff0 ; } final int diff1 = name . compareTo ( other . name ) ; if ( diff1 != 0 ) { return diff1 ; } return typeDescriptorStr . compareTo ( other . typeDescriptorStr ) ; }
Sort in order of class name method name then type descriptor .
33,081
public static synchronized String getVersion ( ) { final Class < ? > cls = ClassGraph . class ; try { final String className = cls . getName ( ) ; final URL classpathResource = cls . getResource ( "/" + JarUtils . classNameToClassfilePath ( className ) ) ; if ( classpathResource != null ) { final Path absolutePackagePath = Paths . get ( classpathResource . toURI ( ) ) . getParent ( ) ; final int packagePathSegments = className . length ( ) - className . replace ( "." , "" ) . length ( ) ; Path path = absolutePackagePath ; for ( int i = 0 ; i < packagePathSegments && path != null ; i ++ ) { path = path . getParent ( ) ; } for ( int i = 0 ; i < 3 && path != null ; i ++ , path = path . getParent ( ) ) { final Path pom = path . resolve ( "pom.xml" ) ; try ( InputStream is = Files . newInputStream ( pom ) ) { final Document doc = DocumentBuilderFactory . newInstance ( ) . newDocumentBuilder ( ) . parse ( is ) ; doc . getDocumentElement ( ) . normalize ( ) ; String version = ( String ) XPathFactory . newInstance ( ) . newXPath ( ) . compile ( "/project/version" ) . evaluate ( doc , XPathConstants . STRING ) ; if ( version != null ) { version = version . trim ( ) ; if ( ! version . isEmpty ( ) ) { return version ; } } } catch ( final IOException e ) { } } } } catch ( final Exception e ) { } try ( InputStream is = cls . getResourceAsStream ( "/META-INF/maven/" + MAVEN_PACKAGE + "/" + MAVEN_ARTIFACT + "/pom.properties" ) ) { if ( is != null ) { final Properties p = new Properties ( ) ; p . load ( is ) ; final String version = p . getProperty ( "version" , "" ) . trim ( ) ; if ( ! version . isEmpty ( ) ) { return version ; } } } catch ( final IOException e ) { } final Package pkg = cls . getPackage ( ) ; if ( pkg != null ) { String version = pkg . getImplementationVersion ( ) ; if ( version == null ) { version = "" ; } version = version . trim ( ) ; if ( version . isEmpty ( ) ) { version = pkg . getSpecificationVersion ( ) ; if ( version == null ) { version = "" ; } version = version . trim ( ) ; } if ( ! version . isEmpty ( ) ) { return version ; } } return "unknown" ; }
Get the version number of ClassGraph .
33,082
private ByteBuffer getChunk ( final int chunkIdx ) throws IOException , InterruptedException { ByteBuffer chunk = chunkCache [ chunkIdx ] ; if ( chunk == null ) { final ByteBuffer byteBufferDup = zipFileSlice . physicalZipFile . getByteBuffer ( chunkIdx ) . duplicate ( ) ; chunk = chunkCache [ chunkIdx ] = byteBufferDup ; } return chunk ; }
Get the 2GB chunk of the zipfile with the given chunk index .
33,083
static int getShort ( final byte [ ] arr , final long off ) throws IndexOutOfBoundsException { final int ioff = ( int ) off ; if ( ioff < 0 || ioff > arr . length - 2 ) { throw new IndexOutOfBoundsException ( ) ; } return ( ( arr [ ioff + 1 ] & 0xff ) << 8 ) | ( arr [ ioff ] & 0xff ) ; }
Get a short from a byte array .
33,084
int getShort ( final long off ) throws IOException , InterruptedException { if ( off < 0 || off > zipFileSlice . len - 2 ) { throw new IndexOutOfBoundsException ( ) ; } if ( read ( off , scratch , 0 , 2 ) < 2 ) { throw new EOFException ( "Unexpected EOF" ) ; } return ( ( scratch [ 1 ] & 0xff ) << 8 ) | ( scratch [ 0 ] & 0xff ) ; }
Get a short from the zipfile slice .
33,085
static int getInt ( final byte [ ] arr , final long off ) throws IOException { final int ioff = ( int ) off ; if ( ioff < 0 || ioff > arr . length - 4 ) { throw new IndexOutOfBoundsException ( ) ; } return ( ( arr [ ioff + 3 ] & 0xff ) << 24 ) | ( ( arr [ ioff + 2 ] & 0xff ) << 16 ) | ( ( arr [ ioff + 1 ] & 0xff ) << 8 ) | ( arr [ ioff ] & 0xff ) ; }
Get an int from a byte array .
33,086
static long getLong ( final byte [ ] arr , final long off ) throws IOException { final int ioff = ( int ) off ; if ( ioff < 0 || ioff > arr . length - 8 ) { throw new IndexOutOfBoundsException ( ) ; } return ( ( arr [ ioff + 7 ] & 0xffL ) << 56 ) | ( ( arr [ ioff + 6 ] & 0xffL ) << 48 ) | ( ( arr [ ioff + 5 ] & 0xffL ) << 40 ) | ( ( arr [ ioff + 4 ] & 0xffL ) << 32 ) | ( ( arr [ ioff + 3 ] & 0xffL ) << 24 ) | ( ( arr [ ioff + 2 ] & 0xffL ) << 16 ) | ( ( arr [ ioff + 1 ] & 0xffL ) << 8 ) | ( arr [ ioff ] & 0xffL ) ; }
Get a long from a byte array .
33,087
long getLong ( final long off ) throws IOException , InterruptedException { if ( off < 0 || off > zipFileSlice . len - 8 ) { throw new IndexOutOfBoundsException ( ) ; } if ( read ( off , scratch , 0 , 8 ) < 8 ) { throw new EOFException ( "Unexpected EOF" ) ; } return ( ( scratch [ 7 ] & 0xffL ) << 56 ) | ( ( scratch [ 6 ] & 0xffL ) << 48 ) | ( ( scratch [ 5 ] & 0xffL ) << 40 ) | ( ( scratch [ 4 ] & 0xffL ) << 32 ) | ( ( scratch [ 3 ] & 0xffL ) << 24 ) | ( ( scratch [ 2 ] & 0xffL ) << 16 ) | ( ( scratch [ 1 ] & 0xffL ) << 8 ) | ( scratch [ 0 ] & 0xffL ) ; }
Get a long from the zipfile slice .
33,088
static String getString ( final byte [ ] arr , final long off , final int lenBytes ) throws IOException { final int ioff = ( int ) off ; if ( ioff < 0 || ioff > arr . length - lenBytes ) { throw new IndexOutOfBoundsException ( ) ; } return new String ( arr , ioff , lenBytes , StandardCharsets . UTF_8 ) ; }
Get a string from a byte array .
33,089
String getString ( final long off , final int lenBytes ) throws IOException , InterruptedException { if ( off < 0 || off > zipFileSlice . len - lenBytes ) { throw new IndexOutOfBoundsException ( ) ; } final byte [ ] scratchToUse = lenBytes <= scratch . length ? scratch : new byte [ lenBytes ] ; if ( read ( off , scratchToUse , 0 , lenBytes ) < lenBytes ) { throw new EOFException ( "Unexpected EOF" ) ; } return new String ( scratchToUse , 0 , lenBytes , StandardCharsets . UTF_8 ) ; }
Get a string from the zipfile slice .
33,090
static ReferenceTypeSignature parseReferenceTypeSignature ( final Parser parser , final String definingClassName ) throws ParseException { final ClassRefTypeSignature classTypeSignature = ClassRefTypeSignature . parse ( parser , definingClassName ) ; if ( classTypeSignature != null ) { return classTypeSignature ; } final TypeVariableSignature typeVariableSignature = TypeVariableSignature . parse ( parser , definingClassName ) ; if ( typeVariableSignature != null ) { return typeVariableSignature ; } final ArrayTypeSignature arrayTypeSignature = ArrayTypeSignature . parse ( parser , definingClassName ) ; if ( arrayTypeSignature != null ) { return arrayTypeSignature ; } return null ; }
Parse a reference type signature .
33,091
static ReferenceTypeSignature parseClassBound ( final Parser parser , final String definingClassName ) throws ParseException { parser . expect ( ':' ) ; return parseReferenceTypeSignature ( parser , definingClassName ) ; }
Parse a class bound .
33,092
public static boolean isClassfile ( final String path ) { final int len = path . length ( ) ; return len > 6 && path . regionMatches ( true , len - 6 , ".class" , 0 , 6 ) ; }
Check if the path ends with a . class extension ignoring case .
33,093
public static String getParentDirPath ( final String path , final char separator ) { final int lastSlashIdx = path . lastIndexOf ( separator ) ; if ( lastSlashIdx <= 0 ) { return "" ; } return path . substring ( 0 , lastSlashIdx ) ; }
Get the parent dir path .
33,094
public static Object getStaticFieldVal ( final Class < ? > cls , final String fieldName , final boolean throwException ) throws IllegalArgumentException { if ( cls == null || fieldName == null ) { if ( throwException ) { throw new NullPointerException ( ) ; } else { return null ; } } return getFieldVal ( cls , null , fieldName , throwException ) ; }
Get the value of the named static field in the given class or any of its superclasses . If an exception is thrown while trying to read the field value and throwException is true then IllegalArgumentException is thrown wrapping the cause otherwise this will return null . If passed a null class reference returns null unless throwException is true then throws IllegalArgumentException .
33,095
private static String getContentLocation ( final Object content ) { final File file = ( File ) ReflectionUtils . invokeMethod ( content , "getFile" , false ) ; return file != null ? file . toURI ( ) . toString ( ) : null ; }
Get the content location .
33,096
private static void addBundle ( final Object bundleWiring , final ClassLoader classLoader , final ClasspathOrder classpathOrderOut , final Set < Object > bundles , final ScanSpec scanSpec , final LogNode log ) { bundles . add ( bundleWiring ) ; final Object revision = ReflectionUtils . invokeMethod ( bundleWiring , "getRevision" , false ) ; final Object content = ReflectionUtils . invokeMethod ( revision , "getContent" , false ) ; final String location = content != null ? getContentLocation ( content ) : null ; if ( location != null ) { classpathOrderOut . addClasspathEntry ( location , classLoader , scanSpec , log ) ; final List < ? > embeddedContent = ( List < ? > ) ReflectionUtils . invokeMethod ( revision , "getContentPath" , false ) ; if ( embeddedContent != null ) { for ( final Object embedded : embeddedContent ) { if ( embedded != content ) { final String embeddedLocation = embedded != null ? getContentLocation ( embedded ) : null ; if ( embeddedLocation != null ) { classpathOrderOut . addClasspathEntry ( embeddedLocation , classLoader , scanSpec , log ) ; } } } } } }
Adds the bundle .
33,097
void toStringParamValueOnly ( final StringBuilder buf ) { if ( value == null ) { buf . append ( "null" ) ; } else { final Object paramVal = value . get ( ) ; final Class < ? > valClass = paramVal . getClass ( ) ; if ( valClass . isArray ( ) ) { buf . append ( '[' ) ; for ( int j = 0 , n = Array . getLength ( paramVal ) ; j < n ; j ++ ) { if ( j > 0 ) { buf . append ( ", " ) ; } final Object elt = Array . get ( paramVal , j ) ; buf . append ( elt == null ? "null" : elt . toString ( ) ) ; } buf . append ( ']' ) ; } else if ( paramVal instanceof String ) { buf . append ( '"' ) ; buf . append ( paramVal . toString ( ) . replace ( "\"" , "\\\"" ) . replace ( "\n" , "\\n" ) . replace ( "\r" , "\\r" ) ) ; buf . append ( '"' ) ; } else if ( paramVal instanceof Character ) { buf . append ( '\'' ) ; buf . append ( paramVal . toString ( ) . replace ( "'" , "\\'" ) . replace ( "\n" , "\\n" ) . replace ( "\r" , "\\r" ) ) ; buf . append ( '\'' ) ; } else { buf . append ( paramVal . toString ( ) ) ; } } }
To string param value only .
33,098
private static boolean addJREPath ( final File dir ) { if ( dir != null && ! dir . getPath ( ) . isEmpty ( ) && FileUtils . canRead ( dir ) && dir . isDirectory ( ) ) { final File [ ] dirFiles = dir . listFiles ( ) ; if ( dirFiles != null ) { for ( final File file : dirFiles ) { final String filePath = file . getPath ( ) ; if ( filePath . endsWith ( ".jar" ) ) { final String jarPathResolved = FastPathResolver . resolve ( FileUtils . CURR_DIR_PATH , filePath ) ; if ( jarPathResolved . endsWith ( "/rt.jar" ) ) { RT_JARS . add ( jarPathResolved ) ; } else { JRE_LIB_OR_EXT_JARS . add ( jarPathResolved ) ; } try { final File canonicalFile = file . getCanonicalFile ( ) ; final String canonicalFilePath = canonicalFile . getPath ( ) ; if ( ! canonicalFilePath . equals ( filePath ) ) { final String canonicalJarPathResolved = FastPathResolver . resolve ( FileUtils . CURR_DIR_PATH , filePath ) ; JRE_LIB_OR_EXT_JARS . add ( canonicalJarPathResolved ) ; } } catch ( IOException | SecurityException e ) { } } } return true ; } } return false ; }
Add and search a JRE path .
33,099
private static Entry < String , Integer > getManifestValue ( final byte [ ] manifest , final int startIdx ) { int curr = startIdx ; final int len = manifest . length ; while ( curr < len && manifest [ curr ] == ( byte ) ' ' ) { curr ++ ; } final int firstNonSpaceIdx = curr ; boolean isMultiLine = false ; for ( ; curr < len && ! isMultiLine ; curr ++ ) { final byte b = manifest [ curr ] ; if ( b == ( byte ) '\r' && curr < len - 1 && manifest [ curr + 1 ] == ( byte ) '\n' ) { if ( curr < len - 2 && manifest [ curr + 2 ] == ( byte ) ' ' ) { isMultiLine = true ; } break ; } else if ( b == ( byte ) '\r' || b == ( byte ) '\n' ) { if ( curr < len - 1 && manifest [ curr + 1 ] == ( byte ) ' ' ) { isMultiLine = true ; } break ; } } String val ; if ( ! isMultiLine ) { val = new String ( manifest , firstNonSpaceIdx , curr - firstNonSpaceIdx , StandardCharsets . UTF_8 ) ; } else { final ByteArrayOutputStream buf = new ByteArrayOutputStream ( ) ; curr = firstNonSpaceIdx ; for ( ; curr < len ; curr ++ ) { final byte b = manifest [ curr ] ; boolean isLineEnd ; if ( b == ( byte ) '\r' && curr < len - 1 && manifest [ curr + 1 ] == ( byte ) '\n' ) { curr += 2 ; isLineEnd = true ; } else if ( b == '\r' || b == '\n' ) { curr += 1 ; isLineEnd = true ; } else { buf . write ( b ) ; isLineEnd = false ; } if ( isLineEnd && curr < len && manifest [ curr ] != ( byte ) ' ' ) { break ; } } try { val = buf . toString ( "UTF-8" ) ; } catch ( final UnsupportedEncodingException e ) { throw ClassGraphException . newClassGraphException ( "UTF-8 encoding unsupported" , e ) ; } } return new SimpleEntry < > ( val . endsWith ( " " ) ? val . trim ( ) : val , curr ) ; }
Extract a value from the manifest and return the value as a string along with the index after the terminating newline . Manifest files support three different line terminator types and entries can be split across lines with a line terminator followed by a space .