idx
int64 0
165k
| question
stringlengths 73
4.15k
| target
stringlengths 5
918
| len_question
int64 21
890
| len_target
int64 3
255
|
|---|---|---|---|---|
156,500
|
private static void addClasspathEntries ( final Object owner , final ClassLoader classLoader , final ClasspathOrder classpathOrderOut , final ScanSpec scanSpec , final LogNode log ) { // type ClasspathEntry[] final Object entries = ReflectionUtils . getFieldVal ( owner , "entries" , false ) ; if ( entries != null ) { for ( int i = 0 , n = Array . getLength ( entries ) ; i < n ; i ++ ) { // type ClasspathEntry final Object entry = Array . get ( entries , i ) ; // type BundleFile final Object bundlefile = ReflectionUtils . getFieldVal ( entry , "bundlefile" , false ) ; addBundleFile ( bundlefile , new HashSet <> ( ) , classLoader , classpathOrderOut , scanSpec , log ) ; } } }
|
Adds the classpath entries .
| 181
| 6
|
156,501
|
static ClassTypeSignature parse ( final String typeDescriptor , final ClassInfo classInfo ) throws ParseException { final Parser parser = new Parser ( typeDescriptor ) ; // The defining class name is used to resolve type variables using the defining class' type descriptor. // But here we are parsing the defining class' type descriptor, so it can't contain variables that // point to itself => just use null as the defining class name. 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 .
| 339
| 11
|
156,502
|
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 .
| 103
| 11
|
156,503
|
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 .
| 96
| 11
|
156,504
|
@ Override 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 .
| 55
| 10
|
156,505
|
private List < ClasspathElementModule > getModuleOrder ( final LogNode log ) throws InterruptedException { final List < ClasspathElementModule > moduleCpEltOrder = new ArrayList <> ( ) ; if ( scanSpec . overrideClasspath == null && scanSpec . overrideClassLoaders == null && scanSpec . scanModules ) { // Add modules to start of classpath order, before traditional classpath 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 ( // If scanning system packages and modules is enabled and white/blacklist is empty, // then scan all system modules ( scanSpec . enableSystemJarsAndModules && scanSpec . moduleWhiteBlackList . whitelistAndBlacklistAreEmpty ( ) ) // Otherwise only scan specifically whitelisted system modules || scanSpec . moduleWhiteBlackList . isSpecificallyWhitelistedAndNotBlacklisted ( moduleName ) ) { // Create a new ClasspathElementModule final ClasspathElementModule classpathElementModule = new ClasspathElementModule ( systemModuleRef , defaultClassLoader , nestedJarHandler , scanSpec ) ; moduleCpEltOrder . add ( classpathElementModule ) ; // Open the ClasspathElementModule classpathElementModule . open ( /* ignored */ 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 ) ) { // Create a new ClasspathElementModule final ClasspathElementModule classpathElementModule = new ClasspathElementModule ( nonSystemModuleRef , defaultClassLoader , nestedJarHandler , scanSpec ) ; moduleCpEltOrder . add ( classpathElementModule ) ; // Open the ClasspathElementModule classpathElementModule . open ( /* ignored */ null , log ) ; } else { if ( log != null ) { log . log ( "Skipping non-whitelisted or blacklisted module: " + moduleName ) ; } } } } } return moduleCpEltOrder ; }
|
Get the module order .
| 642
| 5
|
156,506
|
private static void findClasspathOrderRec ( final ClasspathElement currClasspathElement , final Set < ClasspathElement > visitedClasspathElts , final List < ClasspathElement > order ) { if ( visitedClasspathElts . add ( currClasspathElement ) ) { if ( ! currClasspathElement . skipClasspathElement ) { // Don't add a classpath element if it is marked to be skipped. order . add ( currClasspathElement ) ; } // Whether or not a classpath element should be skipped, add any child classpath elements that are // not marked to be skipped (i.e. keep recursing) 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 .
| 190
| 27
|
156,507
|
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 .
| 189
| 17
|
156,508
|
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 .
| 226
| 55
|
156,509
|
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 ( ) ; } // Throw InterruptedException if any of the workers failed interruptionChecker . check ( ) ; }
|
Process work units .
| 115
| 4
|
156,510
|
@ Override public ScanResult call ( ) throws InterruptedException , CancellationException , ExecutionException { ScanResult scanResult = null ; Exception exception = null ; final long scanStart = System . currentTimeMillis ( ) ; try { // Perform the scan scanResult = openClasspathElementsThenScan ( ) ; // Log total time after scan completes, and flush log if ( topLevelLog != null ) { topLevelLog . log ( "~" , String . format ( "Total time: %.3f sec" , ( System . currentTimeMillis ( ) - scanStart ) * .001 ) ) ; topLevelLog . flush ( ) ; } // Call the ScanResultProcessor, if one was provided 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 ) { // Re-throw throw e ; } } catch ( final CancellationException e ) { if ( topLevelLog != null ) { topLevelLog . log ( "~" , "Scan cancelled" ) ; } exception = e ; if ( failureHandler == null ) { // Re-throw throw e ; } } catch ( final ExecutionException e ) { if ( topLevelLog != null ) { topLevelLog . log ( "~" , "Uncaught exception during scan" , InterruptionChecker . getCause ( e ) ) ; } exception = e ; if ( failureHandler == null ) { // Re-throw throw e ; } } catch ( final RuntimeException e ) { if ( topLevelLog != null ) { topLevelLog . log ( "~" , "Uncaught exception during scan" , e ) ; } exception = e ; if ( failureHandler == null ) { // Wrap unchecked exceptions in a new ExecutionException throw new ExecutionException ( "Exception while scanning" , e ) ; } } finally { if ( exception != null || scanSpec . removeTemporaryFilesAfterScan ) { // If an exception was thrown or removeTemporaryFilesAfterScan was set, remove temporary files // and close resources, zipfiles, and modules nestedJarHandler . close ( topLevelLog ) ; } } if ( exception != null ) { // If an exception was thrown, log the cause, and flush the toplevel log if ( topLevelLog != null ) { final Throwable cause = InterruptionChecker . getCause ( exception ) ; topLevelLog . log ( "~" , "An uncaught exception was thrown:" , cause ) ; topLevelLog . flush ( ) ; } // If exception is null, then failureHandler must be non-null at this point try { // Call the FailureHandler failureHandler . onFailure ( exception ) ; } catch ( final Exception f ) { // The failure handler failed if ( topLevelLog != null ) { topLevelLog . log ( "~" , "The failure handler threw an exception:" , f ) ; } // Group the two exceptions into one, using the suppressed exception mechanism // to show the scan exception below the failure handler exception final ExecutionException failureHandlerException = new ExecutionException ( "Exception while calling failure handler" , f ) ; failureHandlerException . addSuppressed ( exception ) ; // Throw a new ExecutionException (although this will probably be ignored, // since any job with a FailureHandler was started with ExecutorService::execute // rather than ExecutorService::submit) throw failureHandlerException ; } } return scanResult ; }
|
Determine the unique ordered classpath elements and run a scan looking for file or classfile matches if necessary .
| 786
| 23
|
156,511
|
public List < String > list ( ) throws SecurityException { if ( collectorsToList == null ) { throw new IllegalArgumentException ( "Could not call Collectors.toList()" ) ; } final Object /* Stream<String> */ resourcesStream = ReflectionUtils . invokeMethod ( moduleReader , "list" , /* throwException = */ true ) ; if ( resourcesStream == null ) { throw new IllegalArgumentException ( "Could not call moduleReader.list()" ) ; } final Object resourcesList = ReflectionUtils . invokeMethod ( resourcesStream , "collect" , collectorClass , collectorsToList , /* throwException = */ 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 .
| 213
| 11
|
156,512
|
private Object openOrRead ( final String path , final boolean open ) throws SecurityException { final String methodName = open ? "open" : "read" ; final Object /* Optional<InputStream> */ optionalInputStream = ReflectionUtils . invokeMethod ( moduleReader , methodName , String . class , path , /* throwException = */ true ) ; if ( optionalInputStream == null ) { throw new IllegalArgumentException ( "Got null result from moduleReader." + methodName + "(name)" ) ; } final Object /* InputStream */ inputStream = ReflectionUtils . invokeMethod ( optionalInputStream , "get" , /* throwException = */ 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 .
| 182
| 16
|
156,513
|
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 // Don't get in a cycle && visited . add ( annotationClassInfo ) ) { for ( final AnnotationInfo metaAnnotationInfo : annotationClassInfo . annotationInfo ) { final ClassInfo metaAnnotationClassInfo = metaAnnotationInfo . getClassInfo ( ) ; final String metaAnnotationClassName = metaAnnotationClassInfo . getName ( ) ; // Don't treat java.lang.annotation annotations as meta-annotations if ( ! metaAnnotationClassName . startsWith ( "java.lang.annotation." ) ) { // Add the meta-annotation to the transitive closure allAnnotationsOut . add ( metaAnnotationInfo ) ; // Recurse to meta-meta-annotation findMetaAnnotations ( metaAnnotationInfo , allAnnotationsOut , visited ) ; } } } }
|
Find the transitive closure of meta - annotations .
| 238
| 10
|
156,514
|
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 .
| 46
| 12
|
156,515
|
private int read ( final int off , final int len ) throws IOException { if ( len == 0 ) { return 0 ; } if ( inputStream != null ) { // Wrapped InputStream return inputStream . read ( buf , off , len ) ; } else { // Wrapped ByteBuffer 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, as per InputStream#read() contract return - 1 ; } if ( byteBuffer != null ) { // Copy from the ByteBuffer into the byte array final int byteBufPositionBefore = byteBuffer . position ( ) ; try { byteBuffer . get ( buf , off , bytesRead ) ; } catch ( final BufferUnderflowException e ) { // Should not happen throw new IOException ( "Buffer underflow" , e ) ; } return byteBuffer . position ( ) - byteBufPositionBefore ; } else { // Nothing to read, since ByteBuffer is backed with an array return bytesRead ; } } }
|
Copy up to len bytes into buf starting at the given offset .
| 255
| 13
|
156,516
|
private void readMore ( final int bytesRequired ) throws IOException { if ( ( long ) used + ( long ) bytesRequired > FileUtils . MAX_BUFFER_SIZE ) { // Since buf is an array, we're limited to reading 2GB per file throw new IOException ( "File is larger than 2GB, cannot read it" ) ; } // Read INITIAL_BUFFER_CHUNK_SIZE for first chunk, or SUBSEQUENT_BUFFER_CHUNK_SIZE for subsequent chunks, // but don't try to read past 2GB limit final int targetReadSize = Math . max ( bytesRequired , // used == 0 ? INITIAL_BUFFER_CHUNK_SIZE : SUBSEQUENT_BUFFER_CHUNK_SIZE ) ; // Calculate number of bytes to read, based on the target read size, handling integer overflow final int maxNewUsed = ( int ) Math . min ( ( long ) used + ( long ) targetReadSize , FileUtils . MAX_BUFFER_SIZE ) ; final int bytesToRead = maxNewUsed - used ; if ( maxNewUsed > buf . length ) { // Ran out of space, need to increase the size of the buffer 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 { // EOF break ; } } if ( totBytesRead < bytesRequired ) { throw new IOException ( "Premature EOF while reading classfile" ) ; } }
|
Read another chunk of from the InputStream or ByteBuffer .
| 443
| 12
|
156,517
|
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 .
| 62
| 7
|
156,518
|
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 .
| 63
| 15
|
156,519
|
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 .
| 36
| 19
|
156,520
|
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 .
| 143
| 8
|
156,521
|
public static String normalizeURLPath ( final String urlPath ) { String urlPathNormalized = urlPath ; if ( ! urlPathNormalized . startsWith ( "jrt:" ) && ! urlPathNormalized . startsWith ( "http://" ) && ! urlPathNormalized . startsWith ( "https://" ) ) { // Any URL with the "jar:" prefix must have "/" after any "!" urlPathNormalized = urlPathNormalized . replace ( "/!" , "!" ) . replace ( "!/" , "!" ) . replace ( "!" , "!/" ) ; // Prepend "jar:file:" 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 .
| 236
| 18
|
156,522
|
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 .
| 92
| 16
|
156,523
|
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 .
| 46
| 15
|
156,524
|
@ Override 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 ; } // In case of multiple entries with the same entry name, return them in consecutive order of location, // so that the earliest entry overrides later entries (this is an arbitrary decision for consistency) 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 .
| 182
| 20
|
156,525
|
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 .
| 95
| 8
|
156,526
|
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 ) ) { // Don't call constructor with size hint if this is not a Collection or Map // (since the constructor could do anything) return null ; } return classFieldCache . getConstructorWithSizeHintForConcreteTypeOf ( fieldRawTypeFullyResolved ) ; } }
|
Get the constructor with size hint for the field type .
| 186
| 11
|
156,527
|
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 .
| 106
| 9
|
156,528
|
private static void appendPathElt ( final Object pathElt , final StringBuilder buf ) { if ( buf . length ( ) > 0 ) { buf . append ( File . pathSeparatorChar ) ; } // Escape any rogue path separators, as long as file separator is not '\\' (on Windows, if there are any // extra ';' characters in a path element, there's really nothing we can do to escape them, since they can't // be escaped as "\\;") final String path = File . separatorChar == ' ' ? pathElt . toString ( ) : pathElt . toString ( ) . replaceAll ( File . pathSeparator , "\\" + File . pathSeparator ) ; buf . append ( path ) ; }
|
Append a path element to a buffer .
| 167
| 9
|
156,529
|
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 ) ) ) ; // In case of temp files (for jars extracted from within jars), remove the temp filename prefix -- see // NestedJarHandler.unzipToTempFile() 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 .
| 272
| 19
|
156,530
|
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 .
| 91
| 12
|
156,531
|
static BaseTypeSignature parse ( final Parser parser ) { switch ( parser . peek ( ) ) { case ' ' : parser . next ( ) ; return new BaseTypeSignature ( "byte" ) ; case ' ' : parser . next ( ) ; return new BaseTypeSignature ( "char" ) ; case ' ' : parser . next ( ) ; return new BaseTypeSignature ( "double" ) ; case ' ' : parser . next ( ) ; return new BaseTypeSignature ( "float" ) ; case ' ' : parser . next ( ) ; return new BaseTypeSignature ( "int" ) ; case ' ' : parser . next ( ) ; return new BaseTypeSignature ( "long" ) ; case ' ' : parser . next ( ) ; return new BaseTypeSignature ( "short" ) ; case ' ' : parser . next ( ) ; return new BaseTypeSignature ( "boolean" ) ; case ' ' : parser . next ( ) ; return new BaseTypeSignature ( "void" ) ; default : return null ; } }
|
Parse a base type .
| 218
| 6
|
156,532
|
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 ) { // giving up. 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 .
| 218
| 9
|
156,533
|
Set < String > findReferencedClassNames ( ) { final Set < String > allReferencedClassNames = new LinkedHashSet <> ( ) ; findReferencedClassNames ( allReferencedClassNames ) ; // Remove references to java.lang.Object allReferencedClassNames . remove ( "java.lang.Object" ) ; return allReferencedClassNames ; }
|
Get the names of all referenced classes .
| 86
| 8
|
156,534
|
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 .
| 212
| 28
|
156,535
|
private static < T > T deserializeObject ( final Class < T > expectedType , final String json , final ClassFieldCache classFieldCache ) throws IllegalArgumentException { // Parse the JSON Object parsedJSON ; try { parsedJSON = JSONParser . parseJSON ( json ) ; } catch ( final ParseException e ) { throw new IllegalArgumentException ( "Could not parse JSON" , e ) ; } T objectInstance ; try { // Construct an object of the expected type 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 ) ; } // Populate the object from the parsed JSON 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 .
| 302
| 48
|
156,536
|
public static < T > T deserializeObject ( final Class < T > expectedType , final String json ) throws IllegalArgumentException { final ClassFieldCache classFieldCache = new ClassFieldCache ( /* resolveTypes = */ true , /* onlySerializePublicFields = */ 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 .
| 78
| 40
|
156,537
|
private static void findLayerOrder ( final Object /* ModuleLayer */ layer , final Set < Object > /* Set<ModuleLayer> */ layerVisited , final Set < Object > /* Set<ModuleLayer> */ parentLayers , final Deque < Object > /* Deque<ModuleLayer> */ layerOrderOut ) { if ( layerVisited . add ( layer ) ) { @ SuppressWarnings ( "unchecked" ) final List < Object > /* List<ModuleLayer> */ parents = ( List < Object > ) ReflectionUtils . invokeMethod ( layer , "parents" , /* throwException = */ 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 .
| 190
| 13
|
156,538
|
private static List < ModuleRef > findModuleRefs ( final LinkedHashSet < Object > layers , final ScanSpec scanSpec , final LogNode log ) { if ( layers . isEmpty ( ) ) { return Collections . emptyList ( ) ; } // Traverse the layer DAG to find the layer resolution order final Deque < Object > /* Deque<ModuleLayer> */ layerOrder = new ArrayDeque <> ( ) ; final Set < Object > /* Set<ModuleLayer */ parentLayers = new HashSet <> ( ) ; for ( final Object layer : layers ) { findLayerOrder ( layer , /* layerVisited = */ new HashSet <> ( ) , parentLayers , layerOrder ) ; } if ( scanSpec . addedModuleLayers != null ) { for ( final Object layer : scanSpec . addedModuleLayers ) { findLayerOrder ( layer , /* layerVisited = */ new HashSet <> ( ) , parentLayers , layerOrder ) ; } } // Remove parent layers from layer order if scanSpec.ignoreParentModuleLayers is true List < Object > /* List<ModuleLayer> */ layerOrderFinal ; if ( scanSpec . ignoreParentModuleLayers ) { layerOrderFinal = new ArrayList <> ( ) ; for ( final Object layer : layerOrder ) { if ( ! parentLayers . contains ( layer ) ) { layerOrderFinal . add ( layer ) ; } } } else { layerOrderFinal = new ArrayList <> ( layerOrder ) ; } // Find modules in the ordered layers final Set < Object > /* Set<ModuleReference> */ addedModules = new HashSet <> ( ) ; final LinkedHashSet < ModuleRef > moduleRefOrder = new LinkedHashSet <> ( ) ; for ( final Object /* ModuleLayer */ layer : layerOrderFinal ) { final Object /* Configuration */ configuration = ReflectionUtils . invokeMethod ( layer , "configuration" , /* throwException = */ true ) ; if ( configuration != null ) { // Get ModuleReferences from layer configuration @ SuppressWarnings ( "unchecked" ) final Set < Object > /* Set<ResolvedModule> */ modules = ( Set < Object > ) ReflectionUtils . invokeMethod ( configuration , "modules" , /* throwException = */ true ) ; if ( modules != null ) { final List < ModuleRef > modulesInLayer = new ArrayList <> ( ) ; for ( final Object /* ResolvedModule */ module : modules ) { final Object /* ModuleReference */ moduleReference = ReflectionUtils . invokeMethod ( module , "reference" , /* throwException = */ 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 ) ; } } } } // Sort modules in layer by name CollectionUtils . sortIfNotEmpty ( modulesInLayer ) ; moduleRefOrder . addAll ( modulesInLayer ) ; } } } return new ArrayList <> ( moduleRefOrder ) ; }
|
Get all visible ModuleReferences in a list of layers .
| 686
| 11
|
156,539
|
static ClassRefTypeSignature parse ( final Parser parser , final String definingClassName ) throws ParseException { if ( parser . peek ( ) == ' ' ) { parser . next ( ) ; if ( ! TypeUtils . getIdentifierToken ( parser , /* separator = */ ' ' , /* separatorReplace = */ ' ' ) ) { 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 , /* separator = */ ' ' , /* separatorReplace = */ ' ' ) ) { 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 .
| 364
| 7
|
156,540
|
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" ) ) { // Strategy is self-first return false ; } } // Strategy is org.codehaus.plexus.classworlds.strategy.ParentFirstStrategy (or failed to find strategy) return true ; }
|
Checks if is this classloader uses a parent - first strategy .
| 176
| 14
|
156,541
|
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 .
| 145
| 11
|
156,542
|
@ Override public void write ( final T value , boolean incomplete ) { // Place the value to the queue, add new terminator element. queue . push ( value ) ; // Move the "flush up to here" pointer. if ( ! incomplete ) { f = queue . backPos ( ) ; } }
|
flushed down the stream .
| 64
| 6
|
156,543
|
@ Override public T unwrite ( ) { if ( f == queue . backPos ( ) ) { return null ; } queue . unpush ( ) ; return queue . back ( ) ; }
|
item exists false otherwise .
| 41
| 5
|
156,544
|
@ Override public boolean flush ( ) { // If there are no un-flushed items, do nothing. if ( w == f ) { return true ; } // Try to set 'c' to 'f'. if ( ! c . compareAndSet ( w , f ) ) { // Compare-and-swap was unsuccessful because 'c' is NULL. // This means that the reader is asleep. Therefore we don't // care about thread-safeness and update c in non-atomic // manner. We'll return false to let the caller know // that reader is sleeping. c . set ( f ) ; w = f ; return false ; } // Reader is alive. Nothing special to do now. Just move // the 'first un-flushed item' pointer to 'f'. w = f ; return true ; }
|
wake the reader up before using the pipe again .
| 172
| 10
|
156,545
|
@ Override public boolean checkRead ( ) { // Was the value prefetched already? If so, return. int h = queue . frontPos ( ) ; if ( h != r ) { return true ; } // There's no prefetched value, so let us prefetch more values. // Prefetching is to simply retrieve the // pointer from c in atomic fashion. If there are no // items to prefetch, set c to -1 (using compare-and-swap). if ( c . compareAndSet ( h , - 1 ) ) { // nothing to read, h == r must be the same } else { // something to have been written r = c . get ( ) ; } // If there are no elements prefetched, exit. // During pipe's lifetime r should never be NULL, however, // it can happen during pipe shutdown when items // are being deallocated. if ( h == r || r == - 1 ) { return false ; } // There was at least one value prefetched. return true ; }
|
Check whether item is available for reading .
| 220
| 8
|
156,546
|
@ Override public ByteBuffer getBuffer ( ) { // If we are expected to read large message, we'll opt for zero- // copy, i.e. we'll ask caller to fill the data directly to the // message. Note that subsequent read(s) are non-blocking, thus // each single read reads at most SO_RCVBUF bytes at once not // depending on how large is the chunk returned from here. // As a consequence, large messages being received won't block // other engines running in the same I/O thread for excessive // amounts of time. if ( toRead >= bufsize ) { zeroCopy = true ; return readPos . duplicate ( ) ; } else { zeroCopy = false ; buf . clear ( ) ; return buf ; } }
|
Returns a buffer to be filled with binary data .
| 161
| 10
|
156,547
|
@ Override public Step . Result decode ( ByteBuffer data , int size , ValueReference < Integer > processed ) { processed . set ( 0 ) ; // In case of zero-copy simply adjust the pointers, no copying // is required. Also, run the state machine in case all the data // were processed. 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 ) { // Copy the data from buffer to the message. 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 ) ; // Try to get more space in the message to fill in. // If none is available, return. 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 .
| 328
| 4
|
156,548
|
public boolean rm ( Msg msg , int start , int size ) { // TODO: Shouldn't an error be reported if the key does not exist? 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 ) ; // Prune redundant nodes if ( nextNode . isRedundant ( ) ) { //delete next_node; assert ( count > 0 ) ; if ( count == 1 ) { // The just pruned node was the only live node next = null ; count = 0 ; -- liveNodes ; assert ( liveNodes == 0 ) ; } else { next [ c - min ] = null ; assert ( liveNodes > 1 ) ; -- liveNodes ; // Compact the table if possible if ( liveNodes == 1 ) { // We can switch to using the more compact single-node // representation since the table only contains one live node Trie node = null ; // Since we always compact the table the pruned node must // either be the left-most or right-most ptr in the node // table if ( c == min ) { // The pruned node is the left-most node ptr in the // node table => keep the right-most node node = next [ count - 1 ] ; min += count - 1 ; } else if ( c == min + count - 1 ) { // The pruned node is the right-most node ptr in the // node table => keep the left-most node node = next [ 0 ] ; } assert ( node != null ) ; //free (next.table); next = new Trie [ ] { node } ; count = 1 ; } else if ( c == min ) { // We can compact the table "from the left". // Find the left-most non-null node ptr, which we'll use as // our new 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 ) { // We can compact the table "from the right". // Find the right-most non-null node ptr, which we'll use to // determine the new table size 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 .
| 712
| 7
|
156,549
|
public boolean check ( ByteBuffer data ) { assert ( data != null ) ; int size = data . limit ( ) ; // This function is on critical path. It deliberately doesn't use // recursion to get a bit better performance. Trie current = this ; int start = 0 ; while ( true ) { // We've found a corresponding subscription! if ( current . refcnt > 0 ) { return true ; } // We've checked all the data and haven't found matching subscription. if ( size == 0 ) { return false ; } // If there's no corresponding slot for the first character // of the prefix, the message does not match. byte c = data . get ( start ) ; if ( c < current . min || c >= current . min + current . count ) { return false ; } // Move to the next character. 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 .
| 228
| 10
|
156,550
|
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 .
| 59
| 15
|
156,551
|
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 .
| 37
| 27
|
156,552
|
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 .
| 36
| 19
|
156,553
|
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 ) { // If receive failed or was interrupted 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 .
| 121
| 38
|
156,554
|
public static boolean save ( ZMsg msg , DataOutputStream file ) { if ( msg == null ) { return false ; } try { // Write number of frames file . writeInt ( msg . size ( ) ) ; if ( msg . size ( ) > 0 ) { for ( ZFrame f : msg ) { // Write byte size of frame file . writeInt ( f . size ( ) ) ; // Write frame byte data file . write ( f . getData ( ) ) ; } } return true ; } catch ( IOException e ) { return false ; } }
|
Save message to an open data output stream .
| 118
| 9
|
156,555
|
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
| 44
| 11
|
156,556
|
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 .
| 140
| 24
|
156,557
|
@ Deprecated protected ZAgent agent ( Socket phone , String secret ) { return ZAgent . Creator . create ( phone , secret ) ; }
|
Creates a new agent for the star .
| 29
| 9
|
156,558
|
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 .
| 84
| 6
|
156,559
|
public long timeout ( ) { if ( tickets . isEmpty ( ) ) { return - 1 ; } sortIfNeeded ( ) ; // Tickets are sorted, so check first ticket Ticket first = tickets . get ( 0 ) ; return first . start - now ( ) + first . delay ; }
|
Returns the time in millisecond until the next ticket .
| 61
| 11
|
156,560
|
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 ) { // tickets are ordered, not meeting the condition means the next ones do not as well break ; } if ( ! ticket . alive ) { // Dead ticket, let's continue 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 .
| 205
| 5
|
156,561
|
private NetProtocol checkProtocol ( String protocol ) { // First check out whether the protcol is something we are aware of. NetProtocol proto = NetProtocol . getProtocol ( protocol ) ; if ( proto == null || ! proto . valid ) { errno . set ( ZError . EPROTONOSUPPORT ) ; return proto ; } // Check whether socket type and transport protocol match. // Specifically, multicast protocols can't be combined with // bi-directional messaging patterns (socket types). if ( ! proto . compatible ( options . type ) ) { errno . set ( ZError . ENOCOMPATPROTO ) ; return null ; } // Protocol is available. return proto ; }
|
bind is available and compatible with the socket type .
| 151
| 10
|
156,562
|
private void addEndpoint ( String addr , Own endpoint , Pipe pipe ) { // Activate the session. Make it a child of this socket. launchChild ( endpoint ) ; endpoints . insert ( addr , new EndpointPipe ( endpoint , pipe ) ) ; }
|
Creates new endpoint ID and adds the endpoint to the map .
| 55
| 13
|
156,563
|
final void startReaping ( Poller poller ) { // Plug the socket to the reaper thread. this . poller = poller ; SelectableChannel fd = mailbox . getFd ( ) ; handle = this . poller . addHandle ( fd , this ) ; this . poller . setPollIn ( handle ) ; // Initialize the termination and check whether it can be deallocated // immediately. terminate ( ) ; checkDestroy ( ) ; }
|
its poller .
| 99
| 4
|
156,564
|
private boolean processCommands ( int timeout , boolean throttle ) { Command cmd ; if ( timeout != 0 ) { // If we are asked to wait, simply ask mailbox to wait. cmd = mailbox . recv ( timeout ) ; } else { // If we are asked not to wait, check whether we haven't processed // commands recently, so that we can throttle the new commands. // Get the CPU's tick counter. If 0, the counter is not available. long tsc = 0 ; // Clock.rdtsc(); // Optimized version of command processing - it doesn't have to check // for incoming commands each time. It does so only if certain time // elapsed since last command processing. Command delay varies // depending on CPU speed: It's ~1ms on 3GHz CPU, ~2ms on 1.5GHz CPU // etc. The optimization makes sense only on platforms where getting // a timestamp is a very cheap operation (tens of nanoseconds). if ( tsc != 0 && throttle ) { // Check whether TSC haven't jumped backwards (in case of migration // between CPU cores) and whether certain time have elapsed since // last command processing. If it didn't do nothing. if ( tsc >= lastTsc && tsc - lastTsc <= Config . MAX_COMMAND_DELAY . getValue ( ) ) { return true ; } lastTsc = tsc ; } // Check whether there are any commands pending for this thread. cmd = mailbox . recv ( 0 ) ; } // Process all the commands available at the moment. 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 ) ; // Do not raise exception at the blocked operation return false ; } return true ; }
|
in a predefined time period .
| 430
| 7
|
156,565
|
private void extractFlags ( Msg msg ) { // Test whether IDENTITY flag is valid for this socket type. if ( msg . isIdentity ( ) ) { assert ( options . recvIdentity ) ; } // Remove MORE flag. rcvmore = msg . hasMore ( ) ; }
|
to be later retrieved by getSocketOpt .
| 63
| 9
|
156,566
|
@ Override public String getAddress ( ) { if ( ( ( InetSocketAddress ) address . address ( ) ) . getPort ( ) == 0 ) { return address ( address ) ; } return address . toString ( ) ; }
|
Get the bound address for use with wildcards
| 50
| 9
|
156,567
|
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
| 87
| 7
|
156,568
|
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 .
| 146
| 16
|
156,569
|
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 .
| 119
| 12
|
156,570
|
private void error ( ErrorReason error ) { if ( options . rawSocket ) { // For raw sockets, send a final 0-length message to the application // so that it knows the peer has been disconnected. 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 .
| 107
| 7
|
156,571
|
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 .
| 84
| 14
|
156,572
|
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 ( ) ) { // If not a single byte can be read from the socket in non-blocking mode // we'll get an error (this may happen during the speculative read). // Several errors are OK. When speculative read is being done we may not // be able to read a single byte from the socket. Also, SIGSTOP issued // by a debugging tool can result in EINTR error. 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 .
| 205
| 9
|
156,573
|
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 .
| 37
| 23
|
156,574
|
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
| 53
| 12
|
156,575
|
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 .
| 60
| 27
|
156,576
|
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 .
| 55
| 28
|
156,577
|
public void terminate ( ) { slotSync . lock ( ) ; try { // Connect up any pending inproc connections, otherwise we will hang for ( Entry < PendingConnection , String > pending : pendingConnections . entries ( ) ) { SocketBase s = createSocket ( ZMQ . ZMQ_PAIR ) ; // create_socket might fail eg: out of memory/sockets limit reached assert ( s != null ) ; s . bind ( pending . getValue ( ) ) ; s . close ( ) ; } if ( ! starting . get ( ) ) { // Check whether termination was already underway, but interrupted and now // restarted. boolean restarted = terminating ; terminating = true ; // First attempt to terminate the context. if ( ! restarted ) { // First send stop command to sockets so that any blocking calls // can be interrupted. If there are no sockets we can ask reaper // thread to stop. for ( SocketBase socket : sockets ) { socket . stop ( ) ; } if ( sockets . isEmpty ( ) ) { reaper . stop ( ) ; } } } } finally { slotSync . unlock ( ) ; } if ( ! starting . get ( ) ) { // Wait till reaper thread closes all the sockets. Command cmd = termMailbox . recv ( WAIT_FOREVER ) ; if ( cmd == null ) { throw new IllegalStateException ( ZError . toString ( errno . get ( ) ) ) ; } assert ( cmd . type == Command . Type . DONE ) : cmd ; slotSync . lock ( ) ; try { assert ( sockets . isEmpty ( ) ) ; } finally { slotSync . unlock ( ) ; } } // Deallocate the resources. try { destroy ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }
|
after the last one is closed .
| 383
| 7
|
156,578
|
public Selector createSelector ( ) { selectorSync . lock ( ) ; try { Selector selector = Selector . open ( ) ; assert ( selector != null ) ; selectors . add ( selector ) ; return selector ; } catch ( IOException e ) { throw new ZError . IOException ( e ) ; } finally { selectorSync . unlock ( ) ; } }
|
Creates a Selector that will be closed when the context is destroyed .
| 78
| 15
|
156,579
|
boolean registerEndpoint ( String addr , Endpoint endpoint ) { endpointsSync . lock ( ) ; Endpoint inserted = null ; try { inserted = endpoints . put ( addr , endpoint ) ; } finally { endpointsSync . unlock ( ) ; } if ( inserted != null ) { return false ; } return true ; }
|
Management of inproc endpoints .
| 69
| 7
|
156,580
|
public void attachPipe ( Pipe pipe ) { assert ( ! isTerminating ( ) ) ; assert ( this . pipe == null ) ; assert ( pipe != null ) ; this . pipe = pipe ; this . pipe . setEventSink ( this ) ; }
|
To be used once only when creating the session .
| 55
| 10
|
156,581
|
private void cleanPipes ( ) { assert ( pipe != null ) ; // Get rid of half-processed messages in the out pipe. Flush any // unflushed messages upstream. pipe . rollback ( ) ; pipe . flush ( ) ; // Remove any half-read message from the in pipe. while ( incompleteIn ) { Msg msg = pullMsg ( ) ; if ( msg == null ) { assert ( ! incompleteIn ) ; break ; } // msg.close (); } }
|
Call this function when engine disconnect to get rid of leftovers .
| 102
| 13
|
156,582
|
public void destroy ( ) { for ( Socket socket : sockets ) { destroySocket ( socket ) ; } sockets . clear ( ) ; for ( Selector selector : selectors ) { context . close ( selector ) ; } selectors . clear ( ) ; // Only terminate context if we are on the main thread if ( isMain ( ) ) { context . term ( ) ; } }
|
Destructor . Call this to gracefully terminate context and close any managed 0MQ sockets
| 79
| 18
|
156,583
|
public Socket createSocket ( SocketType type ) { // Create and register socket Socket socket = context . socket ( type ) ; socket . setRcvHWM ( this . rcvhwm ) ; socket . setSndHWM ( this . sndhwm ) ; sockets . add ( socket ) ; return socket ; }
|
Creates a new managed socket within this ZContext instance . Use this to get automatic management of the socket at shutdown
| 68
| 23
|
156,584
|
public void destroySocket ( Socket s ) { if ( s == null ) { return ; } s . setLinger ( linger ) ; s . close ( ) ; this . sockets . remove ( s ) ; }
|
Destroys managed socket within this context and remove from sockets list
| 44
| 13
|
156,585
|
Selector selector ( ) { Selector selector = context . selector ( ) ; selectors . add ( selector ) ; return selector ; }
|
Creates a selector . Resource will be released when context will be closed .
| 28
| 15
|
156,586
|
@ Deprecated @ Draft public void closeSelector ( Selector selector ) { if ( selectors . remove ( selector ) ) { context . close ( selector ) ; } }
|
Closes a selector . This is a DRAFT method and may change without notice .
| 36
| 17
|
156,587
|
public static ZContext shadow ( ZContext ctx ) { ZContext context = new ZContext ( ctx . context , false , ctx . ioThreads ) ; context . linger = ctx . linger ; context . sndhwm = ctx . sndhwm ; context . rcvhwm = ctx . rcvhwm ; context . pipehwm = ctx . pipehwm ; return context ; }
|
Creates new shadow context . Shares same underlying org . zeromq . Context instance but has own list of managed sockets io thread count etc .
| 91
| 30
|
156,588
|
public Socket fork ( ZThread . IAttachedRunnable runnable , Object ... args ) { return ZThread . fork ( this , runnable , args ) ; }
|
Create an attached thread An attached thread gets a ctx and a PAIR pipe back to its parent . It must monitor its pipe and exit if the pipe becomes unreadable
| 38
| 34
|
156,589
|
public static ByteBuffer putUInt64 ( ByteBuffer buf , long value ) { buf . put ( ( byte ) ( ( value >>> 56 ) & 0xff ) ) ; buf . put ( ( byte ) ( ( value >>> 48 ) & 0xff ) ) ; buf . put ( ( byte ) ( ( value >>> 40 ) & 0xff ) ) ; buf . put ( ( byte ) ( ( value >>> 32 ) & 0xff ) ) ; buf . put ( ( byte ) ( ( value >>> 24 ) & 0xff ) ) ; buf . put ( ( byte ) ( ( value >>> 16 ) & 0xff ) ) ; buf . put ( ( byte ) ( ( value >>> 8 ) & 0xff ) ) ; buf . put ( ( byte ) ( ( value ) & 0xff ) ) ; return buf ; }
|
8 bytes value
| 171
| 3
|
156,590
|
public static Socket fork ( ZContext ctx , IAttachedRunnable runnable , Object ... args ) { Socket pipe = ctx . createSocket ( SocketType . PAIR ) ; if ( pipe != null ) { pipe . bind ( String . format ( "inproc://zctx-pipe-%d" , pipe . hashCode ( ) ) ) ; } else { return null ; } // Connect child pipe to our pipe ZContext ccontext = ZContext . shadow ( ctx ) ; Socket cpipe = ccontext . createSocket ( SocketType . PAIR ) ; if ( cpipe == null ) { return null ; } cpipe . connect ( String . format ( "inproc://zctx-pipe-%d" , pipe . hashCode ( ) ) ) ; // Prepare child thread Thread shim = new ShimThread ( ccontext , runnable , args , cpipe ) ; shim . start ( ) ; return pipe ; }
|
pipe becomes unreadable . Returns pipe or null if there was an error .
| 202
| 15
|
156,591
|
private void startConnecting ( ) { // Open the connecting socket. try { boolean rc = open ( ) ; // Connect may succeed in synchronous manner. if ( rc ) { handle = ioObject . addFd ( fd ) ; connectEvent ( ) ; } // Connection establishment may be delayed. Poll for its completion. else { handle = ioObject . addFd ( fd ) ; ioObject . setPollConnect ( handle ) ; socket . eventConnectDelayed ( addr . toString ( ) , - 1 ) ; } } catch ( RuntimeException | IOException e ) { // Handle any other error condition by eventual reconnect. if ( fd != null ) { close ( ) ; } addReconnectTimer ( ) ; } }
|
Internal function to start the actual connection establishment .
| 156
| 9
|
156,592
|
private void addReconnectTimer ( ) { int rcIvl = getNewReconnectIvl ( ) ; ioObject . addTimer ( rcIvl , RECONNECT_TIMER_ID ) ; // resolve address again to take into account other addresses // besides the failing one (e.g. multiple dns entries). try { addr . resolve ( options . ipv6 ) ; } catch ( Exception ignored ) { // This will fail if the network goes away and the // address cannot be resolved for some reason. Try // not to fail as the event loop will quit } socket . eventConnectRetried ( addr . toString ( ) , rcIvl ) ; timerStarted = true ; }
|
Internal function to add a reconnect timer
| 149
| 7
|
156,593
|
private int getNewReconnectIvl ( ) { // The new interval is the current interval + random value. int interval = currentReconnectIvl + ( Utils . randomInt ( ) % options . reconnectIvl ) ; // Only change the current reconnect interval if the maximum reconnect // interval was set and if it's larger than the reconnect interval. if ( options . reconnectIvlMax > 0 && options . reconnectIvlMax > options . reconnectIvl ) { // Calculate the next interval currentReconnectIvl = Math . min ( currentReconnectIvl * 2 , options . reconnectIvlMax ) ; } return interval ; }
|
Returns the currently used interval
| 139
| 5
|
156,594
|
private boolean open ( ) throws IOException { assert ( fd == null ) ; // Resolve the address if ( addr == null ) { throw new IOException ( "Null address" ) ; } addr . resolve ( options . ipv6 ) ; Address . IZAddress resolved = addr . resolved ( ) ; if ( resolved == null ) { throw new IOException ( "Address not resolved" ) ; } SocketAddress sa = resolved . address ( ) ; if ( sa == null ) { throw new IOException ( "Socket address not resolved" ) ; } // Create the socket. if ( options . selectorChooser == null ) { fd = SocketChannel . open ( ) ; } else { fd = options . selectorChooser . choose ( resolved , options ) . openSocketChannel ( ) ; } // On some systems, IPv4 mapping in IPv6 sockets is disabled by default. // Switch it on in such cases. // The method enableIpv4Mapping is empty. Still to be written if ( resolved . family ( ) == StandardProtocolFamily . INET6 ) { TcpUtils . enableIpv4Mapping ( fd ) ; } // Set the socket to non-blocking mode so that we get async connect(). TcpUtils . unblockSocket ( fd ) ; // Set the socket buffer limits for the underlying socket. if ( options . sndbuf != 0 ) { TcpUtils . setTcpSendBuffer ( fd , options . sndbuf ) ; } if ( options . rcvbuf != 0 ) { TcpUtils . setTcpReceiveBuffer ( fd , options . rcvbuf ) ; } // Set the IP Type-Of-Service priority for this socket if ( options . tos != 0 ) { TcpUtils . setIpTypeOfService ( fd , options . tos ) ; } // TODO V4 Set a source address for conversations if ( resolved . sourceAddress ( ) != null ) { // SocketChannel bind = channel.bind(resolved.sourceAddress()); // if (bind == null) { // return false; // } } // Connect to the remote peer. boolean rc ; try { rc = fd . connect ( sa ) ; if ( rc ) { // Connect was successful immediately. } else { // Translate error codes indicating asynchronous connect has been // launched to a uniform EINPROGRESS. errno . set ( ZError . EINPROGRESS ) ; } } catch ( IllegalArgumentException e ) { // this will happen if sa is bad. Address validation is not documented but // I've found that IAE is thrown in openjdk as well as on android. throw new IOException ( e . getMessage ( ) , e ) ; } return rc ; }
|
Returns false if async connect was launched .
| 588
| 8
|
156,595
|
private SocketChannel connect ( ) { try { // Async connect has finished. Check whether an error occurred boolean finished = fd . finishConnect ( ) ; assert ( finished ) ; return fd ; } catch ( IOException e ) { return null ; } }
|
null if the connection was unsuccessful .
| 54
| 7
|
156,596
|
protected void close ( ) { assert ( fd != null ) ; try { fd . close ( ) ; socket . eventClosed ( addr . toString ( ) , fd ) ; } catch ( IOException e ) { socket . eventCloseFailed ( addr . toString ( ) , ZError . exccode ( e ) ) ; } fd = null ; }
|
Close the connecting socket .
| 80
| 5
|
156,597
|
@ Deprecated public boolean setInterval ( Timer timer , long interval ) { assert ( timer . parent == this ) ; return timer . setInterval ( interval ) ; }
|
Changes the interval of the timer . This method is slow canceling existing and adding a new timer yield better performance .
| 37
| 23
|
156,598
|
public long timeout ( ) { final long now = now ( ) ; for ( Entry < Timer , Long > entry : entries ( ) ) { final Timer timer = entry . getKey ( ) ; final Long expiration = entry . getValue ( ) ; if ( timer . alive ) { // Live timer, lets return the timeout if ( expiration - now > 0 ) { return expiration - now ; } else { return 0 ; } } // Remove it from the list of active timers. timers . remove ( expiration , timer ) ; } // Wait forever as no timers are alive return - 1 ; }
|
Returns the time in millisecond until the next timer .
| 123
| 11
|
156,599
|
public int execute ( ) { int executed = 0 ; final long now = now ( ) ; for ( Entry < Timer , Long > entry : entries ( ) ) { final Timer timer = entry . getKey ( ) ; final Long expiration = entry . getValue ( ) ; // Dead timer, lets remove it and continue if ( ! timer . alive ) { // Remove it from the list of active timers. timers . remove ( expiration , timer ) ; continue ; } // Map is ordered, if we have to wait for current timer we can stop. if ( expiration - now > 0 ) { break ; } insert ( timer ) ; timer . handler . time ( timer . args ) ; ++ executed ; } return executed ; }
|
Execute the timers .
| 150
| 5
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.