idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
33,100
private static byte [ ] manifestKeyToBytes ( final String key ) { final byte [ ] bytes = new byte [ key . length ( ) ] ; for ( int i = 0 ; i < key . length ( ) ; i ++ ) { bytes [ i ] = ( byte ) Character . toLowerCase ( key . charAt ( i ) ) ; } return bytes ; }
Manifest key to bytes .
33,101
private static boolean keyMatchesAtPosition ( final byte [ ] manifest , final byte [ ] key , final int pos ) { if ( pos + key . length + 1 > manifest . length || manifest [ pos + key . length ] != ':' ) { return false ; } for ( int i = 0 ; i < key . length ; i ++ ) { if ( toLowerCase [ manifest [ i + pos ] ] != key [ i ] ) { return false ; } } return true ; }
Key matches at position .
33,102
public String getModuleName ( ) { String moduleName = moduleRef . getName ( ) ; if ( moduleName == null || moduleName . isEmpty ( ) ) { moduleName = moduleNameFromModuleDescriptor ; } return moduleName == null || moduleName . isEmpty ( ) ? null : moduleName ; }
Get the module name from the module reference or the module descriptor .
33,103
void addAnnotations ( final AnnotationInfoList packageAnnotations ) { if ( packageAnnotations != null && ! packageAnnotations . isEmpty ( ) ) { if ( this . annotationInfo == null ) { this . annotationInfo = new AnnotationInfoList ( packageAnnotations ) ; } else { this . annotationInfo . addAll ( packageAnnotations ) ; } } }
Add annotations found in a package descriptor classfile .
33,104
public PackageInfoList getChildren ( ) { if ( children == null ) { return PackageInfoList . EMPTY_LIST ; } final PackageInfoList childrenSorted = new PackageInfoList ( children ) ; CollectionUtils . sortIfNotEmpty ( childrenSorted , new Comparator < PackageInfo > ( ) { public int compare ( final PackageInfo o1 , final PackageInfo o2 ) { return o1 . name . compareTo ( o2 . name ) ; } } ) ; return childrenSorted ; }
The child packages of this package or the empty list if none .
33,105
static String getParentPackageName ( final String packageOrClassName ) { if ( packageOrClassName . isEmpty ( ) ) { return null ; } final int lastDotIdx = packageOrClassName . lastIndexOf ( '.' ) ; return lastDotIdx < 0 ? "" : packageOrClassName . substring ( 0 , lastDotIdx ) ; }
Get the name of the parent package of a parent or the package of the named class .
33,106
public String getPositionInfo ( ) { final int showStart = Math . max ( 0 , position - SHOW_BEFORE ) ; final int showEnd = Math . min ( string . length ( ) , position + SHOW_AFTER ) ; return "before: \"" + JSONUtils . escapeJSONString ( string . substring ( showStart , position ) ) + "\"; after: \"" + JSONUtils . escapeJSONString ( string . substring ( position , showEnd ) ) + "\"; position: " + position + "; token: \"" + token + "\"" ; }
Get the parsing context as a string for debugging .
33,107
public void expect ( final char expectedChar ) throws ParseException { final int next = getc ( ) ; if ( next != expectedChar ) { throw new ParseException ( this , "Expected '" + expectedChar + "'; got '" + ( char ) next + "'" ) ; } }
Expect the next character .
33,108
public void skipWhitespace ( ) { while ( position < string . length ( ) ) { final char c = string . charAt ( position ) ; if ( c == ' ' || c == '\n' || c == '\r' || c == '\t' ) { position ++ ; } else { break ; } } }
Skip whitespace starting at the current position .
33,109
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 ( ) ; int numDisplayedFields ; if ( includeNullValuedFields ) { numDisplayedFields = n ; } else { numDisplayedFields = 0 ; for ( final Entry < String , Object > item : items ) { if ( item . getValue ( ) != null ) { numDisplayedFields ++ ; } } } if ( objectId == null && numDisplayedFields == 0 ) { buf . append ( "{}" ) ; } else { buf . append ( prettyPrint ? "{\n" : "{" ) ; if ( objectId != null ) { if ( prettyPrint ) { JSONUtils . indent ( depth + 1 , indentWidth , buf ) ; } buf . append ( '"' ) ; buf . append ( JSONUtils . ID_KEY ) ; buf . append ( prettyPrint ? "\": " : "\":" ) ; JSONSerializer . jsonValToJSONString ( objectId , jsonReferenceToId , includeNullValuedFields , depth + 1 , indentWidth , buf ) ; if ( numDisplayedFields > 0 ) { buf . append ( ',' ) ; } if ( prettyPrint ) { buf . append ( '\n' ) ; } } for ( int i = 0 , j = 0 ; i < n ; i ++ ) { final Entry < String , Object > item = items . get ( i ) ; final Object val = item . getValue ( ) ; if ( val != null || includeNullValuedFields ) { final String key = item . getKey ( ) ; if ( key == null ) { throw new IllegalArgumentException ( "Cannot serialize JSON object with null key" ) ; } if ( prettyPrint ) { JSONUtils . indent ( depth + 1 , indentWidth , buf ) ; } buf . append ( '"' ) ; JSONUtils . escapeJSONString ( key , buf ) ; buf . append ( prettyPrint ? "\": " : "\":" ) ; JSONSerializer . jsonValToJSONString ( val , jsonReferenceToId , includeNullValuedFields , depth + 1 , indentWidth , buf ) ; if ( ++ j < numDisplayedFields ) { buf . append ( ',' ) ; } if ( prettyPrint ) { buf . append ( '\n' ) ; } } } if ( prettyPrint ) { JSONUtils . indent ( depth , indentWidth , buf ) ; } buf . append ( '}' ) ; } }
Serialize this JSONObject to a string .
33,110
private static void handleResourceLoader ( final Object resourceLoader , final ClassLoader classLoader , final ClasspathOrder classpathOrderOut , final ScanSpec scanSpec , final LogNode log ) { if ( resourceLoader == null ) { return ; } final Object root = ReflectionUtils . getFieldVal ( resourceLoader , "root" , false ) ; final File physicalFile = ( File ) ReflectionUtils . invokeMethod ( root , "getPhysicalFile" , false ) ; String path = null ; if ( physicalFile != null ) { final String name = ( String ) ReflectionUtils . invokeMethod ( root , "getName" , false ) ; if ( name != null ) { final File file = new File ( physicalFile . getParentFile ( ) , name ) ; if ( FileUtils . canRead ( file ) ) { path = file . getAbsolutePath ( ) ; } else { path = physicalFile . getAbsolutePath ( ) ; } } else { path = physicalFile . getAbsolutePath ( ) ; } } else { path = ( String ) ReflectionUtils . invokeMethod ( root , "getPathName" , false ) ; if ( path == null ) { final File file = root instanceof Path ? ( ( Path ) root ) . toFile ( ) : root instanceof File ? ( File ) root : null ; if ( file != null ) { path = file . getAbsolutePath ( ) ; } } } if ( path == null ) { final File file = ( File ) ReflectionUtils . getFieldVal ( resourceLoader , "fileOfJar" , false ) ; if ( file != null ) { path = file . getAbsolutePath ( ) ; } } if ( path != null ) { classpathOrderOut . addClasspathEntry ( path , classLoader , scanSpec , log ) ; } else { if ( log != null ) { log . log ( "Could not determine classpath for ResourceLoader: " + resourceLoader ) ; } } }
Handle a resource loader .
33,111
private static void handleRealModule ( final Object module , final Set < Object > visitedModules , final ClassLoader classLoader , final ClasspathOrder classpathOrderOut , final ScanSpec scanSpec , final LogNode log ) { if ( ! visitedModules . add ( module ) ) { return ; } ClassLoader moduleLoader = ( ClassLoader ) ReflectionUtils . invokeMethod ( module , "getClassLoader" , false ) ; if ( moduleLoader == null ) { moduleLoader = classLoader ; } final Object vfsResourceLoaders = ReflectionUtils . invokeMethod ( moduleLoader , "getResourceLoaders" , false ) ; if ( vfsResourceLoaders != null ) { for ( int i = 0 , n = Array . getLength ( vfsResourceLoaders ) ; i < n ; i ++ ) { final Object resourceLoader = Array . get ( vfsResourceLoaders , i ) ; handleResourceLoader ( resourceLoader , moduleLoader , classpathOrderOut , scanSpec , log ) ; } } }
Handle a module .
33,112
private static boolean matchesPatternList ( final String str , final List < Pattern > patterns ) { if ( patterns != null ) { for ( final Pattern pattern : patterns ) { if ( pattern . matcher ( str ) . matches ( ) ) { return true ; } } } return false ; }
Check if a string matches one of the patterns in the provided list .
33,113
private static void quoteList ( final Collection < String > coll , final StringBuilder buf ) { buf . append ( '[' ) ; boolean first = true ; for ( final String item : coll ) { if ( first ) { first = false ; } else { buf . append ( ", " ) ; } buf . append ( '"' ) ; for ( int i = 0 ; i < item . length ( ) ; i ++ ) { final char c = item . charAt ( i ) ; if ( c == '"' ) { buf . append ( "\\\"" ) ; } else { buf . append ( c ) ; } } buf . append ( '"' ) ; } buf . append ( ']' ) ; }
Quote list .
33,114
public String getModuleName ( ) { String moduleName = moduleNameFromModuleDescriptor ; if ( moduleName == null || moduleName . isEmpty ( ) ) { moduleName = moduleNameFromManifestFile ; } if ( moduleName == null || moduleName . isEmpty ( ) ) { if ( derivedAutomaticModuleName == null ) { derivedAutomaticModuleName = JarUtils . derivedAutomaticModuleName ( zipFilePath ) ; } moduleName = derivedAutomaticModuleName ; } return moduleName == null || moduleName . isEmpty ( ) ? null : moduleName ; }
Get module name from module descriptor or get the automatic module name from the manifest file or derive an automatic module name from the jar name .
33,115
String getZipFilePath ( ) { return packageRootPrefix . isEmpty ( ) ? zipFilePath : zipFilePath + "!/" + packageRootPrefix . substring ( 0 , packageRootPrefix . length ( ) - 1 ) ; }
Get the zipfile path .
33,116
private boolean filter ( final String classpathElementPath ) { if ( scanSpec . classpathElementFilters != null ) { for ( final ClasspathElementFilter filter : scanSpec . classpathElementFilters ) { if ( ! filter . includeClasspathElement ( classpathElementPath ) ) { return false ; } } } return true ; }
Test to see if a RelativePath has been filtered out by the user .
33,117
boolean addSystemClasspathEntry ( final String pathEntry , final ClassLoader classLoader ) { if ( classpathEntryUniqueResolvedPaths . add ( pathEntry ) ) { order . add ( new SimpleEntry < > ( pathEntry , classLoader ) ) ; return true ; } return false ; }
Add a system classpath entry .
33,118
private boolean addClasspathEntry ( final String pathEntry , final ClassLoader classLoader , final ScanSpec scanSpec ) { if ( scanSpec . overrideClasspath == null && ( SystemJarFinder . getJreLibOrExtJars ( ) . contains ( pathEntry ) || pathEntry . equals ( SystemJarFinder . getJreRtJarPath ( ) ) ) ) { return false ; } if ( classpathEntryUniqueResolvedPaths . add ( pathEntry ) ) { order . add ( new SimpleEntry < > ( pathEntry , classLoader ) ) ; return true ; } return false ; }
Add a classpath entry .
33,119
public boolean addClasspathEntries ( final String pathStr , final ClassLoader classLoader , final ScanSpec scanSpec , final LogNode log ) { if ( pathStr == null || pathStr . isEmpty ( ) ) { return false ; } else { final String [ ] parts = JarUtils . smartPathSplit ( pathStr ) ; if ( parts . length == 0 ) { return false ; } else { for ( final String pathElement : parts ) { addClasspathEntry ( pathElement , classLoader , scanSpec , log ) ; } return true ; } } }
Add classpath entries separated by the system path separator character .
33,120
private static TypeArgument parse ( final Parser parser , final String definingClassName ) throws ParseException { final char peek = parser . peek ( ) ; if ( peek == '*' ) { parser . expect ( '*' ) ; return new TypeArgument ( Wildcard . ANY , null ) ; } else if ( peek == '+' ) { parser . expect ( '+' ) ; final ReferenceTypeSignature typeSignature = ReferenceTypeSignature . parseReferenceTypeSignature ( parser , definingClassName ) ; if ( typeSignature == null ) { throw new ParseException ( parser , "Missing '+' type bound" ) ; } return new TypeArgument ( Wildcard . EXTENDS , typeSignature ) ; } else if ( peek == '-' ) { parser . expect ( '-' ) ; final ReferenceTypeSignature typeSignature = ReferenceTypeSignature . parseReferenceTypeSignature ( parser , definingClassName ) ; if ( typeSignature == null ) { throw new ParseException ( parser , "Missing '-' type bound" ) ; } return new TypeArgument ( Wildcard . SUPER , typeSignature ) ; } else { final ReferenceTypeSignature typeSignature = ReferenceTypeSignature . parseReferenceTypeSignature ( parser , definingClassName ) ; if ( typeSignature == null ) { throw new ParseException ( parser , "Missing type bound" ) ; } return new TypeArgument ( Wildcard . NONE , typeSignature ) ; } }
Parse a type argument .
33,121
static List < TypeArgument > parseList ( final Parser parser , final String definingClassName ) throws ParseException { if ( parser . peek ( ) == '<' ) { parser . expect ( '<' ) ; final List < TypeArgument > typeArguments = new ArrayList < > ( 2 ) ; while ( parser . peek ( ) != '>' ) { if ( ! parser . hasMore ( ) ) { throw new ParseException ( parser , "Missing '>'" ) ; } typeArguments . add ( parse ( parser , definingClassName ) ) ; } parser . expect ( '>' ) ; return typeArguments ; } else { return Collections . emptyList ( ) ; } }
Parse a list of type arguments .
33,122
private static void addBundleFile ( final Object bundlefile , final Set < Object > path , final ClassLoader classLoader , final ClasspathOrder classpathOrderOut , final ScanSpec scanSpec , final LogNode log ) { if ( bundlefile != null && path . add ( bundlefile ) ) { final Object basefile = ReflectionUtils . getFieldVal ( bundlefile , "basefile" , false ) ; if ( basefile != null ) { boolean foundClassPathElement = false ; for ( final String fieldName : FIELD_NAMES ) { final Object fieldVal = ReflectionUtils . getFieldVal ( bundlefile , fieldName , false ) ; foundClassPathElement = fieldVal != null ; if ( foundClassPathElement ) { classpathOrderOut . addClasspathEntry ( basefile . toString ( ) + "/" + fieldVal . toString ( ) , classLoader , scanSpec , log ) ; break ; } } if ( ! foundClassPathElement ) { classpathOrderOut . addClasspathEntry ( basefile . toString ( ) , classLoader , scanSpec , log ) ; } } addBundleFile ( ReflectionUtils . getFieldVal ( bundlefile , "wrapped" , false ) , path , classLoader , classpathOrderOut , scanSpec , log ) ; addBundleFile ( ReflectionUtils . getFieldVal ( bundlefile , "next" , false ) , path , classLoader , classpathOrderOut , scanSpec , log ) ; } }
Add the bundle file .
33,123
private static void addClasspathEntries ( final Object owner , final ClassLoader classLoader , final ClasspathOrder classpathOrderOut , final ScanSpec scanSpec , final LogNode log ) { final Object entries = ReflectionUtils . getFieldVal ( owner , "entries" , false ) ; if ( entries != null ) { for ( int i = 0 , n = Array . getLength ( entries ) ; i < n ; i ++ ) { final Object entry = Array . get ( entries , i ) ; final Object bundlefile = ReflectionUtils . getFieldVal ( entry , "bundlefile" , false ) ; addBundleFile ( bundlefile , new HashSet < > ( ) , classLoader , classpathOrderOut , scanSpec , log ) ; } } }
Adds the classpath entries .
33,124
static ClassTypeSignature parse ( final String typeDescriptor , final ClassInfo classInfo ) throws ParseException { final Parser parser = new Parser ( typeDescriptor ) ; final String definingClassNameNull = null ; final List < TypeParameter > typeParameters = TypeParameter . parseList ( parser , definingClassNameNull ) ; final ClassRefTypeSignature superclassSignature = ClassRefTypeSignature . parse ( parser , definingClassNameNull ) ; List < ClassRefTypeSignature > superinterfaceSignatures ; if ( parser . hasMore ( ) ) { superinterfaceSignatures = new ArrayList < > ( ) ; while ( parser . hasMore ( ) ) { final ClassRefTypeSignature superinterfaceSignature = ClassRefTypeSignature . parse ( parser , definingClassNameNull ) ; if ( superinterfaceSignature == null ) { throw new ParseException ( parser , "Could not parse superinterface signature" ) ; } superinterfaceSignatures . add ( superinterfaceSignature ) ; } } else { superinterfaceSignatures = Collections . emptyList ( ) ; } if ( parser . hasMore ( ) ) { throw new ParseException ( parser , "Extra characters at end of type descriptor" ) ; } return new ClassTypeSignature ( classInfo , typeParameters , superclassSignature , superinterfaceSignatures ) ; }
Parse a class type signature or class type descriptor .
33,125
public TypeSignature getTypeDescriptor ( ) { if ( typeDescriptorStr == null ) { return null ; } if ( typeDescriptor == null ) { try { typeDescriptor = TypeSignature . parse ( typeDescriptorStr , declaringClassName ) ; typeDescriptor . setScanResult ( scanResult ) ; } catch ( final ParseException e ) { throw new IllegalArgumentException ( e ) ; } } return typeDescriptor ; }
Returns the parsed type descriptor for the field if available .
33,126
public TypeSignature getTypeSignature ( ) { if ( typeSignatureStr == null ) { return null ; } if ( typeSignature == null ) { try { typeSignature = TypeSignature . parse ( typeSignatureStr , declaringClassName ) ; typeSignature . setScanResult ( scanResult ) ; } catch ( final ParseException e ) { throw new IllegalArgumentException ( e ) ; } } return typeSignature ; }
Returns the parsed type signature for the field if available .
33,127
public int compareTo ( final FieldInfo other ) { final int diff = declaringClassName . compareTo ( other . declaringClassName ) ; if ( diff != 0 ) { return diff ; } return name . compareTo ( other . name ) ; }
Sort in order of class name then field name .
33,128
private List < ClasspathElementModule > getModuleOrder ( final LogNode log ) throws InterruptedException { final List < ClasspathElementModule > moduleCpEltOrder = new ArrayList < > ( ) ; if ( scanSpec . overrideClasspath == null && scanSpec . overrideClassLoaders == null && scanSpec . scanModules ) { final List < ModuleRef > systemModuleRefs = classLoaderAndModuleFinder . getSystemModuleRefs ( ) ; final ClassLoader defaultClassLoader = classLoaderOrderRespectingParentDelegation != null && classLoaderOrderRespectingParentDelegation . length != 0 ? classLoaderOrderRespectingParentDelegation [ 0 ] : null ; if ( systemModuleRefs != null ) { for ( final ModuleRef systemModuleRef : systemModuleRefs ) { final String moduleName = systemModuleRef . getName ( ) ; if ( ( scanSpec . enableSystemJarsAndModules && scanSpec . moduleWhiteBlackList . whitelistAndBlacklistAreEmpty ( ) ) || scanSpec . moduleWhiteBlackList . isSpecificallyWhitelistedAndNotBlacklisted ( moduleName ) ) { final ClasspathElementModule classpathElementModule = new ClasspathElementModule ( systemModuleRef , defaultClassLoader , nestedJarHandler , scanSpec ) ; moduleCpEltOrder . add ( classpathElementModule ) ; classpathElementModule . open ( null , log ) ; } else { if ( log != null ) { log . log ( "Skipping non-whitelisted or blacklisted system module: " + moduleName ) ; } } } } final List < ModuleRef > nonSystemModuleRefs = classLoaderAndModuleFinder . getNonSystemModuleRefs ( ) ; if ( nonSystemModuleRefs != null ) { for ( final ModuleRef nonSystemModuleRef : nonSystemModuleRefs ) { String moduleName = nonSystemModuleRef . getName ( ) ; if ( moduleName == null ) { moduleName = "" ; } if ( scanSpec . moduleWhiteBlackList . isWhitelistedAndNotBlacklisted ( moduleName ) ) { final ClasspathElementModule classpathElementModule = new ClasspathElementModule ( nonSystemModuleRef , defaultClassLoader , nestedJarHandler , scanSpec ) ; moduleCpEltOrder . add ( classpathElementModule ) ; classpathElementModule . open ( null , log ) ; } else { if ( log != null ) { log . log ( "Skipping non-whitelisted or blacklisted module: " + moduleName ) ; } } } } } return moduleCpEltOrder ; }
Get the module order .
33,129
private static void findClasspathOrderRec ( final ClasspathElement currClasspathElement , final Set < ClasspathElement > visitedClasspathElts , final List < ClasspathElement > order ) { if ( visitedClasspathElts . add ( currClasspathElement ) ) { if ( ! currClasspathElement . skipClasspathElement ) { order . add ( currClasspathElement ) ; } for ( final ClasspathElement childClasspathElt : currClasspathElement . childClasspathElementsOrdered ) { findClasspathOrderRec ( childClasspathElt , visitedClasspathElts , order ) ; } } }
Recursively perform a depth - first search of jar interdependencies breaking cycles if necessary to determine the final classpath element order .
33,130
private static List < ClasspathElement > orderClasspathElements ( final Collection < Entry < Integer , ClasspathElement > > classpathEltsIndexed ) { final List < Entry < Integer , ClasspathElement > > classpathEltsIndexedOrdered = new ArrayList < > ( classpathEltsIndexed ) ; CollectionUtils . sortIfNotEmpty ( classpathEltsIndexedOrdered , INDEXED_CLASSPATH_ELEMENT_COMPARATOR ) ; final List < ClasspathElement > classpathEltsOrdered = new ArrayList < > ( classpathEltsIndexedOrdered . size ( ) ) ; for ( final Entry < Integer , ClasspathElement > ent : classpathEltsIndexedOrdered ) { classpathEltsOrdered . add ( ent . getValue ( ) ) ; } return classpathEltsOrdered ; }
Sort a collection of indexed ClasspathElements into increasing order of integer index key .
33,131
private List < ClasspathElement > findClasspathOrder ( final Set < ClasspathElement > uniqueClasspathElements , final Queue < Entry < Integer , ClasspathElement > > toplevelClasspathEltsIndexed ) { final List < ClasspathElement > toplevelClasspathEltsOrdered = orderClasspathElements ( toplevelClasspathEltsIndexed ) ; for ( final ClasspathElement classpathElt : uniqueClasspathElements ) { classpathElt . childClasspathElementsOrdered = orderClasspathElements ( classpathElt . childClasspathElementsIndexed ) ; } final Set < ClasspathElement > visitedClasspathElts = new HashSet < > ( ) ; final List < ClasspathElement > order = new ArrayList < > ( ) ; for ( final ClasspathElement toplevelClasspathElt : toplevelClasspathEltsOrdered ) { findClasspathOrderRec ( toplevelClasspathElt , visitedClasspathElts , order ) ; } return order ; }
Recursively perform a depth - first traversal of child classpath elements breaking cycles if necessary to determine the final classpath element order . This causes child classpath elements to be inserted in - place in the classpath order after the parent classpath element that contained them .
33,132
private < W > void processWorkUnits ( final Collection < W > workUnits , final LogNode log , final WorkUnitProcessor < W > workUnitProcessor ) throws InterruptedException , ExecutionException { WorkQueue . runWorkQueue ( workUnits , executorService , interruptionChecker , numParallelTasks , log , workUnitProcessor ) ; if ( log != null ) { log . addElapsedTime ( ) ; } interruptionChecker . check ( ) ; }
Process work units .
33,133
public ScanResult call ( ) throws InterruptedException , CancellationException , ExecutionException { ScanResult scanResult = null ; Exception exception = null ; final long scanStart = System . currentTimeMillis ( ) ; try { scanResult = openClasspathElementsThenScan ( ) ; if ( topLevelLog != null ) { topLevelLog . log ( "~" , String . format ( "Total time: %.3f sec" , ( System . currentTimeMillis ( ) - scanStart ) * .001 ) ) ; topLevelLog . flush ( ) ; } if ( scanResultProcessor != null ) { try { scanResultProcessor . processScanResult ( scanResult ) ; } finally { scanResult . close ( ) ; } } } catch ( final InterruptedException e ) { if ( topLevelLog != null ) { topLevelLog . log ( "~" , "Scan interrupted" ) ; } exception = e ; interruptionChecker . interrupt ( ) ; if ( failureHandler == null ) { throw e ; } } catch ( final CancellationException e ) { if ( topLevelLog != null ) { topLevelLog . log ( "~" , "Scan cancelled" ) ; } exception = e ; if ( failureHandler == null ) { throw e ; } } catch ( final ExecutionException e ) { if ( topLevelLog != null ) { topLevelLog . log ( "~" , "Uncaught exception during scan" , InterruptionChecker . getCause ( e ) ) ; } exception = e ; if ( failureHandler == null ) { throw e ; } } catch ( final RuntimeException e ) { if ( topLevelLog != null ) { topLevelLog . log ( "~" , "Uncaught exception during scan" , e ) ; } exception = e ; if ( failureHandler == null ) { throw new ExecutionException ( "Exception while scanning" , e ) ; } } finally { if ( exception != null || scanSpec . removeTemporaryFilesAfterScan ) { nestedJarHandler . close ( topLevelLog ) ; } } if ( exception != null ) { if ( topLevelLog != null ) { final Throwable cause = InterruptionChecker . getCause ( exception ) ; topLevelLog . log ( "~" , "An uncaught exception was thrown:" , cause ) ; topLevelLog . flush ( ) ; } try { failureHandler . onFailure ( exception ) ; } catch ( final Exception f ) { if ( topLevelLog != null ) { topLevelLog . log ( "~" , "The failure handler threw an exception:" , f ) ; } final ExecutionException failureHandlerException = new ExecutionException ( "Exception while calling failure handler" , f ) ; failureHandlerException . addSuppressed ( exception ) ; throw failureHandlerException ; } } return scanResult ; }
Determine the unique ordered classpath elements and run a scan looking for file or classfile matches if necessary .
33,134
public List < String > list ( ) throws SecurityException { if ( collectorsToList == null ) { throw new IllegalArgumentException ( "Could not call Collectors.toList()" ) ; } final Object resourcesStream = ReflectionUtils . invokeMethod ( moduleReader , "list" , true ) ; if ( resourcesStream == null ) { throw new IllegalArgumentException ( "Could not call moduleReader.list()" ) ; } final Object resourcesList = ReflectionUtils . invokeMethod ( resourcesStream , "collect" , collectorClass , collectorsToList , true ) ; if ( resourcesList == null ) { throw new IllegalArgumentException ( "Could not call moduleReader.list().collect(Collectors.toList())" ) ; } @ SuppressWarnings ( "unchecked" ) final List < String > resourcesListTyped = ( List < String > ) resourcesList ; return resourcesListTyped ; }
Get the list of resources accessible to a ModuleReader .
33,135
private Object openOrRead ( final String path , final boolean open ) throws SecurityException { final String methodName = open ? "open" : "read" ; final Object optionalInputStream = ReflectionUtils . invokeMethod ( moduleReader , methodName , String . class , path , true ) ; if ( optionalInputStream == null ) { throw new IllegalArgumentException ( "Got null result from moduleReader." + methodName + "(name)" ) ; } final Object inputStream = ReflectionUtils . invokeMethod ( optionalInputStream , "get" , true ) ; if ( inputStream == null ) { throw new IllegalArgumentException ( "Got null result from moduleReader." + methodName + "(name).get()" ) ; } return inputStream ; }
Use the proxied ModuleReader to open the named resource as an InputStream .
33,136
private static void findMetaAnnotations ( final AnnotationInfo ai , final AnnotationInfoList allAnnotationsOut , final Set < ClassInfo > visited ) { final ClassInfo annotationClassInfo = ai . getClassInfo ( ) ; if ( annotationClassInfo != null && annotationClassInfo . annotationInfo != null && visited . add ( annotationClassInfo ) ) { for ( final AnnotationInfo metaAnnotationInfo : annotationClassInfo . annotationInfo ) { final ClassInfo metaAnnotationClassInfo = metaAnnotationInfo . getClassInfo ( ) ; final String metaAnnotationClassName = metaAnnotationClassInfo . getName ( ) ; if ( ! metaAnnotationClassName . startsWith ( "java.lang.annotation." ) ) { allAnnotationsOut . add ( metaAnnotationInfo ) ; findMetaAnnotations ( metaAnnotationInfo , allAnnotationsOut , visited ) ; } } } }
Find the transitive closure of meta - annotations .
33,137
public boolean containsName ( final String methodName ) { for ( final MethodInfo mi : this ) { if ( mi . getName ( ) . equals ( methodName ) ) { return true ; } } return false ; }
Check whether the list contains a method with the given name .
33,138
private int read ( final int off , final int len ) throws IOException { if ( len == 0 ) { return 0 ; } if ( inputStream != null ) { return inputStream . read ( buf , off , len ) ; } else { final int bytesRemainingInBuf = byteBuffer != null ? byteBuffer . remaining ( ) : buf . length - off ; final int bytesRead = Math . max ( 0 , Math . min ( len , bytesRemainingInBuf ) ) ; if ( bytesRead == 0 ) { return - 1 ; } if ( byteBuffer != null ) { final int byteBufPositionBefore = byteBuffer . position ( ) ; try { byteBuffer . get ( buf , off , bytesRead ) ; } catch ( final BufferUnderflowException e ) { throw new IOException ( "Buffer underflow" , e ) ; } return byteBuffer . position ( ) - byteBufPositionBefore ; } else { return bytesRead ; } } }
Copy up to len bytes into buf starting at the given offset .
33,139
private void readMore ( final int bytesRequired ) throws IOException { if ( ( long ) used + ( long ) bytesRequired > FileUtils . MAX_BUFFER_SIZE ) { throw new IOException ( "File is larger than 2GB, cannot read it" ) ; } final int targetReadSize = Math . max ( bytesRequired , used == 0 ? INITIAL_BUFFER_CHUNK_SIZE : SUBSEQUENT_BUFFER_CHUNK_SIZE ) ; final int maxNewUsed = ( int ) Math . min ( ( long ) used + ( long ) targetReadSize , FileUtils . MAX_BUFFER_SIZE ) ; final int bytesToRead = maxNewUsed - used ; if ( maxNewUsed > buf . length ) { long newBufLen = buf . length ; while ( newBufLen < maxNewUsed ) { newBufLen <<= 1 ; } buf = Arrays . copyOf ( buf , ( int ) Math . min ( newBufLen , FileUtils . MAX_BUFFER_SIZE ) ) ; } int extraBytesStillNotRead = bytesToRead ; int totBytesRead = 0 ; while ( extraBytesStillNotRead > 0 ) { final int bytesRead = read ( used , extraBytesStillNotRead ) ; if ( bytesRead > 0 ) { used += bytesRead ; totBytesRead += bytesRead ; extraBytesStillNotRead -= bytesRead ; } else { break ; } } if ( totBytesRead < bytesRequired ) { throw new IOException ( "Premature EOF while reading classfile" ) ; } }
Read another chunk of from the InputStream or ByteBuffer .
33,140
public void skip ( final int bytesToSkip ) throws IOException { final int bytesToRead = Math . max ( 0 , curr + bytesToSkip - used ) ; if ( bytesToRead > 0 ) { readMore ( bytesToRead ) ; } curr += bytesToSkip ; }
Skip the given number of bytes .
33,141
public List < String > getPaths ( ) { final List < String > resourcePaths = new ArrayList < > ( this . size ( ) ) ; for ( final Resource resource : this ) { resourcePaths . add ( resource . getPath ( ) ) ; } return resourcePaths ; }
Get the paths of all resources in this list relative to the package root .
33,142
public static ClassGraphException newClassGraphException ( final String message , final Throwable cause ) throws ClassGraphException { return new ClassGraphException ( message , cause ) ; }
Static factory method to stop IDEs from auto - completing ClassGraphException after new ClassGraph .
33,143
static ArrayTypeSignature parse ( final Parser parser , final String definingClassName ) throws ParseException { int numArrayDims = 0 ; while ( parser . peek ( ) == '[' ) { numArrayDims ++ ; parser . next ( ) ; } if ( numArrayDims > 0 ) { final TypeSignature elementTypeSignature = TypeSignature . parse ( parser , definingClassName ) ; if ( elementTypeSignature == null ) { throw new ParseException ( parser , "elementTypeSignature == null" ) ; } return new ArrayTypeSignature ( elementTypeSignature , numArrayDims ) ; } else { return null ; } }
Parses the array type signature .
33,144
public static String normalizeURLPath ( final String urlPath ) { String urlPathNormalized = urlPath ; if ( ! urlPathNormalized . startsWith ( "jrt:" ) && ! urlPathNormalized . startsWith ( "http://" ) && ! urlPathNormalized . startsWith ( "https://" ) ) { urlPathNormalized = urlPathNormalized . replace ( "/!" , "!" ) . replace ( "!/" , "!" ) . replace ( "!" , "!/" ) ; if ( ! urlPathNormalized . startsWith ( "file:" ) && ! urlPathNormalized . startsWith ( "jar:" ) ) { urlPathNormalized = "file:" + urlPathNormalized ; } if ( urlPathNormalized . contains ( "!" ) && ! urlPathNormalized . startsWith ( "jar:" ) ) { urlPathNormalized = "jar:" + urlPathNormalized ; } } return encodePath ( urlPathNormalized ) ; }
Normalize a URL path so that it can be fed into the URL or URI constructor .
33,145
public boolean canGetAsSlice ( ) throws IOException , InterruptedException { final long dataStartOffsetWithinPhysicalZipFile = getEntryDataStartOffsetWithinPhysicalZipFile ( ) ; return ! isDeflated && dataStartOffsetWithinPhysicalZipFile / FileUtils . MAX_BUFFER_SIZE == ( dataStartOffsetWithinPhysicalZipFile + uncompressedSize ) / FileUtils . MAX_BUFFER_SIZE ; }
True if the entire zip entry can be opened as a single ByteBuffer slice .
33,146
public byte [ ] load ( ) throws IOException , InterruptedException { try ( InputStream is = open ( ) ) { return FileUtils . readAllBytesAsArray ( is , uncompressedSize ) ; } }
Load the content of the zip entry and return it as a byte array .
33,147
public int compareTo ( final FastZipEntry o ) { final int diff0 = o . version - this . version ; if ( diff0 != 0 ) { return diff0 ; } final int diff1 = entryNameUnversioned . compareTo ( o . entryNameUnversioned ) ; if ( diff1 != 0 ) { return diff1 ; } final int diff2 = entryName . compareTo ( o . entryName ) ; if ( diff2 != 0 ) { return diff2 ; } final long diff3 = locHeaderPos - o . locHeaderPos ; return diff3 < 0L ? - 1 : diff3 > 0L ? 1 : 0 ; }
Sort in decreasing order of version number then lexicographically increasing order of unversioned entry path .
33,148
private static boolean hasTypeVariables ( final Type type ) { if ( type instanceof TypeVariable < ? > || type instanceof GenericArrayType ) { return true ; } else if ( type instanceof ParameterizedType ) { for ( final Type arg : ( ( ParameterizedType ) type ) . getActualTypeArguments ( ) ) { if ( hasTypeVariables ( arg ) ) { return true ; } } } return false ; }
Check if the type has type variables .
33,149
public Constructor < ? > getConstructorForFieldTypeWithSizeHint ( final Type fieldTypeFullyResolved , final ClassFieldCache classFieldCache ) { if ( ! isTypeVariable ) { return constructorForFieldTypeWithSizeHint ; } else { final Class < ? > fieldRawTypeFullyResolved = JSONUtils . getRawType ( fieldTypeFullyResolved ) ; if ( ! Collection . class . isAssignableFrom ( fieldRawTypeFullyResolved ) && ! Map . class . isAssignableFrom ( fieldRawTypeFullyResolved ) ) { return null ; } return classFieldCache . getConstructorWithSizeHintForConcreteTypeOf ( fieldRawTypeFullyResolved ) ; } }
Get the constructor with size hint for the field type .
33,150
public Constructor < ? > getDefaultConstructorForFieldType ( final Type fieldTypeFullyResolved , final ClassFieldCache classFieldCache ) { if ( ! isTypeVariable ) { return defaultConstructorForFieldType ; } else { final Class < ? > fieldRawTypeFullyResolved = JSONUtils . getRawType ( fieldTypeFullyResolved ) ; return classFieldCache . getDefaultConstructorForConcreteTypeOf ( fieldRawTypeFullyResolved ) ; } }
Get the default constructor for the field type .
33,151
private static void appendPathElt ( final Object pathElt , final StringBuilder buf ) { if ( buf . length ( ) > 0 ) { buf . append ( File . pathSeparatorChar ) ; } final String path = File . separatorChar == '\\' ? pathElt . toString ( ) : pathElt . toString ( ) . replaceAll ( File . pathSeparator , "\\" + File . pathSeparator ) ; buf . append ( path ) ; }
Append a path element to a buffer .
33,152
public static String leafName ( final String path ) { final int bangIdx = path . indexOf ( '!' ) ; final int endIdx = bangIdx >= 0 ? bangIdx : path . length ( ) ; int leafStartIdx = 1 + ( File . separatorChar == '/' ? path . lastIndexOf ( '/' , endIdx ) : Math . max ( path . lastIndexOf ( '/' , endIdx ) , path . lastIndexOf ( File . separatorChar , endIdx ) ) ) ; int sepIdx = path . indexOf ( NestedJarHandler . TEMP_FILENAME_LEAF_SEPARATOR ) ; if ( sepIdx >= 0 ) { sepIdx += NestedJarHandler . TEMP_FILENAME_LEAF_SEPARATOR . length ( ) ; } leafStartIdx = Math . max ( leafStartIdx , sepIdx ) ; leafStartIdx = Math . min ( leafStartIdx , endIdx ) ; return path . substring ( leafStartIdx , endIdx ) ; }
Returns the leafname of a path after first stripping off everything after the first ! if present .
33,153
public static String classfilePathToClassName ( final String classfilePath ) { if ( ! classfilePath . endsWith ( ".class" ) ) { throw new IllegalArgumentException ( "Classfile path does not end with \".class\": " + classfilePath ) ; } return classfilePath . substring ( 0 , classfilePath . length ( ) - 6 ) . replace ( '/' , '.' ) ; }
Convert a classfile path to the corresponding class name .
33,154
static BaseTypeSignature parse ( final Parser parser ) { switch ( parser . peek ( ) ) { case 'B' : parser . next ( ) ; return new BaseTypeSignature ( "byte" ) ; case 'C' : parser . next ( ) ; return new BaseTypeSignature ( "char" ) ; case 'D' : parser . next ( ) ; return new BaseTypeSignature ( "double" ) ; case 'F' : parser . next ( ) ; return new BaseTypeSignature ( "float" ) ; case 'I' : parser . next ( ) ; return new BaseTypeSignature ( "int" ) ; case 'J' : parser . next ( ) ; return new BaseTypeSignature ( "long" ) ; case 'S' : parser . next ( ) ; return new BaseTypeSignature ( "short" ) ; case 'Z' : parser . next ( ) ; return new BaseTypeSignature ( "boolean" ) ; case 'V' : parser . next ( ) ; return new BaseTypeSignature ( "void" ) ; default : return null ; } }
Parse a base type .
33,155
private static String getPath ( final Object classpath ) { final Object container = ReflectionUtils . getFieldVal ( classpath , "container" , false ) ; if ( container == null ) { return "" ; } final Object delegate = ReflectionUtils . getFieldVal ( container , "delegate" , false ) ; if ( delegate == null ) { return "" ; } final String path = ( String ) ReflectionUtils . getFieldVal ( delegate , "path" , false ) ; if ( path != null && path . length ( ) > 0 ) { return path ; } final Object base = ReflectionUtils . getFieldVal ( delegate , "base" , false ) ; if ( base == null ) { return "" ; } final Object archiveFile = ReflectionUtils . getFieldVal ( base , "archiveFile" , false ) ; if ( archiveFile != null ) { final File file = ( File ) archiveFile ; return file . getAbsolutePath ( ) ; } return "" ; }
Get the path from a classpath object .
33,156
Set < String > findReferencedClassNames ( ) { final Set < String > allReferencedClassNames = new LinkedHashSet < > ( ) ; findReferencedClassNames ( allReferencedClassNames ) ; allReferencedClassNames . remove ( "java.lang.Object" ) ; return allReferencedClassNames ; }
Get the names of all referenced classes .
33,157
private static Map < CharSequence , Object > getInitialIdToObjectMap ( final Object objectInstance , final Object parsedJSON ) { final Map < CharSequence , Object > idToObjectInstance = new HashMap < > ( ) ; if ( parsedJSON instanceof JSONObject ) { final JSONObject itemJsonObject = ( JSONObject ) parsedJSON ; if ( ! itemJsonObject . items . isEmpty ( ) ) { final Entry < String , Object > firstItem = itemJsonObject . items . get ( 0 ) ; if ( firstItem . getKey ( ) . equals ( JSONUtils . ID_KEY ) ) { final Object firstItemValue = firstItem . getValue ( ) ; if ( firstItemValue == null || ! CharSequence . class . isAssignableFrom ( firstItemValue . getClass ( ) ) ) { idToObjectInstance . put ( ( CharSequence ) firstItemValue , objectInstance ) ; } } } } return idToObjectInstance ; }
Set up the initial mapping from id to object by adding the id of the toplevel object if it has an id field in JSON .
33,158
private static < T > T deserializeObject ( final Class < T > expectedType , final String json , final ClassFieldCache classFieldCache ) throws IllegalArgumentException { Object parsedJSON ; try { parsedJSON = JSONParser . parseJSON ( json ) ; } catch ( final ParseException e ) { throw new IllegalArgumentException ( "Could not parse JSON" , e ) ; } T objectInstance ; try { final Constructor < ? > constructor = classFieldCache . getDefaultConstructorForConcreteTypeOf ( expectedType ) ; @ SuppressWarnings ( "unchecked" ) final T newInstance = ( T ) constructor . newInstance ( ) ; objectInstance = newInstance ; } catch ( final ReflectiveOperationException | SecurityException e ) { throw new IllegalArgumentException ( "Could not construct object of type " + expectedType . getName ( ) , e ) ; } final List < Runnable > collectionElementAdders = new ArrayList < > ( ) ; populateObjectFromJsonObject ( objectInstance , expectedType , parsedJSON , classFieldCache , getInitialIdToObjectMap ( objectInstance , parsedJSON ) , collectionElementAdders ) ; for ( final Runnable runnable : collectionElementAdders ) { runnable . run ( ) ; } return objectInstance ; }
Deserialize JSON to a new object graph with the root object of the specified expected type using or reusing the given type cache . Does not work for generic types since it is not possible to obtain the generic type of a Class reference .
33,159
public static < T > T deserializeObject ( final Class < T > expectedType , final String json ) throws IllegalArgumentException { final ClassFieldCache classFieldCache = new ClassFieldCache ( true , false ) ; return deserializeObject ( expectedType , json , classFieldCache ) ; }
Deserialize JSON to a new object graph with the root object of the specified expected type . Does not work for generic types since it is not possible to obtain the generic type of a Class reference .
33,160
private static void findLayerOrder ( final Object layer , final Set < Object > layerVisited , final Set < Object > parentLayers , final Deque < Object > layerOrderOut ) { if ( layerVisited . add ( layer ) ) { @ SuppressWarnings ( "unchecked" ) final List < Object > parents = ( List < Object > ) ReflectionUtils . invokeMethod ( layer , "parents" , true ) ; if ( parents != null ) { parentLayers . addAll ( parents ) ; for ( final Object parent : parents ) { findLayerOrder ( parent , layerVisited , parentLayers , layerOrderOut ) ; } } layerOrderOut . push ( layer ) ; } }
Recursively find the topological sort order of ancestral layers .
33,161
private static List < ModuleRef > findModuleRefs ( final LinkedHashSet < Object > layers , final ScanSpec scanSpec , final LogNode log ) { if ( layers . isEmpty ( ) ) { return Collections . emptyList ( ) ; } final Deque < Object > layerOrder = new ArrayDeque < > ( ) ; final Set < Object > parentLayers = new HashSet < > ( ) ; for ( final Object layer : layers ) { findLayerOrder ( layer , new HashSet < > ( ) , parentLayers , layerOrder ) ; } if ( scanSpec . addedModuleLayers != null ) { for ( final Object layer : scanSpec . addedModuleLayers ) { findLayerOrder ( layer , new HashSet < > ( ) , parentLayers , layerOrder ) ; } } List < Object > layerOrderFinal ; if ( scanSpec . ignoreParentModuleLayers ) { layerOrderFinal = new ArrayList < > ( ) ; for ( final Object layer : layerOrder ) { if ( ! parentLayers . contains ( layer ) ) { layerOrderFinal . add ( layer ) ; } } } else { layerOrderFinal = new ArrayList < > ( layerOrder ) ; } final Set < Object > addedModules = new HashSet < > ( ) ; final LinkedHashSet < ModuleRef > moduleRefOrder = new LinkedHashSet < > ( ) ; for ( final Object layer : layerOrderFinal ) { final Object configuration = ReflectionUtils . invokeMethod ( layer , "configuration" , true ) ; if ( configuration != null ) { @ SuppressWarnings ( "unchecked" ) final Set < Object > modules = ( Set < Object > ) ReflectionUtils . invokeMethod ( configuration , "modules" , true ) ; if ( modules != null ) { final List < ModuleRef > modulesInLayer = new ArrayList < > ( ) ; for ( final Object module : modules ) { final Object moduleReference = ReflectionUtils . invokeMethod ( module , "reference" , true ) ; if ( moduleReference != null && addedModules . add ( moduleReference ) ) { try { modulesInLayer . add ( new ModuleRef ( moduleReference , layer ) ) ; } catch ( final IllegalArgumentException e ) { if ( log != null ) { log . log ( "Exception while creating ModuleRef for module " + moduleReference , e ) ; } } } } CollectionUtils . sortIfNotEmpty ( modulesInLayer ) ; moduleRefOrder . addAll ( modulesInLayer ) ; } } } return new ArrayList < > ( moduleRefOrder ) ; }
Get all visible ModuleReferences in a list of layers .
33,162
static ClassRefTypeSignature parse ( final Parser parser , final String definingClassName ) throws ParseException { if ( parser . peek ( ) == 'L' ) { parser . next ( ) ; if ( ! TypeUtils . getIdentifierToken ( parser , '/' , '.' ) ) { throw new ParseException ( parser , "Could not parse identifier token" ) ; } final String className = parser . currToken ( ) ; final List < TypeArgument > typeArguments = TypeArgument . parseList ( parser , definingClassName ) ; List < String > suffixes ; List < List < TypeArgument > > suffixTypeArguments ; if ( parser . peek ( ) == '.' ) { suffixes = new ArrayList < > ( ) ; suffixTypeArguments = new ArrayList < > ( ) ; while ( parser . peek ( ) == '.' ) { parser . expect ( '.' ) ; if ( ! TypeUtils . getIdentifierToken ( parser , '/' , '.' ) ) { throw new ParseException ( parser , "Could not parse identifier token" ) ; } suffixes . add ( parser . currToken ( ) ) ; suffixTypeArguments . add ( TypeArgument . parseList ( parser , definingClassName ) ) ; } } else { suffixes = Collections . emptyList ( ) ; suffixTypeArguments = Collections . emptyList ( ) ; } parser . expect ( ';' ) ; return new ClassRefTypeSignature ( className , typeArguments , suffixes , suffixTypeArguments ) ; } else { return null ; } }
Parse a class type signature .
33,163
private static boolean isParentFirstStrategy ( final ClassLoader classRealmInstance ) { final Object strategy = ReflectionUtils . getFieldVal ( classRealmInstance , "strategy" , false ) ; if ( strategy != null ) { final String strategyClassName = strategy . getClass ( ) . getName ( ) ; if ( strategyClassName . equals ( "org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy" ) || strategyClassName . equals ( "org.codehaus.plexus.classworlds.strategy.OsgiBundleStrategy" ) ) { return false ; } } return true ; }
Checks if is this classloader uses a parent - first strategy .
33,164
public static boolean startsWith ( Msg msg , String data , boolean includeLength ) { final int length = data . length ( ) ; assert ( length < 256 ) ; int start = includeLength ? 1 : 0 ; if ( msg . size ( ) < length + start ) { return false ; } boolean comparison = includeLength ? length == ( msg . get ( 0 ) & 0xff ) : true ; if ( comparison ) { for ( int idx = start ; idx < length ; ++ idx ) { comparison = ( msg . get ( idx ) == data . charAt ( idx - start ) ) ; if ( ! comparison ) { break ; } } } return comparison ; }
Checks if the message starts with the given string .
33,165
public void write ( final T value , boolean incomplete ) { queue . push ( value ) ; if ( ! incomplete ) { f = queue . backPos ( ) ; } }
flushed down the stream .
33,166
public T unwrite ( ) { if ( f == queue . backPos ( ) ) { return null ; } queue . unpush ( ) ; return queue . back ( ) ; }
item exists false otherwise .
33,167
public boolean flush ( ) { if ( w == f ) { return true ; } if ( ! c . compareAndSet ( w , f ) ) { c . set ( f ) ; w = f ; return false ; } w = f ; return true ; }
wake the reader up before using the pipe again .
33,168
public boolean checkRead ( ) { int h = queue . frontPos ( ) ; if ( h != r ) { return true ; } if ( c . compareAndSet ( h , - 1 ) ) { } else { r = c . get ( ) ; } if ( h == r || r == - 1 ) { return false ; } return true ; }
Check whether item is available for reading .
33,169
public ByteBuffer getBuffer ( ) { if ( toRead >= bufsize ) { zeroCopy = true ; return readPos . duplicate ( ) ; } else { zeroCopy = false ; buf . clear ( ) ; return buf ; } }
Returns a buffer to be filled with binary data .
33,170
public Step . Result decode ( ByteBuffer data , int size , ValueReference < Integer > processed ) { processed . set ( 0 ) ; if ( zeroCopy ) { assert ( size <= toRead ) ; readPos . position ( readPos . position ( ) + size ) ; toRead -= size ; processed . set ( size ) ; while ( readPos . remaining ( ) == 0 ) { Step . Result result = next . apply ( ) ; if ( result != Step . Result . MORE_DATA ) { return result ; } } return Step . Result . MORE_DATA ; } while ( processed . get ( ) < size ) { int toCopy = Math . min ( toRead , size - processed . get ( ) ) ; int limit = data . limit ( ) ; data . limit ( data . position ( ) + toCopy ) ; readPos . put ( data ) ; data . limit ( limit ) ; toRead -= toCopy ; processed . set ( processed . get ( ) + toCopy ) ; while ( readPos . remaining ( ) == 0 ) { Step . Result result = next . apply ( ) ; if ( result != Step . Result . MORE_DATA ) { return result ; } } } return Step . Result . MORE_DATA ; }
bytes actually processed .
33,171
public boolean rm ( Msg msg , int start , int size ) { if ( size == 0 ) { if ( refcnt == 0 ) { return false ; } refcnt -- ; return refcnt == 0 ; } assert ( msg != null ) ; byte c = msg . get ( start ) ; if ( count == 0 || c < min || c >= min + count ) { return false ; } Trie nextNode = count == 1 ? next [ 0 ] : next [ c - min ] ; if ( nextNode == null ) { return false ; } boolean ret = nextNode . rm ( msg , start + 1 , size - 1 ) ; if ( nextNode . isRedundant ( ) ) { assert ( count > 0 ) ; if ( count == 1 ) { next = null ; count = 0 ; -- liveNodes ; assert ( liveNodes == 0 ) ; } else { next [ c - min ] = null ; assert ( liveNodes > 1 ) ; -- liveNodes ; if ( liveNodes == 1 ) { Trie node = null ; if ( c == min ) { node = next [ count - 1 ] ; min += count - 1 ; } else if ( c == min + count - 1 ) { node = next [ 0 ] ; } assert ( node != null ) ; next = new Trie [ ] { node } ; count = 1 ; } else if ( c == min ) { byte newMin = min ; for ( int i = 1 ; i < count ; ++ i ) { if ( next [ i ] != null ) { newMin = ( byte ) ( i + min ) ; break ; } } assert ( newMin != min ) ; assert ( newMin > min ) ; assert ( count > newMin - min ) ; count = count - ( newMin - min ) ; next = realloc ( next , count , true ) ; min = newMin ; } else if ( c == min + count - 1 ) { int newCount = count ; for ( int i = 1 ; i < count ; ++ i ) { if ( next [ count - 1 - i ] != null ) { newCount = count - i ; break ; } } assert ( newCount != count ) ; count = newCount ; next = realloc ( next , count , false ) ; } } } return ret ; }
removed from the trie .
33,172
public boolean check ( ByteBuffer data ) { assert ( data != null ) ; int size = data . limit ( ) ; Trie current = this ; int start = 0 ; while ( true ) { if ( current . refcnt > 0 ) { return true ; } if ( size == 0 ) { return false ; } byte c = data . get ( start ) ; if ( c < current . min || c >= current . min + current . count ) { return false ; } if ( current . count == 1 ) { current = current . next [ 0 ] ; } else { current = current . next [ c - current . min ] ; if ( current == null ) { return false ; } } start ++ ; size -- ; } }
Check whether particular key is in the trie .
33,173
public ZMsg duplicate ( ) { if ( frames . isEmpty ( ) ) { return null ; } else { ZMsg msg = new ZMsg ( ) ; for ( ZFrame f : frames ) { msg . add ( f . duplicate ( ) ) ; } return msg ; } }
Creates copy of this ZMsg . Also duplicates all frame content .
33,174
public ZMsg wrap ( ZFrame frame ) { if ( frame != null ) { push ( new ZFrame ( "" ) ) ; push ( frame ) ; } return this ; }
Push frame plus empty frame to front of message before 1st frame . Message takes ownership of frame will destroy it when message is sent .
33,175
public static ZMsg recvMsg ( Socket socket , boolean wait ) { return recvMsg ( socket , wait ? 0 : ZMQ . DONTWAIT ) ; }
Receives message from socket returns ZMsg object or null if the recv was interrupted .
33,176
public static ZMsg recvMsg ( Socket socket , int flag ) { if ( socket == null ) { throw new IllegalArgumentException ( "socket is null" ) ; } ZMsg msg = new ZMsg ( ) ; while ( true ) { ZFrame f = ZFrame . recvFrame ( socket , flag ) ; if ( f == null ) { msg . destroy ( ) ; msg = null ; break ; } msg . add ( f ) ; if ( ! f . hasMore ( ) ) { break ; } } return msg ; }
Receives message from socket returns ZMsg object or null if the recv was interrupted . Setting the flag to ZMQ . DONTWAIT does a non - blocking recv .
33,177
public static boolean save ( ZMsg msg , DataOutputStream file ) { if ( msg == null ) { return false ; } try { file . writeInt ( msg . size ( ) ) ; if ( msg . size ( ) > 0 ) { for ( ZFrame f : msg ) { file . writeInt ( f . size ( ) ) ; file . write ( f . getData ( ) ) ; } } return true ; } catch ( IOException e ) { return false ; } }
Save message to an open data output stream .
33,178
public static ZMsg newStringMsg ( String ... strings ) { ZMsg msg = new ZMsg ( ) ; for ( String data : strings ) { msg . addString ( data ) ; } return msg ; }
Create a new ZMsg from one or more Strings
33,179
public ZMsg dump ( Appendable out ) { try { StringWriter sw = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( sw ) ; pw . printf ( "--------------------------------------\n" ) ; for ( ZFrame frame : frames ) { pw . printf ( "[%03d] %s\n" , frame . size ( ) , frame . toString ( ) ) ; } out . append ( sw . getBuffer ( ) ) ; sw . close ( ) ; } catch ( IOException e ) { throw new RuntimeException ( "Message dump exception " + super . toString ( ) , e ) ; } return this ; }
Dump the message in human readable format . This should only be used for debugging and tracing inefficient in handling large messages .
33,180
protected ZAgent agent ( Socket phone , String secret ) { return ZAgent . Creator . create ( phone , secret ) ; }
Creates a new agent for the star .
33,181
public Ticket add ( long delay , TimerHandler handler , Object ... args ) { if ( handler == null ) { return null ; } Utils . checkArgument ( delay > 0 , "Delay of a ticket has to be strictly greater than 0" ) ; final Ticket ticket = new Ticket ( this , now ( ) , delay , handler , args ) ; insert ( ticket ) ; return ticket ; }
Add ticket to the set .
33,182
public long timeout ( ) { if ( tickets . isEmpty ( ) ) { return - 1 ; } sortIfNeeded ( ) ; Ticket first = tickets . get ( 0 ) ; return first . start - now ( ) + first . delay ; }
Returns the time in millisecond until the next ticket .
33,183
public int execute ( ) { int executed = 0 ; final long now = now ( ) ; sortIfNeeded ( ) ; Set < Ticket > cancelled = new HashSet < > ( ) ; for ( Ticket ticket : this . tickets ) { if ( now - ticket . start < ticket . delay ) { break ; } if ( ! ticket . alive ) { cancelled . add ( ticket ) ; continue ; } ticket . alive = false ; cancelled . add ( ticket ) ; ticket . handler . time ( ticket . args ) ; ++ executed ; } for ( int idx = tickets . size ( ) ; idx -- > 0 ; ) { Ticket ticket = tickets . get ( idx ) ; if ( ticket . alive ) { break ; } cancelled . add ( ticket ) ; } this . tickets . removeAll ( cancelled ) ; cancelled . clear ( ) ; return executed ; }
Execute the tickets .
33,184
private NetProtocol checkProtocol ( String protocol ) { NetProtocol proto = NetProtocol . getProtocol ( protocol ) ; if ( proto == null || ! proto . valid ) { errno . set ( ZError . EPROTONOSUPPORT ) ; return proto ; } if ( ! proto . compatible ( options . type ) ) { errno . set ( ZError . ENOCOMPATPROTO ) ; return null ; } return proto ; }
bind is available and compatible with the socket type .
33,185
private void addEndpoint ( String addr , Own endpoint , Pipe pipe ) { launchChild ( endpoint ) ; endpoints . insert ( addr , new EndpointPipe ( endpoint , pipe ) ) ; }
Creates new endpoint ID and adds the endpoint to the map .
33,186
final void startReaping ( Poller poller ) { this . poller = poller ; SelectableChannel fd = mailbox . getFd ( ) ; handle = this . poller . addHandle ( fd , this ) ; this . poller . setPollIn ( handle ) ; terminate ( ) ; checkDestroy ( ) ; }
its poller .
33,187
private boolean processCommands ( int timeout , boolean throttle ) { Command cmd ; if ( timeout != 0 ) { cmd = mailbox . recv ( timeout ) ; } else { long tsc = 0 ; if ( tsc != 0 && throttle ) { if ( tsc >= lastTsc && tsc - lastTsc <= Config . MAX_COMMAND_DELAY . getValue ( ) ) { return true ; } lastTsc = tsc ; } cmd = mailbox . recv ( 0 ) ; } while ( cmd != null ) { cmd . process ( ) ; cmd = mailbox . recv ( 0 ) ; } if ( errno . get ( ) == ZError . EINTR ) { return false ; } assert ( errno . get ( ) == ZError . EAGAIN ) : errno ; if ( ctxTerminated ) { errno . set ( ZError . ETERM ) ; return false ; } return true ; }
in a predefined time period .
33,188
private void extractFlags ( Msg msg ) { if ( msg . isIdentity ( ) ) { assert ( options . recvIdentity ) ; } rcvmore = msg . hasMore ( ) ; }
to be later retrieved by getSocketOpt .
33,189
public String getAddress ( ) { if ( ( ( InetSocketAddress ) address . address ( ) ) . getPort ( ) == 0 ) { return address ( address ) ; } return address . toString ( ) ; }
Get the bound address for use with wildcards
33,190
public boolean pathExists ( String path ) { String [ ] pathElements = path . split ( "/" ) ; ZConfig current = this ; for ( String pathElem : pathElements ) { if ( pathElem . isEmpty ( ) ) { continue ; } current = current . children . get ( pathElem ) ; if ( current == null ) { return false ; } } return true ; }
check if a value - path exists
33,191
public String [ ] keypairZ85 ( ) { String [ ] pair = new String [ 2 ] ; byte [ ] publicKey = new byte [ Size . PUBLICKEY . bytes ( ) ] ; byte [ ] secretKey = new byte [ Size . SECRETKEY . bytes ( ) ] ; int rc = curve25519xsalsa20poly1305 . crypto_box_keypair ( publicKey , secretKey ) ; assert ( rc == 0 ) ; pair [ 0 ] = Z85 . encode ( publicKey , Size . PUBLICKEY . bytes ( ) ) ; pair [ 1 ] = Z85 . encode ( secretKey , Size . SECRETKEY . bytes ( ) ) ; return pair ; }
Generates a pair of Z85 - encoded keys for use with this class .
33,192
public byte [ ] [ ] keypair ( ) { byte [ ] [ ] pair = new byte [ 2 ] [ ] ; byte [ ] publicKey = new byte [ Size . PUBLICKEY . bytes ( ) ] ; byte [ ] secretKey = new byte [ Size . SECRETKEY . bytes ( ) ] ; int rc = curve25519xsalsa20poly1305 . crypto_box_keypair ( publicKey , secretKey ) ; assert ( rc == 0 ) ; pair [ 0 ] = publicKey ; pair [ 1 ] = secretKey ; return pair ; }
Generates a pair of keys for use with this class .
33,193
private void error ( ErrorReason error ) { if ( options . rawSocket ) { Msg terminator = new Msg ( ) ; processMsg . apply ( terminator ) ; } assert ( session != null ) ; socket . eventDisconnected ( endpoint , fd ) ; session . flush ( ) ; session . engineError ( error ) ; unplug ( ) ; destroy ( ) ; }
Function to handle network disconnections .
33,194
private int write ( ByteBuffer outbuf ) { int nbytes ; try { nbytes = fd . write ( outbuf ) ; if ( nbytes == 0 ) { errno . set ( ZError . EAGAIN ) ; } } catch ( IOException e ) { errno . set ( ZError . ENOTCONN ) ; nbytes = - 1 ; } return nbytes ; }
of error or orderly shutdown by the other peer - 1 is returned .
33,195
private int read ( ByteBuffer buf ) { int nbytes ; try { nbytes = fd . read ( buf ) ; if ( nbytes == - 1 ) { errno . set ( ZError . ENOTCONN ) ; } else if ( nbytes == 0 ) { if ( ! fd . isBlocking ( ) ) { errno . set ( ZError . EAGAIN ) ; nbytes = - 1 ; } } } catch ( IOException e ) { errno . set ( ZError . ENOTCONN ) ; nbytes = - 1 ; } return nbytes ; }
Zero indicates the peer has closed the connection .
33,196
public boolean sendAndDestroy ( Socket socket , int flags ) { boolean ret = send ( socket , flags ) ; if ( ret ) { destroy ( ) ; } return ret ; }
Sends frame to socket if it contains data . Use this method to send a frame and destroy the data after .
33,197
public boolean hasSameData ( ZFrame other ) { if ( other == null ) { return false ; } if ( size ( ) == other . size ( ) ) { return Arrays . equals ( data , other . data ) ; } return false ; }
Returns true if both frames have byte - for byte identical data
33,198
private byte [ ] recv ( Socket socket , int flags ) { Utils . checkArgument ( socket != null , "socket parameter must not be null" ) ; data = socket . recv ( flags ) ; more = socket . hasReceiveMore ( ) ; return data ; }
Internal method to call recv on the socket . Does not trap any ZMQExceptions but expects caling routine to handle them .
33,199
public static ZFrame recvFrame ( Socket socket , int flags ) { ZFrame f = new ZFrame ( ) ; byte [ ] data = f . recv ( socket , flags ) ; if ( data == null ) { return null ; } return f ; }
Receive a new frame off the socket Returns newly - allocated frame or null if there was no input waiting or if the read was interrupted .