idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
144,500 | private boolean operations ( Options opt , ConstructorDoc m [ ] ) { boolean printed = false ; for ( ConstructorDoc cd : m ) { if ( hidden ( cd ) ) continue ; stereotype ( opt , cd , Align . LEFT ) ; String cs = visibility ( opt , cd ) + cd . name ( ) // + ( opt . showType ? "(" + parameter ( opt , cd . parameters ( ) ) + ")" : "()" ) ; tableLine ( Align . LEFT , cs ) ; tagvalue ( opt , cd ) ; printed = true ; } return printed ; } | Print the class s constructors m | 126 | 7 |
144,501 | private boolean operations ( Options opt , MethodDoc m [ ] ) { boolean printed = false ; for ( MethodDoc md : m ) { if ( hidden ( md ) ) continue ; // Filter-out static initializer method if ( md . name ( ) . equals ( "<clinit>" ) && md . isStatic ( ) && md . isPackagePrivate ( ) ) continue ; stereotype ( opt , md , Align . LEFT ) ; String op = visibility ( opt , md ) + md . name ( ) + // ( opt . showType ? "(" + parameter ( opt , md . parameters ( ) ) + ")" + typeAnnotation ( opt , md . returnType ( ) ) : "()" ) ; tableLine ( Align . LEFT , ( md . isAbstract ( ) ? Font . ABSTRACT : Font . NORMAL ) . wrap ( opt , op ) ) ; printed = true ; tagvalue ( opt , md ) ; } return printed ; } | Print the class s operations m | 204 | 6 |
144,502 | private void nodeProperties ( Options opt ) { Options def = opt . getGlobalOptions ( ) ; if ( opt . nodeFontName != def . nodeFontName ) w . print ( ",fontname=\"" + opt . nodeFontName + "\"" ) ; if ( opt . nodeFontColor != def . nodeFontColor ) w . print ( ",fontcolor=\"" + opt . nodeFontColor + "\"" ) ; if ( opt . nodeFontSize != def . nodeFontSize ) w . print ( ",fontsize=" + fmt ( opt . nodeFontSize ) ) ; w . print ( opt . shape . style ) ; w . println ( "];" ) ; } | Print the common class node s properties | 142 | 7 |
144,503 | private void tagvalue ( Options opt , Doc c ) { Tag tags [ ] = c . tags ( "tagvalue" ) ; if ( tags . length == 0 ) return ; for ( Tag tag : tags ) { String t [ ] = tokenize ( tag . text ( ) ) ; if ( t . length != 2 ) { System . err . println ( "@tagvalue expects two fields: " + tag . text ( ) ) ; continue ; } tableLine ( Align . RIGHT , Font . TAG . wrap ( opt , "{" + t [ 0 ] + " = " + t [ 1 ] + "}" ) ) ; } } | Return as a string the tagged values associated with c | 134 | 10 |
144,504 | private void stereotype ( Options opt , Doc c , Align align ) { for ( Tag tag : c . tags ( "stereotype" ) ) { String t [ ] = tokenize ( tag . text ( ) ) ; if ( t . length != 1 ) { System . err . println ( "@stereotype expects one field: " + tag . text ( ) ) ; continue ; } tableLine ( align , guilWrap ( opt , t [ 0 ] ) ) ; } } | Return as a string the stereotypes associated with c terminated by the escape character term | 103 | 15 |
144,505 | private boolean hidden ( ProgramElementDoc c ) { if ( c . tags ( "hidden" ) . length > 0 || c . tags ( "view" ) . length > 0 ) return true ; Options opt = optionProvider . getOptionsFor ( c instanceof ClassDoc ? ( ClassDoc ) c : c . containingClass ( ) ) ; return opt . matchesHideExpression ( c . toString ( ) ) // || ( opt . hidePrivateInner && c instanceof ClassDoc && c . isPrivate ( ) && ( ( ClassDoc ) c ) . containingClass ( ) != null ) ; } | Return true if c has a | 126 | 6 |
144,506 | private boolean hidden ( String className ) { className = removeTemplate ( className ) ; ClassInfo ci = classnames . get ( className ) ; return ci != null ? ci . hidden : optionProvider . getOptionsFor ( className ) . matchesHideExpression ( className ) ; } | Return true if the class name is associated to an hidden class or matches a hide expression | 65 | 17 |
144,507 | private void allRelation ( Options opt , RelationType rt , ClassDoc from ) { String tagname = rt . lower ; for ( Tag tag : from . tags ( tagname ) ) { String t [ ] = tokenize ( tag . text ( ) ) ; // l-src label l-dst target t = t . length == 1 ? new String [ ] { "-" , "-" , "-" , t [ 0 ] } : t ; // Shorthand if ( t . length != 4 ) { System . err . println ( "Error in " + from + "\n" + tagname + " expects four fields (l-src label l-dst target): " + tag . text ( ) ) ; return ; } ClassDoc to = from . findClass ( t [ 3 ] ) ; if ( to != null ) { if ( hidden ( to ) ) continue ; relation ( opt , rt , from , to , t [ 0 ] , t [ 1 ] , t [ 2 ] ) ; } else { if ( hidden ( t [ 3 ] ) ) continue ; relation ( opt , rt , from , from . toString ( ) , to , t [ 3 ] , t [ 0 ] , t [ 1 ] , t [ 2 ] ) ; } } } | Print all relations for a given s class s tag | 273 | 10 |
144,508 | public void printRelations ( ClassDoc c ) { Options opt = optionProvider . getOptionsFor ( c ) ; if ( hidden ( c ) || c . name ( ) . equals ( "" ) ) // avoid phantom classes, they may pop up when the source uses annotations return ; // Print generalization (through the Java superclass) Type s = c . superclassType ( ) ; ClassDoc sc = s != null && ! s . qualifiedTypeName ( ) . equals ( Object . class . getName ( ) ) ? s . asClassDoc ( ) : null ; if ( sc != null && ! c . isEnum ( ) && ! hidden ( sc ) ) relation ( opt , RelationType . EXTENDS , c , sc , null , null , null ) ; // Print generalizations (through @extends tags) for ( Tag tag : c . tags ( "extends" ) ) if ( ! hidden ( tag . text ( ) ) ) relation ( opt , RelationType . EXTENDS , c , c . findClass ( tag . text ( ) ) , null , null , null ) ; // Print realizations (Java interfaces) for ( Type iface : c . interfaceTypes ( ) ) { ClassDoc ic = iface . asClassDoc ( ) ; if ( ! hidden ( ic ) ) relation ( opt , RelationType . IMPLEMENTS , c , ic , null , null , null ) ; } // Print other associations allRelation ( opt , RelationType . COMPOSED , c ) ; allRelation ( opt , RelationType . NAVCOMPOSED , c ) ; allRelation ( opt , RelationType . HAS , c ) ; allRelation ( opt , RelationType . NAVHAS , c ) ; allRelation ( opt , RelationType . ASSOC , c ) ; allRelation ( opt , RelationType . NAVASSOC , c ) ; allRelation ( opt , RelationType . DEPEND , c ) ; } | Print a class s relations | 421 | 5 |
144,509 | public void printExtraClasses ( RootDoc root ) { Set < String > names = new HashSet < String > ( classnames . keySet ( ) ) ; for ( String className : names ) { ClassInfo info = getClassInfo ( className , true ) ; if ( info . nodePrinted ) continue ; ClassDoc c = root . classNamed ( className ) ; if ( c != null ) { printClass ( c , false ) ; continue ; } // Handle missing classes: Options opt = optionProvider . getOptionsFor ( className ) ; if ( opt . matchesHideExpression ( className ) ) continue ; w . println ( linePrefix + "// " + className ) ; w . print ( linePrefix + info . name + "[label=" ) ; externalTableStart ( opt , className , classToUrl ( className ) ) ; innerTableStart ( ) ; String qualifiedName = qualifiedName ( opt , className ) ; int startTemplate = qualifiedName . indexOf ( ' ' ) ; int idx = qualifiedName . lastIndexOf ( ' ' , startTemplate < 0 ? qualifiedName . length ( ) - 1 : startTemplate ) ; if ( opt . postfixPackage && idx > 0 && idx < ( qualifiedName . length ( ) - 1 ) ) { String packageName = qualifiedName . substring ( 0 , idx ) ; String cn = qualifiedName . substring ( idx + 1 ) ; tableLine ( Align . CENTER , Font . CLASS . wrap ( opt , escape ( cn ) ) ) ; tableLine ( Align . CENTER , Font . PACKAGE . wrap ( opt , packageName ) ) ; } else { tableLine ( Align . CENTER , Font . CLASS . wrap ( opt , escape ( qualifiedName ) ) ) ; } innerTableEnd ( ) ; externalTableEnd ( ) ; if ( className == null || className . length ( ) == 0 ) w . print ( ",URL=\"" + classToUrl ( className ) + "\"" ) ; nodeProperties ( opt ) ; } } | Print classes that were parts of relationships but not parsed by javadoc | 445 | 15 |
144,510 | public void printInferredRelations ( ClassDoc c ) { // check if the source is excluded from inference if ( hidden ( c ) ) return ; Options opt = optionProvider . getOptionsFor ( c ) ; for ( FieldDoc field : c . fields ( false ) ) { if ( hidden ( field ) ) continue ; // skip statics if ( field . isStatic ( ) ) continue ; // skip primitives FieldRelationInfo fri = getFieldRelationInfo ( field ) ; if ( fri == null ) continue ; // check if the destination is excluded from inference if ( hidden ( fri . cd ) ) continue ; // if source and dest are not already linked, add a dependency RelationPattern rp = getClassInfo ( c , true ) . getRelation ( fri . cd . toString ( ) ) ; if ( rp == null ) { String destAdornment = fri . multiple ? "*" : "" ; relation ( opt , opt . inferRelationshipType , c , fri . cd , "" , "" , destAdornment ) ; } } } | Prints associations recovered from the fields of a class . An association is inferred only if another relation between the two classes is not already in the graph . | 224 | 30 |
144,511 | public void printInferredDependencies ( ClassDoc c ) { if ( hidden ( c ) ) return ; Options opt = optionProvider . getOptionsFor ( c ) ; Set < Type > types = new HashSet < Type > ( ) ; // harvest method return and parameter types for ( MethodDoc method : filterByVisibility ( c . methods ( false ) , opt . inferDependencyVisibility ) ) { types . add ( method . returnType ( ) ) ; for ( Parameter parameter : method . parameters ( ) ) { types . add ( parameter . type ( ) ) ; } } // and the field types if ( ! opt . inferRelationships ) { for ( FieldDoc field : filterByVisibility ( c . fields ( false ) , opt . inferDependencyVisibility ) ) { types . add ( field . type ( ) ) ; } } // see if there are some type parameters if ( c . asParameterizedType ( ) != null ) { ParameterizedType pt = c . asParameterizedType ( ) ; types . addAll ( Arrays . asList ( pt . typeArguments ( ) ) ) ; } // see if type parameters extend something for ( TypeVariable tv : c . typeParameters ( ) ) { if ( tv . bounds ( ) . length > 0 ) types . addAll ( Arrays . asList ( tv . bounds ( ) ) ) ; } // and finally check for explicitly imported classes (this // assumes there are no unused imports...) if ( opt . useImports ) types . addAll ( Arrays . asList ( importedClasses ( c ) ) ) ; // compute dependencies for ( Type type : types ) { // skip primitives and type variables, as well as dependencies // on the source class if ( type . isPrimitive ( ) || type instanceof WildcardType || type instanceof TypeVariable || c . toString ( ) . equals ( type . asClassDoc ( ) . toString ( ) ) ) continue ; // check if the destination is excluded from inference ClassDoc fc = type . asClassDoc ( ) ; if ( hidden ( fc ) ) continue ; // check if source and destination are in the same package and if we are allowed // to infer dependencies between classes in the same package if ( ! opt . inferDepInPackage && c . containingPackage ( ) . equals ( fc . containingPackage ( ) ) ) continue ; // if source and dest are not already linked, add a dependency RelationPattern rp = getClassInfo ( c , true ) . getRelation ( fc . toString ( ) ) ; if ( rp == null || rp . matchesOne ( new RelationPattern ( RelationDirection . OUT ) ) ) { relation ( opt , RelationType . DEPEND , c , fc , "" , "" , "" ) ; } } } | Prints dependencies recovered from the methods of a class . A dependency is inferred only if another relation between the two classes is not already in the graph . | 600 | 30 |
144,512 | private < T extends ProgramElementDoc > List < T > filterByVisibility ( T [ ] docs , Visibility visibility ) { if ( visibility == Visibility . PRIVATE ) return Arrays . asList ( docs ) ; List < T > filtered = new ArrayList < T > ( ) ; for ( T doc : docs ) { if ( Visibility . get ( doc ) . compareTo ( visibility ) > 0 ) filtered . add ( doc ) ; } return filtered ; } | Returns all program element docs that have a visibility greater or equal than the specified level | 101 | 16 |
144,513 | private void firstInnerTableStart ( Options opt ) { w . print ( linePrefix + linePrefix + "<tr>" + opt . shape . extraColumn ( ) + "<td><table border=\"0\" cellspacing=\"0\" " + "cellpadding=\"1\">" + linePostfix ) ; } | Start the first inner table of a class . | 67 | 9 |
144,514 | private File extractThriftFile ( String artifactId , String fileName , Set < File > thriftFiles ) { for ( File thriftFile : thriftFiles ) { boolean fileFound = false ; if ( fileName . equals ( thriftFile . getName ( ) ) ) { for ( String pathComponent : thriftFile . getPath ( ) . split ( File . separator ) ) { if ( pathComponent . equals ( artifactId ) ) { fileFound = true ; } } } if ( fileFound ) { return thriftFile ; } } return null ; } | Picks out a File from thriftFiles corresponding to a given artifact ID and file name . Returns null if artifactId and fileName do not map to a thrift file path . | 121 | 37 |
144,515 | public void execute ( ) throws MojoExecutionException , MojoFailureException { try { Set < File > thriftFiles = findThriftFiles ( ) ; final File outputDirectory = getOutputDirectory ( ) ; ImmutableSet < File > outputFiles = findGeneratedFilesInDirectory ( getOutputDirectory ( ) ) ; Set < String > compileRoots = new HashSet < String > ( ) ; compileRoots . add ( "scrooge" ) ; if ( thriftFiles . isEmpty ( ) ) { getLog ( ) . info ( "No thrift files to compile." ) ; } else if ( checkStaleness && ( ( lastModified ( thriftFiles ) + staleMillis ) < lastModified ( outputFiles ) ) ) { getLog ( ) . info ( "Generated thrift files up to date, skipping compile." ) ; attachFiles ( compileRoots ) ; } else { outputDirectory . mkdirs ( ) ; // Quick fix to fix issues with two mvn installs in a row (ie no clean) cleanDirectory ( outputDirectory ) ; getLog ( ) . info ( format ( "compiling thrift files %s with Scrooge" , thriftFiles ) ) ; synchronized ( lock ) { ScroogeRunner runner = new ScroogeRunner ( ) ; Map < String , String > thriftNamespaceMap = new HashMap < String , String > ( ) ; for ( ThriftNamespaceMapping mapping : thriftNamespaceMappings ) { thriftNamespaceMap . put ( mapping . getFrom ( ) , mapping . getTo ( ) ) ; } // Include thrifts from resource as well. Set < File > includes = thriftIncludes ; includes . add ( getResourcesOutputDirectory ( ) ) ; // Include thrift root final File thriftSourceRoot = getThriftSourceRoot ( ) ; if ( thriftSourceRoot != null && thriftSourceRoot . exists ( ) ) { includes . add ( thriftSourceRoot ) ; } runner . compile ( getLog ( ) , includeOutputDirectoryNamespace ? new File ( outputDirectory , "scrooge" ) : outputDirectory , thriftFiles , includes , thriftNamespaceMap , language , thriftOpts ) ; } attachFiles ( compileRoots ) ; } } catch ( IOException e ) { throw new MojoExecutionException ( "An IO error occurred" , e ) ; } } | Executes the mojo . | 514 | 6 |
144,516 | private long lastModified ( Set < File > files ) { long result = 0 ; for ( File file : files ) { if ( file . lastModified ( ) > result ) result = file . lastModified ( ) ; } return result ; } | Get the last modified time for a set of files . | 53 | 11 |
144,517 | private Set < File > findThriftFiles ( ) throws IOException , MojoExecutionException { final File thriftSourceRoot = getThriftSourceRoot ( ) ; Set < File > thriftFiles = new HashSet < File > ( ) ; if ( thriftSourceRoot != null && thriftSourceRoot . exists ( ) ) { thriftFiles . addAll ( findThriftFilesInDirectory ( thriftSourceRoot ) ) ; } getLog ( ) . info ( "finding thrift files in dependencies" ) ; extractFilesFromDependencies ( findThriftDependencies ( ) , getResourcesOutputDirectory ( ) ) ; if ( buildExtractedThrift && getResourcesOutputDirectory ( ) . exists ( ) ) { thriftFiles . addAll ( findThriftFilesInDirectory ( getResourcesOutputDirectory ( ) ) ) ; } getLog ( ) . info ( "finding thrift files in referenced (reactor) projects" ) ; thriftFiles . addAll ( getReferencedThriftFiles ( ) ) ; return thriftFiles ; } | build a complete set of local files files from referenced projects and dependencies . | 225 | 14 |
144,518 | private Set < Artifact > findThriftDependencies ( ) throws IOException , MojoExecutionException { Set < Artifact > thriftDependencies = new HashSet < Artifact > ( ) ; Set < Artifact > deps = new HashSet < Artifact > ( ) ; deps . addAll ( project . getArtifacts ( ) ) ; deps . addAll ( project . getDependencyArtifacts ( ) ) ; Map < String , Artifact > depsMap = new HashMap < String , Artifact > ( ) ; for ( Artifact dep : deps ) { depsMap . put ( dep . getId ( ) , dep ) ; } for ( Artifact artifact : deps ) { // This artifact has an idl classifier. if ( isIdlCalssifier ( artifact , classifier ) ) { thriftDependencies . add ( artifact ) ; } else { if ( isDepOfIdlArtifact ( artifact , depsMap ) ) { // Fetch idl artifact for dependency of an idl artifact. try { Artifact idlArtifact = MavenScroogeCompilerUtil . getIdlArtifact ( artifact , artifactFactory , artifactResolver , localRepository , remoteArtifactRepositories , classifier ) ; thriftDependencies . add ( idlArtifact ) ; } catch ( MojoExecutionException e ) { /* Do nothing as this artifact is not an idl artifact binary jars may have dependency on thrift lib etc. */ getLog ( ) . debug ( "Could not fetch idl jar for " + artifact ) ; } } } } return thriftDependencies ; } | Iterate through dependencies | 347 | 4 |
144,519 | protected List < File > getRecursiveThriftFiles ( MavenProject project , String outputDirectory ) throws IOException { return getRecursiveThriftFiles ( project , outputDirectory , new ArrayList < File > ( ) ) ; } | Walk project references recursively building up a list of thrift files they provide starting with an empty file list . | 49 | 23 |
144,520 | List < File > getRecursiveThriftFiles ( MavenProject project , String outputDirectory , List < File > files ) throws IOException { HashFunction hashFun = Hashing . md5 ( ) ; File dir = new File ( new File ( project . getFile ( ) . getParent ( ) , "target" ) , outputDirectory ) ; if ( dir . exists ( ) ) { URI baseDir = getFileURI ( dir ) ; for ( File f : findThriftFilesInDirectory ( dir ) ) { URI fileURI = getFileURI ( f ) ; String relPath = baseDir . relativize ( fileURI ) . getPath ( ) ; File destFolder = getResourcesOutputDirectory ( ) ; destFolder . mkdirs ( ) ; File destFile = new File ( destFolder , relPath ) ; if ( ! destFile . exists ( ) || ( destFile . isFile ( ) && ! Files . hash ( f , hashFun ) . equals ( Files . hash ( destFile , hashFun ) ) ) ) { getLog ( ) . info ( format ( "copying %s to %s" , f . getCanonicalPath ( ) , destFile . getCanonicalPath ( ) ) ) ; copyFile ( f , destFile ) ; } files . add ( destFile ) ; } } Map < String , MavenProject > refs = project . getProjectReferences ( ) ; for ( String name : refs . keySet ( ) ) { getRecursiveThriftFiles ( refs . get ( name ) , outputDirectory , files ) ; } return files ; } | Walk project references recursively adding thrift files to the provided list . | 341 | 15 |
144,521 | private boolean isDepOfIdlArtifact ( Artifact artifact , Map < String , Artifact > depsMap ) { List < String > depTrail = artifact . getDependencyTrail ( ) ; // depTrail can be null sometimes, which seems like a maven bug if ( depTrail != null ) { for ( String name : depTrail ) { Artifact dep = depsMap . get ( name ) ; if ( dep != null && isIdlCalssifier ( dep , classifier ) ) { return true ; } } } return false ; } | Checks if the artifact is dependency of an dependent idl artifact | 120 | 13 |
144,522 | public static Artifact getIdlArtifact ( Artifact artifact , ArtifactFactory artifactFactory , ArtifactResolver artifactResolver , ArtifactRepository localRepository , List < ArtifactRepository > remoteRepos , String classifier ) throws MojoExecutionException { Artifact idlArtifact = artifactFactory . createArtifactWithClassifier ( artifact . getGroupId ( ) , artifact . getArtifactId ( ) , artifact . getVersion ( ) , "jar" , classifier ) ; try { artifactResolver . resolve ( idlArtifact , remoteRepos , localRepository ) ; return idlArtifact ; } catch ( final ArtifactResolutionException e ) { throw new MojoExecutionException ( "Failed to resolve one or more idl artifacts:\n\n" + e . getMessage ( ) , e ) ; } catch ( final ArtifactNotFoundException e ) { throw new MojoExecutionException ( "Failed to resolve one or more idl artifacts:\n\n" + e . getMessage ( ) , e ) ; } } | Resolves an idl jar for the artifact . | 222 | 10 |
144,523 | public static < Z > Function0 < Z > lift ( Func0 < Z > f ) { return bridge . lift ( f ) ; } | Lift a Java Func0 to a Scala Function0 | 30 | 12 |
144,524 | public static < A , Z > Function1 < A , Z > lift ( Func1 < A , Z > f ) { return bridge . lift ( f ) ; } | Lift a Java Func1 to a Scala Function1 | 36 | 12 |
144,525 | public static < A , B , Z > Function2 < A , B , Z > lift ( Func2 < A , B , Z > f ) { return bridge . lift ( f ) ; } | Lift a Java Func2 to a Scala Function2 | 42 | 12 |
144,526 | public static < A , B , C , Z > Function3 < A , B , C , Z > lift ( Func3 < A , B , C , Z > f ) { return bridge . lift ( f ) ; } | Lift a Java Func3 to a Scala Function3 | 48 | 12 |
144,527 | public static < A , B , C , D , Z > Function4 < A , B , C , D , Z > lift ( Func4 < A , B , C , D , Z > f ) { return bridge . lift ( f ) ; } | Lift a Java Func4 to a Scala Function4 | 54 | 12 |
144,528 | public static < Z > Function0 < Z > lift ( Callable < Z > f ) { return bridge . lift ( f ) ; } | Lift a Java Callable to a Scala Function0 | 29 | 11 |
144,529 | public static CssSel sel ( String selector , String value ) { return j . sel ( selector , value ) ; } | Create a Css Selector Transform | 27 | 7 |
144,530 | public static < T > Vendor < T > vendor ( Func0 < T > f ) { return j . vendor ( f ) ; } | Create a Vendor from a Func0 | 29 | 8 |
144,531 | public static < T > Vendor < T > vendor ( Callable < T > f ) { return j . vendor ( f ) ; } | Create a Vendor from a Callable | 28 | 7 |
144,532 | public static < T > SessionVar < T > vendSessionVar ( T defValue ) { return ( new VarsJBridge ( ) ) . vendSessionVar ( defValue , new Exception ( ) ) ; } | Vend a SessionVar with the default value | 44 | 9 |
144,533 | public static < T > SessionVar < T > vendSessionVar ( Callable < T > defFunc ) { return ( new VarsJBridge ( ) ) . vendSessionVar ( defFunc , new Exception ( ) ) ; } | Vend a SessionVar with the function to create the default value | 50 | 13 |
144,534 | protected < T1 > void dispatchCommand ( final BiConsumer < P , T1 > action , final T1 routable1 ) { routingFor ( routable1 ) . routees ( ) . forEach ( routee -> routee . receiveCommand ( action , routable1 ) ) ; } | DISPATCHING - COMMANDS | 62 | 8 |
144,535 | @ Nullable public ResultT first ( ) { final CoreRemoteMongoCursor < ResultT > cursor = iterator ( ) ; if ( ! cursor . hasNext ( ) ) { return null ; } return cursor . next ( ) ; } | Helper to return the first item in the iterator or null . | 50 | 12 |
144,536 | public < U > CoreRemoteMongoIterable < U > map ( final Function < ResultT , U > mapper ) { return new CoreRemoteMappingIterable <> ( this , mapper ) ; } | Maps this iterable from the source document type to the target document type . | 45 | 15 |
144,537 | public < A extends Collection < ? super ResultT > > A into ( final A target ) { forEach ( new Block < ResultT > ( ) { @ Override public void apply ( @ Nonnull final ResultT t ) { target . add ( t ) ; } } ) ; return target ; } | Iterates over all the documents adding each to the given target . | 63 | 13 |
144,538 | public AwsServiceClient withCodecRegistry ( @ Nonnull final CodecRegistry codecRegistry ) { return new AwsServiceClientImpl ( proxy . withCodecRegistry ( codecRegistry ) , dispatcher ) ; } | Create a new AwsServiceClient instance with a different codec registry . | 48 | 14 |
144,539 | public void callFunction ( final String name , final List < ? > args , final @ Nullable Long requestTimeout ) { this . functionService . callFunction ( name , args , requestTimeout ) ; } | Calls the specified Stitch function . | 42 | 8 |
144,540 | public < T > T callFunction ( final String name , final List < ? > args , final @ Nullable Long requestTimeout , final Class < T > resultClass , final CodecRegistry codecRegistry ) { return this . functionService . withCodecRegistry ( codecRegistry ) . callFunction ( name , args , requestTimeout , resultClass ) ; } | Calls the specified Stitch function and decodes the response into an instance of the specified type . The response will be decoded using the codec registry given . | 76 | 32 |
144,541 | public void start ( ) { instanceLock . writeLock ( ) . lock ( ) ; try { for ( final Map . Entry < MongoNamespace , NamespaceChangeStreamListener > streamerEntry : nsStreamers . entrySet ( ) ) { streamerEntry . getValue ( ) . start ( ) ; } } finally { instanceLock . writeLock ( ) . unlock ( ) ; } } | Starts all streams . | 82 | 5 |
144,542 | public void stop ( ) { instanceLock . writeLock ( ) . lock ( ) ; try { for ( final NamespaceChangeStreamListener streamer : nsStreamers . values ( ) ) { streamer . stop ( ) ; } } finally { instanceLock . writeLock ( ) . unlock ( ) ; } } | Stops all streams . | 65 | 5 |
144,543 | public void addNamespace ( final MongoNamespace namespace ) { this . instanceLock . writeLock ( ) . lock ( ) ; try { if ( this . nsStreamers . containsKey ( namespace ) ) { return ; } final NamespaceChangeStreamListener streamer = new NamespaceChangeStreamListener ( namespace , instanceConfig . getNamespaceConfig ( namespace ) , service , networkMonitor , authMonitor , getLockForNamespace ( namespace ) ) ; this . nsStreamers . put ( namespace , streamer ) ; } finally { this . instanceLock . writeLock ( ) . unlock ( ) ; } } | Requests that the given namespace be started listening to for change events . | 127 | 14 |
144,544 | @ Override public void removeNamespace ( final MongoNamespace namespace ) { this . instanceLock . writeLock ( ) . lock ( ) ; try { if ( ! this . nsStreamers . containsKey ( namespace ) ) { return ; } final NamespaceChangeStreamListener streamer = this . nsStreamers . get ( namespace ) ; streamer . stop ( ) ; this . nsStreamers . remove ( namespace ) ; } finally { this . instanceLock . writeLock ( ) . unlock ( ) ; } } | Requests that the given namespace stopped being listened to for change events . | 108 | 14 |
144,545 | public Map < BsonValue , ChangeEvent < BsonDocument > > getEventsForNamespace ( final MongoNamespace namespace ) { this . instanceLock . readLock ( ) . lock ( ) ; final NamespaceChangeStreamListener streamer ; try { streamer = nsStreamers . get ( namespace ) ; } finally { this . instanceLock . readLock ( ) . unlock ( ) ; } if ( streamer == null ) { return new HashMap <> ( ) ; } return streamer . getEvents ( ) ; } | Returns the latest change events for a given namespace . | 111 | 10 |
144,546 | public @ Nullable ChangeEvent < BsonDocument > getUnprocessedEventForDocumentId ( final MongoNamespace namespace , final BsonValue documentId ) { this . instanceLock . readLock ( ) . lock ( ) ; final NamespaceChangeStreamListener streamer ; try { streamer = nsStreamers . get ( namespace ) ; } finally { this . instanceLock . readLock ( ) . unlock ( ) ; } if ( streamer == null ) { return null ; } return streamer . getUnprocessedEventForDocumentId ( documentId ) ; } | If there is an unprocessed change event for a particular document ID fetch it from the appropriate namespace change stream listener and remove it . By reading the event here we are assuming it will be processed by the consumer . | 119 | 43 |
144,547 | void setPaused ( final boolean isPaused ) { docLock . writeLock ( ) . lock ( ) ; try { docsColl . updateOne ( getDocFilter ( namespace , documentId ) , new BsonDocument ( "$set" , new BsonDocument ( ConfigCodec . Fields . IS_PAUSED , new BsonBoolean ( isPaused ) ) ) ) ; this . isPaused = isPaused ; } catch ( IllegalStateException e ) { // eat this } finally { docLock . writeLock ( ) . unlock ( ) ; } } | A document that is paused no longer has remote updates applied to it . Any local updates to this document cause it to be thawed . An example of pausing a document is when a conflict is being resolved for that document and the handler throws an exception . | 121 | 51 |
144,548 | public void setSomePendingWritesAndSave ( final long atTime , final ChangeEvent < BsonDocument > changeEvent ) { docLock . writeLock ( ) . lock ( ) ; try { // if we were frozen if ( isPaused ) { // unfreeze the document due to the local write setPaused ( false ) ; // and now the unfrozen document is now stale setStale ( true ) ; } this . lastUncommittedChangeEvent = coalesceChangeEvents ( this . lastUncommittedChangeEvent , changeEvent ) ; this . lastResolution = atTime ; docsColl . replaceOne ( getDocFilter ( namespace , documentId ) , this ) ; } finally { docLock . writeLock ( ) . unlock ( ) ; } } | Sets that there are some pending writes that occurred at a time for an associated locally emitted change event . This variant maintains the last version set . | 162 | 29 |
144,549 | private static ChangeEvent < BsonDocument > coalesceChangeEvents ( final ChangeEvent < BsonDocument > lastUncommittedChangeEvent , final ChangeEvent < BsonDocument > newestChangeEvent ) { if ( lastUncommittedChangeEvent == null ) { return newestChangeEvent ; } switch ( lastUncommittedChangeEvent . getOperationType ( ) ) { case INSERT : switch ( newestChangeEvent . getOperationType ( ) ) { // Coalesce replaces/updates to inserts since we believe at some point a document did not // exist remotely and that this replace or update should really be an insert if we are // still in an uncommitted state. case REPLACE : case UPDATE : return new ChangeEvent <> ( newestChangeEvent . getId ( ) , OperationType . INSERT , newestChangeEvent . getFullDocument ( ) , newestChangeEvent . getNamespace ( ) , newestChangeEvent . getDocumentKey ( ) , null , newestChangeEvent . hasUncommittedWrites ( ) ) ; default : break ; } break ; case DELETE : switch ( newestChangeEvent . getOperationType ( ) ) { // Coalesce inserts to replaces since we believe at some point a document existed // remotely and that this insert should really be an replace if we are still in an // uncommitted state. case INSERT : return new ChangeEvent <> ( newestChangeEvent . getId ( ) , OperationType . REPLACE , newestChangeEvent . getFullDocument ( ) , newestChangeEvent . getNamespace ( ) , newestChangeEvent . getDocumentKey ( ) , null , newestChangeEvent . hasUncommittedWrites ( ) ) ; default : break ; } break ; case UPDATE : switch ( newestChangeEvent . getOperationType ( ) ) { case UPDATE : return new ChangeEvent <> ( newestChangeEvent . getId ( ) , OperationType . UPDATE , newestChangeEvent . getFullDocument ( ) , newestChangeEvent . getNamespace ( ) , newestChangeEvent . getDocumentKey ( ) , lastUncommittedChangeEvent . getUpdateDescription ( ) != null ? lastUncommittedChangeEvent . getUpdateDescription ( ) . merge ( newestChangeEvent . getUpdateDescription ( ) ) : newestChangeEvent . getUpdateDescription ( ) , newestChangeEvent . hasUncommittedWrites ( ) ) ; case REPLACE : return new ChangeEvent <> ( newestChangeEvent . getId ( ) , OperationType . REPLACE , newestChangeEvent . getFullDocument ( ) , newestChangeEvent . getNamespace ( ) , newestChangeEvent . getDocumentKey ( ) , null , newestChangeEvent . hasUncommittedWrites ( ) ) ; default : break ; } break ; case REPLACE : switch ( newestChangeEvent . getOperationType ( ) ) { case UPDATE : return new ChangeEvent <> ( newestChangeEvent . getId ( ) , OperationType . REPLACE , newestChangeEvent . getFullDocument ( ) , newestChangeEvent . getNamespace ( ) , newestChangeEvent . getDocumentKey ( ) , null , newestChangeEvent . hasUncommittedWrites ( ) ) ; default : break ; } break ; default : break ; } return newestChangeEvent ; } | Possibly coalesces the newest change event to match the user s original intent . For example an unsynchronized insert and update is still an insert . | 675 | 31 |
144,550 | static DocumentVersionInfo getRemoteVersionInfo ( final BsonDocument remoteDocument ) { final BsonDocument version = getDocumentVersionDoc ( remoteDocument ) ; return new DocumentVersionInfo ( version , remoteDocument != null ? BsonUtils . getDocumentId ( remoteDocument ) : null ) ; } | Returns the current version info for a provided remote document . | 62 | 11 |
144,551 | static BsonDocument getFreshVersionDocument ( ) { final BsonDocument versionDoc = new BsonDocument ( ) ; versionDoc . append ( Fields . SYNC_PROTOCOL_VERSION_FIELD , new BsonInt32 ( 1 ) ) ; versionDoc . append ( Fields . INSTANCE_ID_FIELD , new BsonString ( UUID . randomUUID ( ) . toString ( ) ) ) ; versionDoc . append ( Fields . VERSION_COUNTER_FIELD , new BsonInt64 ( 0L ) ) ; return versionDoc ; } | Returns a BSON version document representing a new version with a new instance ID and version counter of zero . | 121 | 21 |
144,552 | static BsonDocument getDocumentVersionDoc ( final BsonDocument document ) { if ( document == null || ! document . containsKey ( DOCUMENT_VERSION_FIELD ) ) { return null ; } return document . getDocument ( DOCUMENT_VERSION_FIELD , null ) ; } | Returns the version document of the given document if any ; returns null otherwise . | 60 | 15 |
144,553 | static BsonDocument getVersionedFilter ( @ Nonnull final BsonValue documentId , @ Nullable final BsonValue version ) { final BsonDocument filter = new BsonDocument ( "_id" , documentId ) ; if ( version == null ) { filter . put ( DOCUMENT_VERSION_FIELD , new BsonDocument ( "$exists" , BsonBoolean . FALSE ) ) ; } else { filter . put ( DOCUMENT_VERSION_FIELD , version ) ; } return filter ; } | Returns a query filter for the given document _id and version . The version is allowed to be null . The query will match only if there is either no version on the document in the database in question if we have no reference of the version or if the version matches the database s version . | 109 | 58 |
144,554 | BsonDocument getNextVersion ( ) { if ( ! this . hasVersion ( ) || this . getVersionDoc ( ) == null ) { return getFreshVersionDocument ( ) ; } final BsonDocument nextVersion = BsonUtils . copyOfDocument ( this . getVersionDoc ( ) ) ; nextVersion . put ( Fields . VERSION_COUNTER_FIELD , new BsonInt64 ( this . getVersion ( ) . getVersionCounter ( ) + 1 ) ) ; return nextVersion ; } | Given a DocumentVersionInfo returns a BSON document representing the next version . This means and incremented version count for a non - empty version or a fresh version document for an empty version . | 108 | 38 |
144,555 | public RemoteMongoCollection < Document > getCollection ( final String collectionName ) { return new RemoteMongoCollectionImpl <> ( proxy . getCollection ( collectionName ) , dispatcher ) ; } | Gets a collection . | 40 | 5 |
144,556 | static < T > StitchEvent < T > fromEvent ( final Event event , final Decoder < T > decoder ) { return new StitchEvent <> ( event . getEventName ( ) , event . getData ( ) , decoder ) ; } | Convert a SSE to a Stitch SSE | 54 | 11 |
144,557 | protected final Event processEvent ( ) throws IOException { while ( true ) { String line ; try { line = readLine ( ) ; } catch ( final EOFException ex ) { if ( doneOnce ) { throw ex ; } doneOnce = true ; line = "" ; } // If the line is empty (a blank line), Dispatch the event, as defined below. if ( line . isEmpty ( ) ) { // If the data buffer is an empty string, set the data buffer and the event name buffer to // the empty string and abort these steps. if ( dataBuffer . length ( ) == 0 ) { eventName = "" ; continue ; } // If the event name buffer is not the empty string but is also not a valid NCName, // set the data buffer and the event name buffer to the empty string and abort these steps. // NOT IMPLEMENTED final Event . Builder eventBuilder = new Event . Builder ( ) ; eventBuilder . withEventName ( eventName . isEmpty ( ) ? Event . MESSAGE_EVENT : eventName ) ; eventBuilder . withData ( dataBuffer . toString ( ) ) ; // Set the data buffer and the event name buffer to the empty string. dataBuffer = new StringBuilder ( ) ; eventName = "" ; return eventBuilder . build ( ) ; // If the line starts with a U+003A COLON character (':') } else if ( line . startsWith ( ":" ) ) { // ignore the line // If the line contains a U+003A COLON character (':') character } else if ( line . contains ( ":" ) ) { // Collect the characters on the line before the first U+003A COLON character (':'), // and let field be that string. final int colonIdx = line . indexOf ( ":" ) ; final String field = line . substring ( 0 , colonIdx ) ; // Collect the characters on the line after the first U+003A COLON character (':'), // and let value be that string. // If value starts with a single U+0020 SPACE character, remove it from value. String value = line . substring ( colonIdx + 1 ) ; value = value . startsWith ( " " ) ? value . substring ( 1 ) : value ; processField ( field , value ) ; // Otherwise, the string is not empty but does not contain a U+003A COLON character (':') // character } else { processField ( line , "" ) ; } } } | Process the next event in a given stream . | 530 | 9 |
144,558 | private static String handleRichError ( final Response response , final String body ) { if ( ! response . getHeaders ( ) . containsKey ( Headers . CONTENT_TYPE ) || ! response . getHeaders ( ) . get ( Headers . CONTENT_TYPE ) . equals ( ContentTypes . APPLICATION_JSON ) ) { return body ; } final Document doc ; try { doc = BsonUtils . parseValue ( body , Document . class ) ; } catch ( Exception e ) { return body ; } if ( ! doc . containsKey ( Fields . ERROR ) ) { return body ; } final String errorMsg = doc . getString ( Fields . ERROR ) ; if ( ! doc . containsKey ( Fields . ERROR_CODE ) ) { return errorMsg ; } final String errorCode = doc . getString ( Fields . ERROR_CODE ) ; throw new StitchServiceException ( errorMsg , StitchServiceErrorCode . fromCodeName ( errorCode ) ) ; } | Private helper method which decodes the Stitch error from the body of an HTTP Response object . If the error is successfully decoded this function will throw the error for the end user to eventually consume . If the error cannot be decoded this is likely not an error from the Stitch server and this function will return an error message that the calling function should use as the message of a StitchServiceException with an unknown code . | 208 | 86 |
144,559 | public static void initialize ( final Context context ) { if ( ! initialized . compareAndSet ( false , true ) ) { return ; } applicationContext = context . getApplicationContext ( ) ; final String packageName = applicationContext . getPackageName ( ) ; localAppName = packageName ; final PackageManager manager = applicationContext . getPackageManager ( ) ; try { final PackageInfo pkgInfo = manager . getPackageInfo ( packageName , 0 ) ; localAppVersion = pkgInfo . versionName ; } catch ( final NameNotFoundException e ) { Log . d ( TAG , "Failed to get version of application, will not send in device info." ) ; } Log . d ( TAG , "Initialized android SDK" ) ; } | Initializes the Stitch SDK so that app clients can be created . | 156 | 14 |
144,560 | public static StitchAppClient getAppClient ( @ Nonnull final String clientAppId ) { ensureInitialized ( ) ; synchronized ( Stitch . class ) { if ( ! appClients . containsKey ( clientAppId ) ) { throw new IllegalStateException ( String . format ( "client for app '%s' has not yet been initialized" , clientAppId ) ) ; } return appClients . get ( clientAppId ) ; } } | Gets an app client by its client app id if it has been initialized ; throws if none can be found . | 95 | 23 |
144,561 | public void start ( ) { nsLock . writeLock ( ) . lock ( ) ; try { if ( runnerThread != null ) { return ; } runnerThread = new Thread ( new NamespaceChangeStreamRunner ( new WeakReference <> ( this ) , networkMonitor , logger ) ) ; runnerThread . start ( ) ; } finally { nsLock . writeLock ( ) . unlock ( ) ; } } | Opens the stream in a background thread . | 84 | 9 |
144,562 | public void stop ( ) { if ( runnerThread == null ) { return ; } runnerThread . interrupt ( ) ; nsLock . writeLock ( ) . lock ( ) ; try { if ( runnerThread == null ) { return ; } this . cancel ( ) ; this . close ( ) ; while ( runnerThread . isAlive ( ) ) { runnerThread . interrupt ( ) ; try { runnerThread . join ( 1000 ) ; } catch ( final Exception e ) { e . printStackTrace ( ) ; return ; } } runnerThread = null ; } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { nsLock . writeLock ( ) . unlock ( ) ; } } | Stops the background stream thread . | 149 | 7 |
144,563 | boolean openStream ( ) throws InterruptedException , IOException { logger . info ( "stream START" ) ; final boolean isOpen ; final Set < BsonValue > idsToWatch = nsConfig . getSynchronizedDocumentIds ( ) ; if ( ! networkMonitor . isConnected ( ) ) { logger . info ( "stream END - Network disconnected" ) ; return false ; } if ( idsToWatch . isEmpty ( ) ) { logger . info ( "stream END - No synchronized documents" ) ; return false ; } nsLock . writeLock ( ) . lockInterruptibly ( ) ; try { if ( ! authMonitor . isLoggedIn ( ) ) { logger . info ( "stream END - Logged out" ) ; return false ; } final Document args = new Document ( ) ; args . put ( "database" , namespace . getDatabaseName ( ) ) ; args . put ( "collection" , namespace . getCollectionName ( ) ) ; args . put ( "ids" , idsToWatch ) ; currentStream = service . streamFunction ( "watch" , Collections . singletonList ( args ) , ResultDecoders . changeEventDecoder ( BSON_DOCUMENT_CODEC ) ) ; if ( currentStream != null && currentStream . isOpen ( ) ) { this . nsConfig . setStale ( true ) ; isOpen = true ; } else { isOpen = false ; } } finally { nsLock . writeLock ( ) . unlock ( ) ; } return isOpen ; } | Open the event stream | 327 | 4 |
144,564 | @ SuppressWarnings ( "unchecked" ) public Map < BsonValue , ChangeEvent < BsonDocument > > getEvents ( ) { nsLock . readLock ( ) . lock ( ) ; final Map < BsonValue , ChangeEvent < BsonDocument > > events ; try { events = new HashMap <> ( this . events ) ; } finally { nsLock . readLock ( ) . unlock ( ) ; } nsLock . writeLock ( ) . lock ( ) ; try { this . events . clear ( ) ; return events ; } finally { nsLock . writeLock ( ) . unlock ( ) ; } } | Returns the latest change events and clears them from the change stream listener . | 134 | 14 |
144,565 | public @ Nullable ChangeEvent < BsonDocument > getUnprocessedEventForDocumentId ( final BsonValue documentId ) { final ChangeEvent < BsonDocument > event ; nsLock . readLock ( ) . lock ( ) ; try { event = this . events . get ( documentId ) ; } finally { nsLock . readLock ( ) . unlock ( ) ; } nsLock . writeLock ( ) . lock ( ) ; try { this . events . remove ( documentId ) ; return event ; } finally { nsLock . writeLock ( ) . unlock ( ) ; } } | If there is an unprocessed change event for a particular document ID fetch it from the change stream listener and remove it . By reading the event here we are assuming it will be processed by the consumer . | 124 | 41 |
144,566 | public static long hash ( final BsonDocument doc ) { if ( doc == null ) { return 0L ; } final byte [ ] docBytes = toBytes ( doc ) ; long hashValue = FNV_64BIT_OFFSET_BASIS ; for ( int offset = 0 ; offset < docBytes . length ; offset ++ ) { hashValue ^= ( 0xFF & docBytes [ offset ] ) ; hashValue *= FNV_64BIT_PRIME ; } return hashValue ; } | Implementation of FNV - 1a hash algorithm . | 107 | 11 |
144,567 | public static boolean deleteDatabase ( final StitchAppClientInfo appInfo , final String serviceName , final EmbeddedMongoClientFactory clientFactory , final String userId ) { final String dataDir = appInfo . getDataDirectory ( ) ; if ( dataDir == null ) { throw new IllegalArgumentException ( "StitchAppClient not configured with a data directory" ) ; } final String instanceKey = String . format ( "%s-%s_sync_%s_%s" , appInfo . getClientAppId ( ) , dataDir , serviceName , userId ) ; final String dbPath = String . format ( "%s/%s/sync_mongodb_%s/%s/0/" , dataDir , appInfo . getClientAppId ( ) , serviceName , userId ) ; final MongoClient client = clientFactory . getClient ( instanceKey , dbPath , appInfo . getCodecRegistry ( ) ) ; for ( final String listDatabaseName : client . listDatabaseNames ( ) ) { try { client . getDatabase ( listDatabaseName ) . drop ( ) ; } catch ( Exception e ) { // do nothing } } client . close ( ) ; clientFactory . removeClient ( instanceKey ) ; return new File ( dbPath ) . delete ( ) ; } | Delete a database for a given path and userId . | 277 | 11 |
144,568 | public Task < Long > count ( ) { return dispatcher . dispatchTask ( new Callable < Long > ( ) { @ Override public Long call ( ) { return proxy . count ( ) ; } } ) ; } | Counts the number of documents in the collection . | 45 | 10 |
144,569 | public Task < RemoteInsertOneResult > insertOne ( final DocumentT document ) { return dispatcher . dispatchTask ( new Callable < RemoteInsertOneResult > ( ) { @ Override public RemoteInsertOneResult call ( ) { return proxy . insertOne ( document ) ; } } ) ; } | Inserts the provided document . If the document is missing an identifier the client should generate one . | 61 | 19 |
144,570 | public Task < Void > registerWithEmail ( @ NonNull final String email , @ NonNull final String password ) { return dispatcher . dispatchTask ( new Callable < Void > ( ) { @ Override public Void call ( ) { registerWithEmailInternal ( email , password ) ; return null ; } } ) ; } | Registers a new user with the given email and password . | 66 | 12 |
144,571 | public Task < Void > confirmUser ( @ NonNull final String token , @ NonNull final String tokenId ) { return dispatcher . dispatchTask ( new Callable < Void > ( ) { @ Override public Void call ( ) { confirmUserInternal ( token , tokenId ) ; return null ; } } ) ; } | Confirms a user with the given token and token id . | 66 | 12 |
144,572 | public Task < Void > resendConfirmationEmail ( @ NonNull final String email ) { return dispatcher . dispatchTask ( new Callable < Void > ( ) { @ Override public Void call ( ) { resendConfirmationEmailInternal ( email ) ; return null ; } } ) ; } | Resend the confirmation for a user to the given email . | 61 | 12 |
144,573 | public Task < Void > sendResetPasswordEmail ( @ NonNull final String email ) { return dispatcher . dispatchTask ( new Callable < Void > ( ) { @ Override public Void call ( ) { sendResetPasswordEmailInternal ( email ) ; return null ; } } ) ; } | Sends a user a password reset email for the given email . | 61 | 13 |
144,574 | @ Override public boolean commit ( ) { final CoreRemoteMongoCollection < DocumentT > collection = getCollection ( ) ; final List < WriteModel < DocumentT > > writeModels = getBulkWriteModels ( ) ; // define success as any one operation succeeding for now boolean success = true ; for ( final WriteModel < DocumentT > write : writeModels ) { if ( write instanceof ReplaceOneModel ) { final ReplaceOneModel < DocumentT > replaceModel = ( ( ReplaceOneModel ) write ) ; final RemoteUpdateResult result = collection . updateOne ( replaceModel . getFilter ( ) , ( Bson ) replaceModel . getReplacement ( ) ) ; success = success && ( result != null && result . getModifiedCount ( ) == result . getMatchedCount ( ) ) ; } else if ( write instanceof UpdateOneModel ) { final UpdateOneModel < DocumentT > updateModel = ( ( UpdateOneModel ) write ) ; final RemoteUpdateResult result = collection . updateOne ( updateModel . getFilter ( ) , updateModel . getUpdate ( ) ) ; success = success && ( result != null && result . getModifiedCount ( ) == result . getMatchedCount ( ) ) ; } else if ( write instanceof UpdateManyModel ) { final UpdateManyModel < DocumentT > updateModel = ( ( UpdateManyModel ) write ) ; final RemoteUpdateResult result = collection . updateMany ( updateModel . getFilter ( ) , updateModel . getUpdate ( ) ) ; success = success && ( result != null && result . getModifiedCount ( ) == result . getMatchedCount ( ) ) ; } } return success ; } | Commits the writes to the remote collection . | 353 | 9 |
144,575 | @ Override public Response doRequest ( final StitchRequest stitchReq ) { initAppMetadata ( clientAppId ) ; return super . doRequestUrl ( stitchReq , getHostname ( ) ) ; } | Performs a request against a Stitch app server determined by the deployment model of the underlying app . Throws a Stitch specific exception if the request fails . | 46 | 32 |
144,576 | @ Override public EventStream doStreamRequest ( final StitchRequest stitchReq ) { initAppMetadata ( clientAppId ) ; return super . doStreamRequestUrl ( stitchReq , getHostname ( ) ) ; } | Performs a streaming request against a Stitch app server determined by the deployment model of the underlying app . Throws a Stitch specific exception if the request fails . | 49 | 33 |
144,577 | public BsonDocument toUpdateDocument ( ) { final List < BsonElement > unsets = new ArrayList <> ( ) ; for ( final String removedField : this . removedFields ) { unsets . add ( new BsonElement ( removedField , new BsonBoolean ( true ) ) ) ; } final BsonDocument updateDocument = new BsonDocument ( ) ; if ( this . updatedFields . size ( ) > 0 ) { updateDocument . append ( "$set" , this . updatedFields ) ; } if ( unsets . size ( ) > 0 ) { updateDocument . append ( "$unset" , new BsonDocument ( unsets ) ) ; } return updateDocument ; } | Convert this update description to an update document . | 151 | 10 |
144,578 | public BsonDocument toBsonDocument ( ) { final BsonDocument updateDescDoc = new BsonDocument ( ) ; updateDescDoc . put ( Fields . UPDATED_FIELDS_FIELD , this . getUpdatedFields ( ) ) ; final BsonArray removedFields = new BsonArray ( ) ; for ( final String field : this . getRemovedFields ( ) ) { removedFields . add ( new BsonString ( field ) ) ; } updateDescDoc . put ( Fields . REMOVED_FIELDS_FIELD , removedFields ) ; return updateDescDoc ; } | Converts this update description to its document representation as it would appear in a MongoDB Change Event . | 129 | 20 |
144,579 | public static UpdateDescription fromBsonDocument ( final BsonDocument document ) { keyPresent ( Fields . UPDATED_FIELDS_FIELD , document ) ; keyPresent ( Fields . REMOVED_FIELDS_FIELD , document ) ; final BsonArray removedFieldsArr = document . getArray ( Fields . REMOVED_FIELDS_FIELD ) ; final Set < String > removedFields = new HashSet <> ( removedFieldsArr . size ( ) ) ; for ( final BsonValue field : removedFieldsArr ) { removedFields . add ( field . asString ( ) . getValue ( ) ) ; } return new UpdateDescription ( document . getDocument ( Fields . UPDATED_FIELDS_FIELD ) , removedFields ) ; } | Converts an update description BSON document from a MongoDB Change Event into an UpdateDescription object . | 168 | 20 |
144,580 | public UpdateDescription merge ( @ Nullable final UpdateDescription otherDescription ) { if ( otherDescription != null ) { for ( final Map . Entry < String , BsonValue > entry : this . updatedFields . entrySet ( ) ) { if ( otherDescription . removedFields . contains ( entry . getKey ( ) ) ) { this . updatedFields . remove ( entry . getKey ( ) ) ; } } for ( final String removedField : this . removedFields ) { if ( otherDescription . updatedFields . containsKey ( removedField ) ) { this . removedFields . remove ( removedField ) ; } } this . removedFields . addAll ( otherDescription . removedFields ) ; this . updatedFields . putAll ( otherDescription . updatedFields ) ; } return this ; } | Unilaterally merge an update description into this update description . | 172 | 11 |
144,581 | @ Override @ SuppressWarnings ( "unchecked" ) public Stream < ChangeEvent < DocumentT > > watch ( final BsonValue ... ids ) throws InterruptedException , IOException { return operations . watch ( new HashSet <> ( Arrays . asList ( ids ) ) , false , documentClass ) . execute ( service ) ; } | Watches specified IDs in a collection . | 77 | 8 |
144,582 | public Task < Void > updateSyncFrequency ( @ NonNull final SyncFrequency syncFrequency ) { return this . dispatcher . dispatchTask ( new Callable < Void > ( ) { @ Override public Void call ( ) throws Exception { SyncImpl . this . proxy . updateSyncFrequency ( syncFrequency ) ; return null ; } } ) ; } | Sets the SyncFrequency on this collection . | 75 | 10 |
144,583 | public void emitEvent ( final NamespaceSynchronizationConfig nsConfig , final ChangeEvent < BsonDocument > event ) { listenersLock . lock ( ) ; try { if ( nsConfig . getNamespaceListenerConfig ( ) == null ) { return ; } final NamespaceListenerConfig namespaceListener = nsConfig . getNamespaceListenerConfig ( ) ; eventDispatcher . dispatch ( ( ) -> { try { if ( namespaceListener . getEventListener ( ) != null ) { namespaceListener . getEventListener ( ) . onEvent ( BsonUtils . getDocumentId ( event . getDocumentKey ( ) ) , ChangeEvents . transformChangeEventForUser ( event , namespaceListener . getDocumentCodec ( ) ) ) ; } } catch ( final Exception ex ) { logger . error ( String . format ( Locale . US , "emitEvent ns=%s documentId=%s emit exception: %s" , event . getNamespace ( ) , BsonUtils . getDocumentId ( event . getDocumentKey ( ) ) , ex ) , ex ) ; } return null ; } ) ; } finally { listenersLock . unlock ( ) ; } } | Emits a change event for the given document id . | 246 | 11 |
144,584 | static ChangeEvent < BsonDocument > changeEventForLocalInsert ( final MongoNamespace namespace , final BsonDocument document , final boolean writePending ) { final BsonValue docId = BsonUtils . getDocumentId ( document ) ; return new ChangeEvent <> ( new BsonDocument ( ) , OperationType . INSERT , document , namespace , new BsonDocument ( "_id" , docId ) , null , writePending ) ; } | Generates a change event for a local insert of the given document in the given namespace . | 97 | 18 |
144,585 | static ChangeEvent < BsonDocument > changeEventForLocalUpdate ( final MongoNamespace namespace , final BsonValue documentId , final UpdateDescription update , final BsonDocument fullDocumentAfterUpdate , final boolean writePending ) { return new ChangeEvent <> ( new BsonDocument ( ) , OperationType . UPDATE , fullDocumentAfterUpdate , namespace , new BsonDocument ( "_id" , documentId ) , update , writePending ) ; } | Generates a change event for a local update of a document in the given namespace referring to the given document _id . | 95 | 24 |
144,586 | static ChangeEvent < BsonDocument > changeEventForLocalReplace ( final MongoNamespace namespace , final BsonValue documentId , final BsonDocument document , final boolean writePending ) { return new ChangeEvent <> ( new BsonDocument ( ) , OperationType . REPLACE , document , namespace , new BsonDocument ( "_id" , documentId ) , null , writePending ) ; } | Generates a change event for a local replacement of a document in the given namespace referring to the given document _id . | 86 | 24 |
144,587 | static ChangeEvent < BsonDocument > changeEventForLocalDelete ( final MongoNamespace namespace , final BsonValue documentId , final boolean writePending ) { return new ChangeEvent <> ( new BsonDocument ( ) , OperationType . DELETE , null , namespace , new BsonDocument ( "_id" , documentId ) , null , writePending ) ; } | Generates a change event for a local deletion of a document in the given namespace referring to the given document _id . | 80 | 24 |
144,588 | public static < T > void notNull ( final String name , final T value ) { if ( value == null ) { throw new IllegalArgumentException ( name + " can not be null" ) ; } } | Throw IllegalArgumentException if the value is null . | 44 | 11 |
144,589 | public static void keyPresent ( final String key , final Map < String , ? > map ) { if ( ! map . containsKey ( key ) ) { throw new IllegalStateException ( String . format ( "expected %s to be present" , key ) ) ; } } | Throw IllegalStateException if key is not present in map . | 57 | 12 |
144,590 | public static BsonDocument copyOfDocument ( final BsonDocument document ) { final BsonDocument newDocument = new BsonDocument ( ) ; for ( final Map . Entry < String , BsonValue > kv : document . entrySet ( ) ) { newDocument . put ( kv . getKey ( ) , kv . getValue ( ) ) ; } return newDocument ; } | Returns a copy of the given document . | 82 | 8 |
144,591 | public static < T > ConflictHandler < T > localWins ( ) { return new ConflictHandler < T > ( ) { @ Override public T resolveConflict ( final BsonValue documentId , final ChangeEvent < T > localEvent , final ChangeEvent < T > remoteEvent ) { return localEvent . getFullDocument ( ) ; } } ; } | The local event will decide the next state of the document in question . | 75 | 14 |
144,592 | public static boolean isTodoItem ( final Document todoItemDoc ) { return todoItemDoc . containsKey ( ID_KEY ) && todoItemDoc . containsKey ( TASK_KEY ) && todoItemDoc . containsKey ( CHECKED_KEY ) ; } | Returns if a MongoDB document is a todo item . | 61 | 12 |
144,593 | void recover ( ) { final List < NamespaceSynchronizationConfig > nsConfigs = new ArrayList <> ( ) ; for ( final MongoNamespace ns : this . syncConfig . getSynchronizedNamespaces ( ) ) { nsConfigs . add ( this . syncConfig . getNamespaceConfig ( ns ) ) ; } for ( final NamespaceSynchronizationConfig nsConfig : nsConfigs ) { nsConfig . getLock ( ) . writeLock ( ) . lock ( ) ; } try { for ( final NamespaceSynchronizationConfig nsConfig : nsConfigs ) { nsConfig . getLock ( ) . writeLock ( ) . lock ( ) ; try { recoverNamespace ( nsConfig ) ; } finally { nsConfig . getLock ( ) . writeLock ( ) . unlock ( ) ; } } } finally { for ( final NamespaceSynchronizationConfig nsConfig : nsConfigs ) { nsConfig . getLock ( ) . writeLock ( ) . unlock ( ) ; } } } | Recovers the state of synchronization in case a system failure happened . The goal is to revert to a known good state . | 214 | 24 |
144,594 | public void wipeInMemorySettings ( ) { this . waitUntilInitialized ( ) ; syncLock . lock ( ) ; try { this . instanceChangeStreamListener . stop ( ) ; if ( instancesColl . find ( ) . first ( ) == null ) { throw new IllegalStateException ( "expected to find instance configuration" ) ; } this . syncConfig = new InstanceSynchronizationConfig ( configDb ) ; this . instanceChangeStreamListener = new InstanceChangeStreamListenerImpl ( syncConfig , service , networkMonitor , authMonitor ) ; this . isConfigured = false ; this . stop ( ) ; } finally { syncLock . unlock ( ) ; } } | Reloads the synchronization config . This wipes all in - memory synchronization settings . | 139 | 16 |
144,595 | public void start ( ) { syncLock . lock ( ) ; try { if ( ! this . isConfigured ) { return ; } instanceChangeStreamListener . stop ( ) ; if ( listenersEnabled ) { instanceChangeStreamListener . start ( ) ; } if ( syncThread == null ) { syncThread = new Thread ( new DataSynchronizerRunner ( new WeakReference <> ( this ) , networkMonitor , logger ) , "dataSynchronizerRunnerThread" ) ; } if ( syncThreadEnabled && ! isRunning ) { syncThread . start ( ) ; isRunning = true ; } } finally { syncLock . unlock ( ) ; } } | Starts data synchronization in a background thread . | 136 | 9 |
144,596 | public void stop ( ) { syncLock . lock ( ) ; try { if ( syncThread == null ) { return ; } instanceChangeStreamListener . stop ( ) ; syncThread . interrupt ( ) ; try { syncThread . join ( ) ; } catch ( final InterruptedException e ) { return ; } syncThread = null ; isRunning = false ; } finally { syncLock . unlock ( ) ; } } | Stops the background data synchronization thread . | 86 | 8 |
144,597 | public void close ( ) { this . waitUntilInitialized ( ) ; this . ongoingOperationsGroup . blockAndWait ( ) ; syncLock . lock ( ) ; try { if ( this . networkMonitor != null ) { this . networkMonitor . removeNetworkStateListener ( this ) ; } this . dispatcher . close ( ) ; stop ( ) ; this . localClient . close ( ) ; } finally { syncLock . unlock ( ) ; } } | Stops the background data synchronization thread and releases the local client . | 93 | 13 |
144,598 | public boolean doSyncPass ( ) { if ( ! this . isConfigured || ! syncLock . tryLock ( ) ) { return false ; } try { if ( logicalT == Long . MAX_VALUE ) { if ( logger . isInfoEnabled ( ) ) { logger . info ( "reached max logical time; resetting back to 0" ) ; } logicalT = 0 ; } logicalT ++ ; if ( logger . isInfoEnabled ( ) ) { logger . info ( String . format ( Locale . US , "t='%d': doSyncPass START" , logicalT ) ) ; } if ( networkMonitor == null || ! networkMonitor . isConnected ( ) ) { if ( logger . isInfoEnabled ( ) ) { logger . info ( String . format ( Locale . US , "t='%d': doSyncPass END - Network disconnected" , logicalT ) ) ; } return false ; } if ( authMonitor == null || ! authMonitor . tryIsLoggedIn ( ) ) { if ( logger . isInfoEnabled ( ) ) { logger . info ( String . format ( Locale . US , "t='%d': doSyncPass END - Logged out" , logicalT ) ) ; } return false ; } syncRemoteToLocal ( ) ; syncLocalToRemote ( ) ; if ( logger . isInfoEnabled ( ) ) { logger . info ( String . format ( Locale . US , "t='%d': doSyncPass END" , logicalT ) ) ; } } catch ( InterruptedException e ) { if ( logger . isInfoEnabled ( ) ) { logger . info ( String . format ( Locale . US , "t='%d': doSyncPass INTERRUPTED" , logicalT ) ) ; } return false ; } finally { syncLock . unlock ( ) ; } return true ; } | Performs a single synchronization pass in both the local and remote directions ; the order of which does not matter . If switching the order produces different results after one pass then there is a bug . | 392 | 38 |
144,599 | @ CheckReturnValue private LocalSyncWriteModelContainer resolveConflict ( final NamespaceSynchronizationConfig nsConfig , final CoreDocumentSynchronizationConfig docConfig , final ChangeEvent < BsonDocument > remoteEvent ) { return resolveConflict ( nsConfig , docConfig , docConfig . getLastUncommittedChangeEvent ( ) , remoteEvent ) ; } | Resolves a conflict between a synchronized document s local and remote state . The resolution will result in either the document being desynchronized or being replaced with some resolved state based on the conflict resolver specified for the document . Uses the last uncommitted local event as the local state . | 75 | 56 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.