signature:
public class NativeAuthenticationHelper { /** * Creates a hash of the given user name and password , which is the hex encoding of
 * { @ code MD5 ( < userName > + " : mongo : " + < password > ) } .
 * @ param userName the user name
 * @ param password the password
 * @ return the hash as a string
 * @ mongodb . driver . manual . . / meta - driver / latest / legacy / implement - authentication - in - driver / Authentication */
public static String createAuthenticationHash ( final String userName , final char [ ] password ) { } }

implementation: ByteArrayOutputStream bout = new ByteArrayOutputStream ( userName . length ( ) + 20 + password . length ) ; try { bout . write ( userName . getBytes ( UTF_8_CHARSET ) ) ; bout . write ( ":mongo:" . getBytes ( UTF_8_CHARSET ) ) ; bout . write ( new String ( password ) . getBytes ( UTF_8_CHARSET ) ) ; } catch ( IOException ioe ) { throw new RuntimeException ( "impossible" , ioe ) ; } return hexMD5 ( bout . toByteArray ( ) ) ;


signature:
public class Bytes { /** * Gets the type byte for a given object .
 * @ param object the object
 * @ return the byte value associated with the type , or - 1 if no type is matched */
@ SuppressWarnings ( "deprecation" ) public static byte getType ( final Object object ) { } }

implementation: if ( object == null ) { return NULL ; } if ( object instanceof Integer || object instanceof Short || object instanceof Byte || object instanceof AtomicInteger ) { return NUMBER_INT ; } if ( object instanceof Long || object instanceof AtomicLong ) { return NUMBER_LONG ; } if ( object instanceof Number ) { return NUMBER ; } if ( object instanceof String ) { return STRING ; } if ( object instanceof java . util . List ) { return ARRAY ; } if ( object instanceof byte [ ] ) { return BINARY ; } if ( object instanceof ObjectId ) { return OID ; } if ( object instanceof Boolean ) { return BOOLEAN ; } if ( object instanceof java . util . Date ) { return DATE ; } if ( object instanceof BSONTimestamp ) { return TIMESTAMP ; } if ( object instanceof java . util . regex . Pattern ) { return REGEX ; } if ( object instanceof DBObject || object instanceof DBRef ) { return OBJECT ; } if ( object instanceof CodeWScope ) { return CODE_W_SCOPE ; } if ( object instanceof Code ) { return CODE ; } return - 1 ;


signature:
public class MapReduceCommand { /** * Turns this command into a DBObject representation of this map reduce command .
 * @ return a DBObject that contains the MongoDB document representation of this command . */
public DBObject toDBObject ( ) { } }

implementation: BasicDBObject cmd = new BasicDBObject ( ) ; cmd . put ( "mapreduce" , mapReduce ) ; cmd . put ( "map" , map ) ; cmd . put ( "reduce" , reduce ) ; if ( verbose != null ) { cmd . put ( "verbose" , verbose ) ; } BasicDBObject out = new BasicDBObject ( ) ; switch ( outputType ) { case INLINE : out . put ( "inline" , 1 ) ; break ; case REPLACE : out . put ( "replace" , outputCollection ) ; break ; case MERGE : out . put ( "merge" , outputCollection ) ; break ; case REDUCE : out . put ( "reduce" , outputCollection ) ; break ; default : throw new IllegalArgumentException ( "Unexpected output type" ) ; } if ( outputDB != null ) { out . put ( "db" , outputDB ) ; } cmd . put ( "out" , out ) ; if ( query != null ) { cmd . put ( "query" , query ) ; } if ( finalize != null ) { cmd . put ( "finalize" , finalize ) ; } if ( sort != null ) { cmd . put ( "sort" , sort ) ; } if ( limit > 0 ) { cmd . put ( "limit" , limit ) ; } if ( scope != null ) { cmd . put ( "scope" , scope ) ; } if ( jsMode != null ) { cmd . put ( "jsMode" , jsMode ) ; } if ( maxTimeMS != 0 ) { cmd . put ( "maxTimeMS" , maxTimeMS ) ; } return cmd ;


signature:
public class WriteConcernException { /** * For internal use only : extract the error code from the response to a write command .
 * @ param response the response
 * @ return the code , or - 1 if there is none */
public static int extractErrorCode ( final BsonDocument response ) { } }

implementation:
// mongos may set an err field containing duplicate key error information
String errorMessage = extractErrorMessage ( response ) ; if ( errorMessage != null ) { if ( response . containsKey ( "err" ) ) { if ( errorMessage . contains ( "E11000 duplicate key error" ) ) { return 11000 ; } } // mongos may return a list of documents representing write command responses from each shard . Return the one with a matching
// " err " field , so that it can be used to get the error code
if ( ! response . containsKey ( "code" ) && response . containsKey ( "errObjects" ) ) { for ( BsonValue curErrorDocument : response . getArray ( "errObjects" ) ) { if ( errorMessage . equals ( extractErrorMessage ( curErrorDocument . asDocument ( ) ) ) ) { return curErrorDocument . asDocument ( ) . getNumber ( "code" ) . intValue ( ) ; } } } } return response . getNumber ( "code" , new BsonInt32 ( - 1 ) ) . intValue ( ) ;


signature:
public class WriteConcernException { /** * For internal use only : extract the error message from the response to a write command .
 * @ param response the response
 * @ return the error message */
@ Nullable public static String extractErrorMessage ( final BsonDocument response ) { } }

implementation: if ( response . isString ( "err" ) ) { return response . getString ( "err" ) . getValue ( ) ; } else if ( response . isString ( "errmsg" ) ) { return response . getString ( "errmsg" ) . getValue ( ) ; } else { return null ; }


signature:
public class TlsChannelImpl { /** * read */
public long read ( final ByteBufferSet dest ) throws IOException { } }

implementation:
checkReadBuffer ( dest ) ; if ( ! dest . hasRemaining ( ) ) { return 0 ; } handshake ( ) ; readLock . lock ( ) ; try { if ( invalid || shutdownSent ) { throw new ClosedChannelException ( ) ; } HandshakeStatus handshakeStatus = engine . getHandshakeStatus ( ) ; int bytesToReturn = inPlain . nullOrEmpty ( ) ? 0 : inPlain . buffer . position ( ) ; while ( true ) { if ( bytesToReturn > 0 ) { if ( inPlain . nullOrEmpty ( ) ) { return bytesToReturn ; } else { return transferPendingPlain ( dest ) ; } } if ( shutdownReceived ) { return - 1 ; } Util . assertTrue ( inPlain . nullOrEmpty ( ) ) ; switch ( handshakeStatus ) { case NEED_UNWRAP : case NEED_WRAP : bytesToReturn = handshake ( Optional . of ( dest ) , Optional . of ( handshakeStatus ) ) ; handshakeStatus = NOT_HANDSHAKING ; break ; case NOT_HANDSHAKING : case FINISHED : UnwrapResult res = readAndUnwrap ( Optional . of ( dest ) , NOT_HANDSHAKING /* statusCondition */
, false /* closing */
) ; if ( res . wasClosed ) { return - 1 ; } bytesToReturn = res . bytesProduced ; handshakeStatus = res . lastHandshakeStatus ; break ; case NEED_TASK : handleTask ( ) ; handshakeStatus = engine . getHandshakeStatus ( ) ; break ; default : throw new SSLHandshakeException ( "Unsupported handshake status: " + handshakeStatus ) ; } } } catch ( EofException e ) { return - 1 ; } finally { readLock . unlock ( ) ; }


signature:
public class TlsChannelImpl { /** * write */
public long write ( final ByteBufferSet source ) throws IOException { } }

implementation:
/* * Note that we should enter the write loop even in the case that the source buffer has no remaining bytes ,
 * as it could be the case , in non - blocking usage , that the user is forced to call write again after the
 * underlying channel is available for writing , just to write pending encrypted bytes . */
handshake ( ) ; writeLock . lock ( ) ; try { if ( invalid || shutdownSent ) { throw new ClosedChannelException ( ) ; } return wrapAndWrite ( source ) ; } finally { writeLock . unlock ( ) ; }


signature:
public class ClusterSettings { /** * Returns a short , pretty description for these ClusterSettings .
 * @ return a String description of the relevant settings . */
public String getShortDescription ( ) { } }

implementation: return "{" + ( hosts . isEmpty ( ) ? "" : "hosts=" + hosts ) + ( srvHost == null ? "" : ", srvHost=" + srvHost ) + ", mode=" + mode + ", requiredClusterType=" + requiredClusterType + ", serverSelectionTimeout='" + serverSelectionTimeoutMS + " ms" + '\'' + ", maxWaitQueueSize=" + maxWaitQueueSize + ( requiredReplicaSetName == null ? "" : ", requiredReplicaSetName='" + requiredReplicaSetName + '\'' ) + ( description == null ? "" : ", description='" + description + '\'' ) + '}' ;


signature:
public class UpdateResult { /** * Create an acknowledged UpdateResult
 * @ param matchedCount the number of documents matched
 * @ param modifiedCount the number of documents modified
 * @ param upsertedId if the replace resulted in an inserted document , the id of the inserted document
 * @ return an acknowledged UpdateResult */
public static UpdateResult acknowledged ( final long matchedCount , @ Nullable final Long modifiedCount , @ Nullable final BsonValue upsertedId ) { } }

implementation: return new AcknowledgedUpdateResult ( matchedCount , modifiedCount , upsertedId ) ;


signature:
public class GridFSFile { /** * The content type of the file
 * @ return the content type of the file
 * @ deprecated content type information should be stored the metadata document instead . */
@ Deprecated public String getContentType ( ) { } }

implementation: if ( extraElements != null && extraElements . containsKey ( "contentType" ) ) { return extraElements . getString ( "contentType" ) ; } else { throw new MongoGridFSException ( "No contentType data for this GridFS file" ) ; }


signature:
public class GridFSFile { /** * The aliases for the file
 * @ return the aliases of the file
 * @ deprecated any aliases should be stored in the metadata document instead . */
@ Deprecated @ SuppressWarnings ( "unchecked" ) public List < String > getAliases ( ) { } }

implementation: if ( extraElements != null && extraElements . containsKey ( "aliases" ) ) { return ( List < String > ) extraElements . get ( "aliases" ) ; } else { throw new MongoGridFSException ( "No aliases data for this GridFS file" ) ; }


signature:
public class AbstractByteBufBsonDocument { /** * Gets the first key in this document , or null if the document is empty .
 * @ return the first key in this document , or null if the document is empty */
public String getFirstKey ( ) { } }

implementation: return findInDocument ( new Finder < String > ( ) { @ Override public String find ( final BsonReader bsonReader ) { return bsonReader . readName ( ) ; } @ Override public String notFound ( ) { throw new NoSuchElementException ( ) ; } } ) ;


signature:
public class Sorts { /** * Create a sort specification for an ascending sort on the given fields .
 * @ param fieldNames the field names , which must contain at least one
 * @ return the sort specification
 * @ mongodb . driver . manual reference / operator / meta / orderby Sort */
public static Bson ascending ( final List < String > fieldNames ) { } }

implementation: notNull ( "fieldNames" , fieldNames ) ; return orderBy ( fieldNames , new BsonInt32 ( 1 ) ) ;


signature:
public class Sorts { /** * Create a sort specification for an ascending sort on the given fields .
 * @ param fieldNames the field names , which must contain at least one
 * @ return the sort specification
 * @ mongodb . driver . manual reference / operator / meta / orderby Sort */
public static Bson descending ( final List < String > fieldNames ) { } }

implementation: notNull ( "fieldNames" , fieldNames ) ; return orderBy ( fieldNames , new BsonInt32 ( - 1 ) ) ;


signature:
public class EncoderContext { /** * Creates a child context based on this and serializes the value with it to the writer .
 * @ param encoder the encoder to encode value with
 * @ param writer the writer to encode to
 * @ param value the value to encode
 * @ param < T > the type of the value */
public < T > void encodeWithChildContext ( final Encoder < T > encoder , final BsonWriter writer , final T value ) { } }

implementation: encoder . encode ( writer , value , DEFAULT_CONTEXT ) ;


signature:
public class JSONSerializers { /** * Returns an { @ code ObjectSerializer } that mostly conforms to the strict JSON format defined in
 * < a href = " http : / / docs . mongodb . org / manual / reference / mongodb - extended - json / " > extended JSON < / a > , but with a few differences to keep
 * compatibility with previous versions of the driver . Clients should generally prefer { @ code getStrict } in preference to this method .
 * @ return object serializer
 * @ mongodb . driver . manual reference / mongodb - extended - json / MongoDB Extended JSON
 * @ see # getStrict ( ) */
public static ObjectSerializer getLegacy ( ) { } }

implementation: ClassMapBasedObjectSerializer serializer = addCommonSerializers ( ) ; serializer . addObjectSerializer ( Date . class , new LegacyDateSerializer ( serializer ) ) ; serializer . addObjectSerializer ( BSONTimestamp . class , new LegacyBSONTimestampSerializer ( serializer ) ) ; serializer . addObjectSerializer ( Binary . class , new LegacyBinarySerializer ( ) ) ; serializer . addObjectSerializer ( byte [ ] . class , new LegacyBinarySerializer ( ) ) ; return serializer ;


signature:
public class JSONSerializers { /** * Returns an { @ code ObjectSerializer } that conforms to the strict JSON format defined in
 * < a href = " http : / / docs . mongodb . org / manual / reference / mongodb - extended - json / " > extended JSON < / a > .
 * @ return object serializer
 * @ mongodb . driver . manual reference / mongodb - extended - json / MongoDB Extended JSON */
public static ObjectSerializer getStrict ( ) { } }

implementation: ClassMapBasedObjectSerializer serializer = addCommonSerializers ( ) ; serializer . addObjectSerializer ( Date . class , new DateSerializer ( serializer ) ) ; serializer . addObjectSerializer ( BSONTimestamp . class , new BSONTimestampSerializer ( serializer ) ) ; serializer . addObjectSerializer ( Binary . class , new BinarySerializer ( serializer ) ) ; serializer . addObjectSerializer ( byte [ ] . class , new ByteArraySerializer ( serializer ) ) ; return serializer ;


signature:
public class ReadConcern { /** * Gets this read concern as a document .
 * @ return The read concern as a BsonDocument */
public BsonDocument asDocument ( ) { } }

implementation: BsonDocument readConcern = new BsonDocument ( ) ; if ( level != null ) { readConcern . put ( "level" , new BsonString ( level . getValue ( ) ) ) ; } return readConcern ;


signature:
public class CLI { /** * CHECKSTYLE : ON */
private static com . mongodb . Mongo getMongo ( ) throws Exception { } }

implementation: if ( mongo == null ) { mongo = new MongoClient ( host ) ; } return mongo ;


signature:
public class CLI { /** * CHECKSTYLE : OFF */
public static void main ( final String [ ] args ) throws Exception { } }

implementation: if ( args . length < 1 ) { printUsage ( ) ; return ; } for ( int i = 0 ; i < args . length ; i ++ ) { String s = args [ i ] ; if ( s . equals ( "--db" ) ) { db = args [ i + 1 ] ; i ++ ; continue ; } if ( s . equals ( "--host" ) ) { host = args [ i + 1 ] ; i ++ ; continue ; } if ( s . equals ( "help" ) ) { printUsage ( ) ; return ; } if ( s . equals ( "list" ) ) { GridFS fs = getGridFS ( ) ; System . out . printf ( "%-60s %-10s%n" , "Filename" , "Length" ) ; DBCursor fileListCursor = fs . getFileList ( ) ; try { while ( fileListCursor . hasNext ( ) ) { DBObject o = fileListCursor . next ( ) ; System . out . printf ( "%-60s %-10d%n" , o . get ( "filename" ) , ( ( Number ) o . get ( "length" ) ) . longValue ( ) ) ; } } finally { fileListCursor . close ( ) ; } return ; } if ( s . equals ( "get" ) ) { GridFS fs = getGridFS ( ) ; String fn = args [ i + 1 ] ; GridFSDBFile f = fs . findOne ( fn ) ; if ( f == null ) { System . err . println ( "can't find file: " + fn ) ; return ; } f . writeTo ( f . getFilename ( ) ) ; return ; } if ( s . equals ( "put" ) ) { GridFS fs = getGridFS ( ) ; String fn = args [ i + 1 ] ; GridFSInputFile f = fs . createFile ( new File ( fn ) ) ; f . save ( ) ; f . validate ( ) ; return ; } if ( s . equals ( "md5" ) ) { GridFS fs = getGridFS ( ) ; String fn = args [ i + 1 ] ; GridFSDBFile f = fs . findOne ( fn ) ; if ( f == null ) { System . err . println ( "can't find file: " + fn ) ; return ; } MessageDigest md5 = MessageDigest . getInstance ( "MD5" ) ; md5 . reset ( ) ; int read = 0 ; DigestInputStream is = new DigestInputStream ( f . getInputStream ( ) , md5 ) ; try { while ( is . read ( ) >= 0 ) { read ++ ; int r = is . read ( new byte [ 17 ] ) ; if ( r < 0 ) { break ; } read += r ; } } finally { is . close ( ) ; } byte [ ] digest = md5 . digest ( ) ; System . out . println ( "length: " + read + " md5: " + Util . toHex ( digest ) ) ; return ; } System . err . println ( "unknown option: " + s ) ; return ; }


signature:
public class SnappyCompressor { /** * be copied into a single byte array . For that reason the compress method defined in the base class can ' t be used . */
@ Override public void compress ( final List < ByteBuf > source , final BsonOutput target ) { } }

implementation: int uncompressedSize = getUncompressedSize ( source ) ; byte [ ] singleByteArraySource = new byte [ uncompressedSize ] ; copy ( source , singleByteArraySource ) ; try { byte [ ] out = new byte [ Snappy . maxCompressedLength ( uncompressedSize ) ] ; int compressedSize = Snappy . compress ( singleByteArraySource , 0 , singleByteArraySource . length , out , 0 ) ; target . writeBytes ( out , 0 , compressedSize ) ; } catch ( IOException e ) { throw new MongoInternalException ( "Unexpected IOException" , e ) ; }


signature:
public class CursorHelper { /** * < p > Gets the limit of the number of documents in the OP _ REPLY response to the get more request . A value of zero tells the server to
 * use the default size . A negative value tells the server to return no more than that number and immediately close the cursor .
 * Otherwise , the server will return no more than that number and return the same cursorId to allow the rest of the documents to be
 * fetched , if it turns out there are more documents . < / p >
 * < p > The value returned by this method is based on the limit , the batch size , both of which can be positive , negative , or zero , and the
 * number of documents fetched so far . < / p >
 * @ return the value for numberToReturn in the OP _ GET _ MORE wire protocol message .
 * @ mongodb . driver . manual . . / meta - driver / latest / legacy / mongodb - wire - protocol / # op - get - more OP _ GET _ MORE
 * @ param limit the user - specified limit on the number of results returned
 * @ param batchSize the user - specified batch size
 * @ param numReturnedSoFar the number of results returned so far */
static int getNumberToReturn ( final int limit , final int batchSize , final int numReturnedSoFar ) { } }

implementation: int numberToReturn ; if ( Math . abs ( limit ) != 0 ) { numberToReturn = Math . abs ( limit ) - numReturnedSoFar ; if ( batchSize != 0 && numberToReturn > Math . abs ( batchSize ) ) { numberToReturn = batchSize ; } } else { numberToReturn = batchSize ; } return numberToReturn ;


signature:
public class BasicBSONObject { /** * Returns the value of a field as an { @ code int } .
 * @ param key the field to look for
 * @ return the field value ( or default ) */
public int getInt ( final String key ) { } }

implementation: Object o = get ( key ) ; if ( o == null ) { throw new NullPointerException ( "no value for: " + key ) ; } return toInt ( o ) ;


signature:
public class BasicBSONObject { /** * Returns the value of a field as an { @ code int } .
 * @ param key the field to look for
 * @ param def the default to return
 * @ return the field value ( or default ) */
public int getInt ( final String key , final int def ) { } }

implementation: Object foo = get ( key ) ; if ( foo == null ) { return def ; } return toInt ( foo ) ;


signature:
public class BasicBSONObject { /** * Returns the value of a field as a { @ code long } .
 * @ param key the field to return
 * @ return the field value */
public long getLong ( final String key ) { } }

implementation: Object foo = get ( key ) ; return ( ( Number ) foo ) . longValue ( ) ;


signature:
public class BasicBSONObject { /** * Returns the value of a field as a { @ code double } .
 * @ param key the field to return
 * @ return the field value */
public double getDouble ( final String key ) { } }

implementation: Object foo = get ( key ) ; return ( ( Number ) foo ) . doubleValue ( ) ;


signature:
public class BasicBSONObject { /** * Returns the value of a field as a string
 * @ param key the field to look up
 * @ return the value of the field , converted to a string */
public String getString ( final String key ) { } }

implementation: Object foo = get ( key ) ; if ( foo == null ) { return null ; } return foo . toString ( ) ;


signature:
public class BasicBSONObject { /** * Returns the value of a field as a boolean
 * @ param key the field to look up
 * @ param def the default value in case the field is not found
 * @ return the value of the field , converted to a string */
public boolean getBoolean ( final String key , final boolean def ) { } }

implementation: Object foo = get ( key ) ; if ( foo == null ) { return def ; } if ( foo instanceof Number ) { return ( ( Number ) foo ) . intValue ( ) > 0 ; } if ( foo instanceof Boolean ) { return ( Boolean ) foo ; } throw new IllegalArgumentException ( "can't coerce to bool:" + foo . getClass ( ) ) ;


signature:
public class BasicBSONObject { /** * Returns the object id or def if not set .
 * @ param field The field to return
 * @ param def the default value in case the field is not found
 * @ return The field object value or def if not set . */
public ObjectId getObjectId ( final String field , final ObjectId def ) { } }

implementation: Object foo = get ( field ) ; return ( foo != null ) ? ( ObjectId ) foo : def ;


signature:
public class BasicBSONObject { /** * Returns the date or def if not set .
 * @ param field The field to return
 * @ param def the default value in case the field is not found
 * @ return The field object value or def if not set . */
public Date getDate ( final String field , final Date def ) { } }

implementation: Object foo = get ( field ) ; return ( foo != null ) ? ( Date ) foo : def ;


signature:
public class BasicBSONObject { /** * create a copy of " from " , but with keys ordered alphabetically */
@ SuppressWarnings ( "unchecked" ) private static Object canonicalize ( final Object from ) { } }

implementation: if ( from instanceof BSONObject && ! ( from instanceof BasicBSONList ) ) { return canonicalizeBSONObject ( ( BSONObject ) from ) ; } else if ( from instanceof List ) { return canonicalizeList ( ( List < Object > ) from ) ; } else if ( from instanceof Map ) { return canonicalizeMap ( ( Map < String , Object > ) from ) ; } else { return from ; }


signature:
public class FindOneAndUpdateOptions { /** * Sets the maximum execution time on the server for this operation .
 * @ param maxTime the max time
 * @ param timeUnit the time unit , which may not be null
 * @ return this */
public FindOneAndUpdateOptions maxTime ( final long maxTime , final TimeUnit timeUnit ) { } }

implementation: notNull ( "timeUnit" , timeUnit ) ; this . maxTimeMS = MILLISECONDS . convert ( maxTime , timeUnit ) ; return this ;


signature:
public class MongoClient { /** * Gets the credential that this client authenticates all connections with
 * @ return the credential , which may be null in unsecured deployments
 * @ since 3.9 */
@ Nullable public MongoCredential getCredential ( ) { } }

implementation: if ( getCredentialsList ( ) . size ( ) > 1 ) { throw new IllegalStateException ( "Instance constructed with more than one MongoCredential" ) ; } else if ( getCredentialsList ( ) . isEmpty ( ) ) { return null ; } else { return getCredentialsList ( ) . get ( 0 ) ; }


signature:
public class MongoClient { /** * Gets the list of databases
 * @ param clazz the class to cast the database documents to
 * @ param < T > the type of the class to use instead of { @ code Document } .
 * @ return the list of databases
 * @ since 3.0 */
public < T > ListDatabasesIterable < T > listDatabases ( final Class < T > clazz ) { } }

implementation: return createListDatabasesIterable ( null , clazz ) ;


signature:
public class MongoClient { /** * Gets the list of databases
 * @ param clientSession the client session with which to associate this operation
 * @ param clazz the class to cast the database documents to
 * @ param < T > the type of the class to use instead of { @ code Document } .
 * @ return the list of databases
 * @ since 3.6
 * @ mongodb . server . release 3.6 */
public < T > ListDatabasesIterable < T > listDatabases ( final ClientSession clientSession , final Class < T > clazz ) { } }

implementation: notNull ( "clientSession" , clientSession ) ; return createListDatabasesIterable ( clientSession , clazz ) ;


signature:
public class MongoClient { /** * Creates a client session .
 * @ param options the options for the client session
 * @ return the client session
 * @ throws MongoClientException if the MongoDB cluster to which this client is connected does not support sessions
 * @ mongodb . server . release 3.6
 * @ since 3.6 */
public ClientSession startSession ( final ClientSessionOptions options ) { } }

implementation: ClientSession clientSession = createClientSession ( notNull ( "options" , options ) ) ; if ( clientSession == null ) { throw new MongoClientException ( "Sessions are not supported by the MongoDB cluster to which this client is connected" ) ; } return clientSession ;


signature:
public class Observables { /** * Convert a { @ link MongoIterable } into an { @ link Observable } .
 * @ param mongoIterable the MongoIterable to subscribe to
 * @ param < TResult > The type of result being observed
 * @ return the observable version of the mongoIterable */
public static < TResult > Observable < TResult > observe ( final MongoIterable < TResult > mongoIterable ) { } }

implementation: return new Observable < TResult > ( ) { @ Override public void subscribe ( final Observer < ? super TResult > observer ) { new MongoIterableSubscription < TResult > ( mongoIterable , observer ) ; } } ;


signature:
public class Observables { /** * Allows the conversion of { @ link SingleResultCallback } based operations into an { @ link Observable }
 * < p > Requires a { @ link Block } that is passed the callback to be used with the operation .
 * This is required to make sure that the operation only occurs once the { @ link Subscription } signals for data . < / p >
 * A typical example would be when wrapping callback based methods to make them observable . < br >
 * For example , converting { @ link MongoCollection # count ( SingleResultCallback ) } into an { @ link Observable } :
 * < pre >
 * { @ code
 * Observable < Long > countObservable = observe ( new Block < SingleResultCallback < Long > > ( ) {
 * public void apply ( final SingleResultCallback < Long > callback ) {
 * collection . countDocuments ( callback ) ;
 * < / pre >
 * @ param operation the block that implements the operation .
 * @ param < TResult > The type of result being observed
 * @ return the observable version of the callback based operation */
public static < TResult > Observable < TResult > observe ( final Block < SingleResultCallback < TResult > > operation ) { } }

implementation: return new Observable < TResult > ( ) { @ Override public void subscribe ( final Observer < ? super TResult > observer ) { new SingleResultCallbackSubscription < TResult > ( operation , observer ) ; } } ;


signature:
public class Observables { /** * Allows the conversion of { @ link SingleResultCallback } based operations and flattens the results in an { @ link Observable } .
 * < p > Requires a { @ link Block } that is passed the callback to be used with the operation .
 * This is required to make sure that the operation only occurs once the { @ link Subscription } signals for data . < / p >
 * @ param operation the operation that is passed a callback and is used to delay execution of an operation until demanded .
 * @ param < TResult > The type of result being observed
 * @ return a subscription */
public static < TResult > Observable < TResult > observeAndFlatten ( final Block < SingleResultCallback < List < TResult > > > operation ) { } }

implementation: return new Observable < TResult > ( ) { @ Override public void subscribe ( final Observer < ? super TResult > observer ) { new FlatteningSingleResultCallbackSubscription < TResult > ( operation , observer ) ; } } ;


signature:
public class JsonReader { /** * CHECKSTYLE : OFF */
@ Override public BsonType readBsonType ( ) { } }

implementation:
if ( isClosed ( ) ) { throw new IllegalStateException ( "This instance has been closed" ) ; } if ( getState ( ) == State . INITIAL || getState ( ) == State . DONE || getState ( ) == State . SCOPE_DOCUMENT ) { // in JSON the top level value can be of any type so fall through
setState ( State . TYPE ) ; } if ( getState ( ) != State . TYPE ) { throwInvalidState ( "readBSONType" , State . TYPE ) ; } if ( getContext ( ) . getContextType ( ) == BsonContextType . DOCUMENT ) { JsonToken nameToken = popToken ( ) ; switch ( nameToken . getType ( ) ) { case STRING : case UNQUOTED_STRING : setCurrentName ( nameToken . getValue ( String . class ) ) ; break ; case END_OBJECT : setState ( State . END_OF_DOCUMENT ) ; return BsonType . END_OF_DOCUMENT ; default : throw new JsonParseException ( "JSON reader was expecting a name but found '%s'." , nameToken . getValue ( ) ) ; } JsonToken colonToken = popToken ( ) ; if ( colonToken . getType ( ) != JsonTokenType . COLON ) { throw new JsonParseException ( "JSON reader was expecting ':' but found '%s'." , colonToken . getValue ( ) ) ; } } JsonToken token = popToken ( ) ; if ( getContext ( ) . getContextType ( ) == BsonContextType . ARRAY && token . getType ( ) == JsonTokenType . END_ARRAY ) { setState ( State . END_OF_ARRAY ) ; return BsonType . END_OF_DOCUMENT ; } boolean noValueFound = false ; switch ( token . getType ( ) ) { case BEGIN_ARRAY : setCurrentBsonType ( BsonType . ARRAY ) ; break ; case BEGIN_OBJECT : visitExtendedJSON ( ) ; break ; case DOUBLE : setCurrentBsonType ( BsonType . DOUBLE ) ; currentValue = token . getValue ( ) ; break ; case END_OF_FILE : setCurrentBsonType ( BsonType . END_OF_DOCUMENT ) ; break ; case INT32 : setCurrentBsonType ( BsonType . INT32 ) ; currentValue = token . getValue ( ) ; break ; case INT64 : setCurrentBsonType ( BsonType . INT64 ) ; currentValue = token . getValue ( ) ; break ; case REGULAR_EXPRESSION : setCurrentBsonType ( BsonType . REGULAR_EXPRESSION ) ; currentValue = token . getValue ( ) ; break ; case STRING : setCurrentBsonType ( BsonType . STRING ) ; currentValue = token . getValue ( ) ; break ; case UNQUOTED_STRING : String value = token . getValue ( String . class ) ; if ( "false" . equals ( value ) || "true" . equals ( value ) ) { setCurrentBsonType ( BsonType . BOOLEAN ) ; currentValue = Boolean . parseBoolean ( value ) ; } else if ( "Infinity" . equals ( value ) ) { setCurrentBsonType ( BsonType . DOUBLE ) ; currentValue = Double . POSITIVE_INFINITY ; } else if ( "NaN" . equals ( value ) ) { setCurrentBsonType ( BsonType . DOUBLE ) ; currentValue = Double . NaN ; } else if ( "null" . equals ( value ) ) { setCurrentBsonType ( BsonType . NULL ) ; } else if ( "undefined" . equals ( value ) ) { setCurrentBsonType ( BsonType . UNDEFINED ) ; } else if ( "MinKey" . equals ( value ) ) { visitEmptyConstructor ( ) ; setCurrentBsonType ( BsonType . MIN_KEY ) ; currentValue = new MinKey ( ) ; } else if ( "MaxKey" . equals ( value ) ) { visitEmptyConstructor ( ) ; setCurrentBsonType ( BsonType . MAX_KEY ) ; currentValue = new MaxKey ( ) ; } else if ( "BinData" . equals ( value ) ) { setCurrentBsonType ( BsonType . BINARY ) ; currentValue = visitBinDataConstructor ( ) ; } else if ( "Date" . equals ( value ) ) { currentValue = visitDateTimeConstructorWithOutNew ( ) ; setCurrentBsonType ( BsonType . STRING ) ; } else if ( "HexData" . equals ( value ) ) { setCurrentBsonType ( BsonType . BINARY ) ; currentValue = visitHexDataConstructor ( ) ; } else if ( "ISODate" . equals ( value ) ) { setCurrentBsonType ( BsonType . DATE_TIME ) ; currentValue = visitISODateTimeConstructor ( ) ; } else if ( "NumberInt" . equals ( value ) ) { setCurrentBsonType ( BsonType . INT32 ) ; currentValue = visitNumberIntConstructor ( ) ; } else if ( "NumberLong" . equals ( value ) ) { setCurrentBsonType ( BsonType . INT64 ) ; currentValue = visitNumberLongConstructor ( ) ; } else if ( "NumberDecimal" . equals ( value ) ) { setCurrentBsonType ( BsonType . DECIMAL128 ) ; currentValue = visitNumberDecimalConstructor ( ) ; } else if ( "ObjectId" . equals ( value ) ) { setCurrentBsonType ( BsonType . OBJECT_ID ) ; currentValue = visitObjectIdConstructor ( ) ; } else if ( "Timestamp" . equals ( value ) ) { setCurrentBsonType ( BsonType . TIMESTAMP ) ; currentValue = visitTimestampConstructor ( ) ; } else if ( "RegExp" . equals ( value ) ) { setCurrentBsonType ( BsonType . REGULAR_EXPRESSION ) ; currentValue = visitRegularExpressionConstructor ( ) ; } else if ( "DBPointer" . equals ( value ) ) { setCurrentBsonType ( BsonType . DB_POINTER ) ; currentValue = visitDBPointerConstructor ( ) ; } else if ( "UUID" . equals ( value ) || "GUID" . equals ( value ) || "CSUUID" . equals ( value ) || "CSGUID" . equals ( value ) || "JUUID" . equals ( value ) || "JGUID" . equals ( value ) || "PYUUID" . equals ( value ) || "PYGUID" . equals ( value ) ) { setCurrentBsonType ( BsonType . BINARY ) ; currentValue = visitUUIDConstructor ( value ) ; } else if ( "new" . equals ( value ) ) { visitNew ( ) ; } else { noValueFound = true ; } break ; default : noValueFound = true ; break ; } if ( noValueFound ) { throw new JsonParseException ( "JSON reader was expecting a value but found '%s'." , token . getValue ( ) ) ; } if ( getContext ( ) . getContextType ( ) == BsonContextType . ARRAY || getContext ( ) . getContextType ( ) == BsonContextType . DOCUMENT ) { JsonToken commaToken = popToken ( ) ; if ( commaToken . getType ( ) != JsonTokenType . COMMA ) { pushToken ( commaToken ) ; } } switch ( getContext ( ) . getContextType ( ) ) { case DOCUMENT : case SCOPE_DOCUMENT : default : setState ( State . NAME ) ; break ; case ARRAY : case JAVASCRIPT_WITH_SCOPE : case TOP_LEVEL : setState ( State . VALUE ) ; break ; } return getCurrentBsonType ( ) ;


signature:
public class WriteConcern { /** * Gets the wTimeout in the given time unit .
 * @ param timeUnit the non - null time unit for the result
 * @ return the WTimeout , which may be null if a wTimeout has not been specified
 * @ since 3.2
 * @ mongodb . driver . manual core / write - concern / # timeouts wTimeout */
@ Nullable public Integer getWTimeout ( final TimeUnit timeUnit ) { } }

implementation: notNull ( "timeUnit" , timeUnit ) ; return wTimeoutMS == null ? null : ( int ) timeUnit . convert ( wTimeoutMS , TimeUnit . MILLISECONDS ) ;


signature:
public class WriteConcern { /** * Gets this write concern as a document .
 * @ return The write concern as a BsonDocument , even if { @ code w & lt ; = 0} */
public BsonDocument asDocument ( ) { } }

implementation: BsonDocument document = new BsonDocument ( ) ; addW ( document ) ; addWTimeout ( document ) ; addFSync ( document ) ; addJ ( document ) ; return document ;


signature:
public class WriteConcern { /** * Returns true if this write concern indicates that write operations must be acknowledged .
 * @ return true w ! = null or w & gt ; 0 or journal is true or fsync is true
 * @ mongodb . driver . manual core / write - concern / # acknowledged Acknowledged */
public boolean isAcknowledged ( ) { } }

implementation: if ( w instanceof Integer ) { return ( Integer ) w > 0 || ( journal != null && journal ) || ( fsync != null && fsync ) ; } return true ;


signature:
public class WriteConcern { /** * Constructs a new WriteConcern from the current one and the specified integer - based value for w
 * @ param w number of servers to ensure write propagation to before acknowledgment , which must be { @ code > = 0}
 * @ return the new WriteConcern
 * @ mongodb . driver . manual core / write - concern / # replica - acknowledged Replica Acknowledged */
public WriteConcern withW ( final int w ) { } }

implementation: return new WriteConcern ( Integer . valueOf ( w ) , wTimeoutMS , fsync , journal ) ;


signature:
public class WriteConcern { /** * Constructs a new WriteConcern from the current one and the specified tag - set based value for w
 * @ param w tag set , or " majority " , representing the servers to ensure write propagation to before acknowledgment . Do not use string
 * representation of integer values for w
 * @ return the new WriteConcern
 * @ see # withW ( int )
 * @ mongodb . driver . manual tutorial / configure - replica - set - tag - sets / # replica - set - configuration - tag - sets Tag Sets */
public WriteConcern withW ( final String w ) { } }

implementation: notNull ( "w" , w ) ; return new WriteConcern ( w , wTimeoutMS , fsync , journal ) ;


signature:
public class WriteConcern { /** * Constructs a new WriteConcern from the current one and the specified wTimeout in the given time unit .
 * @ param wTimeout the wTimeout , which must be & gt ; = 0 and & lt ; = Integer . MAX _ VALUE after conversion to milliseconds
 * @ param timeUnit the non - null time unit to apply to wTimeout
 * @ return the WriteConcern with the given wTimeout
 * @ since 3.2
 * @ mongodb . driver . manual reference / write - concern / # wtimeout wtimeout option */
public WriteConcern withWTimeout ( final long wTimeout , final TimeUnit timeUnit ) { } }

implementation: notNull ( "timeUnit" , timeUnit ) ; long newWTimeOutMS = TimeUnit . MILLISECONDS . convert ( wTimeout , timeUnit ) ; isTrueArgument ( "wTimeout >= 0" , wTimeout >= 0 ) ; isTrueArgument ( "wTimeout <= " + Integer . MAX_VALUE + " ms" , newWTimeOutMS <= Integer . MAX_VALUE ) ; return new WriteConcern ( w , ( int ) newWTimeOutMS , fsync , journal ) ;


signature:
public class WriteConcern { /** * Create a Majority Write Concern that requires a majority of servers to acknowledge the write .
 * @ param wtimeout timeout for write operation
 * @ param fsync whether or not to fsync
 * @ param j whether writes should wait for a journal group commit
 * @ return Majority , a subclass of WriteConcern that represents the write concern requiring most servers to acknowledge the write
 * @ deprecated Prefer { @ link # MAJORITY } , { @ link # withWTimeout ( long , TimeUnit ) } , { @ link # withJournal ( Boolean ) } */
@ Deprecated public static Majority majorityWriteConcern ( final int wtimeout , final boolean fsync , final boolean j ) { } }

implementation: return new Majority ( wtimeout , fsync , j ) ;


signature:
public class BulkWriteOperation { /** * Add an insert request to the bulk operation
 * @ param document the document to insert */
public void insert ( final DBObject document ) { } }

implementation: isTrue ( "already executed" , ! closed ) ; if ( document . get ( ID_FIELD_NAME ) == null ) { document . put ( ID_FIELD_NAME , new ObjectId ( ) ) ; } addRequest ( new InsertRequest ( document , collection . getObjectCodec ( ) ) ) ;


signature:
public class BulkWriteOperation { /** * Start building a write request to add to the bulk write operation . The returned builder can be used to create an update , replace ,
 * or remove request with the given query .
 * @ param query the query for an update , replace or remove request
 * @ return a builder for a single write request */
public BulkWriteRequestBuilder find ( final DBObject query ) { } }

implementation: isTrue ( "already executed" , ! closed ) ; return new BulkWriteRequestBuilder ( this , query , collection . getDefaultDBObjectCodec ( ) , collection . getObjectCodec ( ) ) ;


signature:
public class BulkWriteOperation { /** * Execute the bulk write operation with the default write concern of the collection from which this came . Note that the
 * continueOnError property of the write concern is ignored .
 * @ return the result of the bulk write operation .
 * @ throws com . mongodb . BulkWriteException if the write failed due some other failure specific to the write command
 * @ throws MongoException if the operation failed for some other reason */
public BulkWriteResult execute ( ) { } }

implementation: isTrue ( "already executed" , ! closed ) ; closed = true ; return collection . executeBulkWriteOperation ( ordered , bypassDocumentValidation , requests ) ;


signature:
public class BasicDBObject { /** * Parses a string in MongoDB Extended JSON format to a { @ code BasicDBObject } .
 * @ param json the JSON string
 * @ return a corresponding { @ code BasicDBObject } object
 * @ see org . bson . json . JsonReader
 * @ mongodb . driver . manual reference / mongodb - extended - json / MongoDB Extended JSON */
public static BasicDBObject parse ( final String json ) { } }

implementation: return parse ( json , DBObjectCodec . getDefaultRegistry ( ) . get ( BasicDBObject . class ) ) ;


signature:
public class BasicDBObject { /** * Parses a string in MongoDB Extended JSON format to a { @ code BasicDBObject } .
 * @ param json the JSON string
 * @ param decoder the decoder to use to decode the BasicDBObject instance
 * @ return a corresponding { @ code BasicDBObject } object
 * @ see org . bson . json . JsonReader
 * @ mongodb . driver . manual reference / mongodb - extended - json / MongoDB Extended JSON */
public static BasicDBObject parse ( final String json , final Decoder < BasicDBObject > decoder ) { } }

implementation: return decoder . decode ( new JsonReader ( json ) , DecoderContext . builder ( ) . build ( ) ) ;


signature:
public class BasicDBObject { /** * Add a key / value pair to this object
 * @ param key the field name
 * @ param val the field value
 * @ return this BasicDBObject with the new values added */
@ Override public BasicDBObject append ( final String key , final Object val ) { } }

implementation: put ( key , val ) ; return this ;


signature:
public class BasicDBObject { /** * Gets a JSON representation of this document
 * < p > With the default { @ link DBObjectCodec } . < / p >
 * @ param writerSettings the json writer settings to use when encoding
 * @ return a JSON representation of this document
 * @ throws org . bson . codecs . configuration . CodecConfigurationException if the document contains types not in the default registry */
public String toJson ( final JsonWriterSettings writerSettings ) { } }

implementation: return toJson ( writerSettings , DBObjectCodec . getDefaultRegistry ( ) . get ( BasicDBObject . class ) ) ;


signature:
public class BasicDBObject { /** * Creates a new instance which is a copy of this BasicDBObject .
 * @ return a BasicDBObject with exactly the same values as this instance . */
public Object copy ( ) { } }

implementation:
// copy field values into new object
BasicDBObject newCopy = new BasicDBObject ( this . toMap ( ) ) ; // need to clone the sub obj
for ( final String field : keySet ( ) ) { Object val = get ( field ) ; if ( val instanceof BasicDBObject ) { newCopy . put ( field , ( ( BasicDBObject ) val ) . copy ( ) ) ; } else if ( val instanceof BasicDBList ) { newCopy . put ( field , ( ( BasicDBList ) val ) . copy ( ) ) ; } } return newCopy ;


signature:
public class Indexes { /** * Create an index key for an ascending index on the given fields .
 * @ param fieldNames the field names , which must contain at least one
 * @ return the index specification
 * @ mongodb . driver . manual core / indexes indexes */
public static Bson ascending ( final List < String > fieldNames ) { } }

implementation: notNull ( "fieldNames" , fieldNames ) ; return compoundIndex ( fieldNames , new BsonInt32 ( 1 ) ) ;


signature:
public class Indexes { /** * Create an index key for an ascending index on the given fields .
 * @ param fieldNames the field names , which must contain at least one
 * @ return the index specification
 * @ mongodb . driver . manual core / indexes indexes */
public static Bson descending ( final List < String > fieldNames ) { } }

implementation: notNull ( "fieldNames" , fieldNames ) ; return compoundIndex ( fieldNames , new BsonInt32 ( - 1 ) ) ;


signature:
public class Indexes { /** * Create an index key for an ascending index on the given fields .
 * @ param fieldNames the field names , which must contain at least one
 * @ return the index specification
 * @ mongodb . driver . manual core / indexes indexes */
public static Bson geo2dsphere ( final List < String > fieldNames ) { } }

implementation: notNull ( "fieldNames" , fieldNames ) ; return compoundIndex ( fieldNames , new BsonString ( "2dsphere" ) ) ;


signature:
public class Indexes { /** * Create an index key for a geohaystack index on the given field .
 * < strong > Note : < / strong > For queries that use spherical geometry , a 2dsphere index is a better option than a haystack index .
 * 2dsphere indexes allow field reordering ; geoHaystack indexes require the first field to be the location field . Also , geoHaystack
 * indexes are only usable via commands and so always return all results at once . .
 * @ param fieldName the field to create a geoHaystack index on
 * @ param additional the additional field that forms the geoHaystack index key
 * @ return the index specification
 * @ mongodb . driver . manual core / geohaystack geoHaystack index */
public static Bson geoHaystack ( final String fieldName , final Bson additional ) { } }

implementation: notNull ( "fieldName" , fieldName ) ; return compoundIndex ( new BsonDocument ( fieldName , new BsonString ( "geoHaystack" ) ) , additional ) ;


signature:
public class CreateIndexesOperation { /** * Gets the index names .
 * @ return a list of index names */
public List < String > getIndexNames ( ) { } }

implementation: List < String > indexNames = new ArrayList < String > ( requests . size ( ) ) ; for ( IndexRequest request : requests ) { if ( request . getName ( ) != null ) { indexNames . add ( request . getName ( ) ) ; } else { indexNames . add ( IndexHelper . generateIndexName ( request . getKeys ( ) ) ) ; } } return indexNames ;


signature:
public class FindOptions { /** * Sets the maximum await execution time on the server for this operation .
 * @ param maxAwaitTime the max await time . A zero value will be ignored , and indicates that the driver should respect the server ' s
 * default value
 * @ param timeUnit the time unit , which may not be null
 * @ return this
 * @ since 3.2
 * @ mongodb . driver . manual reference / method / cursor . maxTimeMS / # cursor . maxTimeMS Max Time */
public FindOptions maxAwaitTime ( final long maxAwaitTime , final TimeUnit timeUnit ) { } }

implementation: notNull ( "timeUnit" , timeUnit ) ; isTrueArgument ( "maxAwaitTime > = 0" , maxAwaitTime >= 0 ) ; this . maxAwaitTimeMS = TimeUnit . MILLISECONDS . convert ( maxAwaitTime , timeUnit ) ; return this ;


signature:
public class BsonDocument { /** * Parses a string in MongoDB Extended JSON format to a { @ code BsonDocument }
 * @ param json the JSON string
 * @ return a corresponding { @ code BsonDocument } object
 * @ see org . bson . json . JsonReader
 * @ mongodb . driver . manual reference / mongodb - extended - json / MongoDB Extended JSON */
public static BsonDocument parse ( final String json ) { } }

implementation: return new BsonDocumentCodec ( ) . decode ( new JsonReader ( json ) , DecoderContext . builder ( ) . build ( ) ) ;


signature:
public class BsonDocument { /** * If the document does not contain the given key , return the given default value . Otherwise , gets the value of the key .
 * @ param key the key
 * @ param defaultValue the default value
 * @ return the value of the key as a BsonValue */
public BsonValue get ( final Object key , final BsonValue defaultValue ) { } }

implementation: BsonValue value = get ( key ) ; return value != null ? value : defaultValue ;


signature:
public class BsonDocument { /** * If the document does not contain the given key , return the given default value . Otherwise , gets the value of the key as a
 * BsonDocument .
 * @ param key the key
 * @ param defaultValue the default value
 * @ return the value of the key as a BsonDocument
 * @ throws org . bson . BsonInvalidOperationException if the document contains the key but the value is not of the expected type */
public BsonDocument getDocument ( final Object key , final BsonDocument defaultValue ) { } }

implementation: if ( ! containsKey ( key ) ) { return defaultValue ; } return get ( key ) . asDocument ( ) ;


signature:
public class BsonDocument { /** * If the document does not contain the given key , return the given default value . Otherwise , gets the value of the key as a
 * BsonArray .
 * @ param key the key
 * @ param defaultValue the default value
 * @ return the value of the key as a BsonArray
 * @ throws org . bson . BsonInvalidOperationException if the document contains the key but the value is not of the expected type */
public BsonArray getArray ( final Object key , final BsonArray defaultValue ) { } }

implementation: if ( ! containsKey ( key ) ) { return defaultValue ; } return get ( key ) . asArray ( ) ;


signature:
public class BsonDocument { /** * If the document does not contain the given key , return the given default value . Otherwise , gets the value of the key as a
 * BsonNumber .
 * @ param key the key
 * @ param defaultValue the default value
 * @ return the value of the key as a BsonNumber
 * @ throws org . bson . BsonInvalidOperationException if the document contains the key but the value is not of the expected type */
public BsonNumber getNumber ( final Object key , final BsonNumber defaultValue ) { } }

implementation: if ( ! containsKey ( key ) ) { return defaultValue ; } return get ( key ) . asNumber ( ) ;


signature:
public class BsonDocument { /** * If the document does not contain the given key , return the given default value . Otherwise , gets the value of the key as a
 * BsonInt32.
 * @ param key the key
 * @ param defaultValue the default value
 * @ return the value of the key as a BsonInt32
 * @ throws org . bson . BsonInvalidOperationException if the document contains the key but the value is not of the expected type */
public BsonInt32 getInt32 ( final Object key , final BsonInt32 defaultValue ) { } }

implementation: if ( ! containsKey ( key ) ) { return defaultValue ; } return get ( key ) . asInt32 ( ) ;


signature:
public class BsonDocument { /** * If the document does not contain the given key , return the given default value . Otherwise , gets the value of the key as a
 * BsonInt64.
 * @ param key the key
 * @ param defaultValue the default value
 * @ return the value of the key as a BsonInt64
 * @ throws org . bson . BsonInvalidOperationException if the document contains the key but the value is not of the expected type */
public BsonInt64 getInt64 ( final Object key , final BsonInt64 defaultValue ) { } }

implementation: if ( ! containsKey ( key ) ) { return defaultValue ; } return get ( key ) . asInt64 ( ) ;


signature:
public class BsonDocument { /** * If the document does not contain the given key , return the given default value . Otherwise , gets the value of the key as a
 * BsonDecimal128.
 * @ param key the key
 * @ param defaultValue the default value
 * @ return the value of the key as a BsonDecimal128
 * @ throws org . bson . BsonInvalidOperationException if the document contains the key but the value is not of the expected type
 * @ since 3.4 */
public BsonDecimal128 getDecimal128 ( final Object key , final BsonDecimal128 defaultValue ) { } }

implementation: if ( ! containsKey ( key ) ) { return defaultValue ; } return get ( key ) . asDecimal128 ( ) ;


signature:
public class BsonDocument { /** * If the document does not contain the given key , return the given default value . Otherwise , gets the value of the key as a
 * BsonDouble .
 * @ param key the key
 * @ param defaultValue the default value
 * @ return the value of the key as a BsonDouble
 * @ throws org . bson . BsonInvalidOperationException if the document contains the key but the value is not of the expected type */
public BsonDouble getDouble ( final Object key , final BsonDouble defaultValue ) { } }

implementation: if ( ! containsKey ( key ) ) { return defaultValue ; } return get ( key ) . asDouble ( ) ;


signature:
public class BsonDocument { /** * If the document does not contain the given key , return the given default value . Otherwise , gets the value of the key as a
 * BsonBoolean .
 * @ param key the key
 * @ param defaultValue the default value
 * @ return the value of the key as a BsonBoolean
 * @ throws org . bson . BsonInvalidOperationException if the document contains the key but the value is not of the expected type */
public BsonBoolean getBoolean ( final Object key , final BsonBoolean defaultValue ) { } }

implementation: if ( ! containsKey ( key ) ) { return defaultValue ; } return get ( key ) . asBoolean ( ) ;


signature:
public class BsonDocument { /** * If the document does not contain the given key , return the given default value . Otherwise , gets the value of the key as a
 * BsonString .
 * @ param key the key
 * @ param defaultValue the default value
 * @ return the value of the key as a BsonString
 * @ throws org . bson . BsonInvalidOperationException if the document contains the key but the value is not of the expected type */
public BsonString getString ( final Object key , final BsonString defaultValue ) { } }

implementation: if ( ! containsKey ( key ) ) { return defaultValue ; } return get ( key ) . asString ( ) ;


signature:
public class BsonDocument { /** * If the document does not contain the given key , return the given default value . Otherwise , gets the value of the key as a
 * BsonDateTime .
 * @ param key the key
 * @ param defaultValue the default value
 * @ return the value of the key as a BsonDateTime
 * @ throws org . bson . BsonInvalidOperationException if the document contains the key but the value is not of the expected type */
public BsonDateTime getDateTime ( final Object key , final BsonDateTime defaultValue ) { } }

implementation: if ( ! containsKey ( key ) ) { return defaultValue ; } return get ( key ) . asDateTime ( ) ;


signature:
public class BsonDocument { /** * If the document does not contain the given key , return the given default value . Otherwise , gets the value of the key as a
 * BsonTimestamp .
 * @ param key the key
 * @ param defaultValue the default value
 * @ return the value of the key as a BsonTimestamp
 * @ throws org . bson . BsonInvalidOperationException if the document contains the key but the value is not of the expected type */
public BsonTimestamp getTimestamp ( final Object key , final BsonTimestamp defaultValue ) { } }

implementation: if ( ! containsKey ( key ) ) { return defaultValue ; } return get ( key ) . asTimestamp ( ) ;


signature:
public class BsonDocument { /** * If the document does not contain the given key , return the given default value . Otherwise , gets the value of the key as a
 * BsonObjectId .
 * @ param key the key
 * @ param defaultValue the default value
 * @ return the value of the key as a BsonObjectId
 * @ throws org . bson . BsonInvalidOperationException if the document contains the key but the value is not of the expected type */
public BsonObjectId getObjectId ( final Object key , final BsonObjectId defaultValue ) { } }

implementation: if ( ! containsKey ( key ) ) { return defaultValue ; } return get ( key ) . asObjectId ( ) ;


signature:
public class BsonDocument { /** * If the document does not contain the given key , return the given default value . Otherwise , gets the value of the key as a
 * BsonBinary .
 * @ param key the key
 * @ param defaultValue the default value
 * @ return the value of the key as a BsonBinary
 * @ throws org . bson . BsonInvalidOperationException if the document contains the key but the value is not of the expected type */
public BsonBinary getBinary ( final Object key , final BsonBinary defaultValue ) { } }

implementation: if ( ! containsKey ( key ) ) { return defaultValue ; } return get ( key ) . asBinary ( ) ;


signature:
public class BsonDocument { /** * If the document does not contain the given key , return the given default value . Otherwise , gets the value of the key as a
 * BsonRegularExpression .
 * @ param key the key
 * @ param defaultValue the default value
 * @ return the value of the key as a BsonRegularExpression
 * @ throws org . bson . BsonInvalidOperationException if the document contains the key but the value is not of the expected type */
public BsonRegularExpression getRegularExpression ( final Object key , final BsonRegularExpression defaultValue ) { } }

implementation: if ( ! containsKey ( key ) ) { return defaultValue ; } return get ( key ) . asRegularExpression ( ) ;


signature:
public class BsonDocument { /** * Gets a JSON representation of this document using the given { @ code JsonWriterSettings } .
 * @ param settings the JSON writer settings
 * @ return a JSON representation of this document */
public String toJson ( final JsonWriterSettings settings ) { } }

implementation: StringWriter writer = new StringWriter ( ) ; new BsonDocumentCodec ( ) . encode ( new JsonWriter ( writer , settings ) , this , EncoderContext . builder ( ) . build ( ) ) ; return writer . toString ( ) ;


signature:
public class AsynchronousTlsChannelGroup { /** * Intended use of the channel group is with sockets that run tasks internally , but out of tolerance , run tasks in
 * thread in case the socket does not . */
private void writeHandlingTasks ( final RegisteredSocket socket , final WriteOperation op ) throws IOException { } }

implementation: while ( true ) { try { socket . tlsChannel . write ( op . bufferSet . array , op . bufferSet . offset , op . bufferSet . length ) ; return ; } catch ( NeedsTaskException e ) { warnAboutNeedTask ( ) ; e . getTask ( ) . run ( ) ; } }


signature:
public class ChangeStreamOperation { /** * Sets the maximum await execution time on the server for this operation .
 * @ param maxAwaitTime the max await time . A value less than one will be ignored , and indicates that the driver should respect the
 * server ' s default value
 * @ param timeUnit the time unit , which may not be null
 * @ return this */
public ChangeStreamOperation < T > maxAwaitTime ( final long maxAwaitTime , final TimeUnit timeUnit ) { } }

implementation: wrapped . maxAwaitTime ( maxAwaitTime , timeUnit ) ; return this ;


signature:
public class BsonDocumentWrapper { /** * A helper to convert an document of type Object to a BsonDocument
 * < p > If not already a BsonDocument it looks up the documents ' class in the codecRegistry and wraps it into a BsonDocumentWrapper < / p >
 * @ param document the document to convert
 * @ param codecRegistry the codecRegistry that can be used in the conversion of the Object
 * @ return a BsonDocument */
@ SuppressWarnings ( { } }

implementation: "rawtypes" , "unchecked" } ) public static BsonDocument asBsonDocument ( final Object document , final CodecRegistry codecRegistry ) { if ( document == null ) { return null ; } if ( document instanceof BsonDocument ) { return ( BsonDocument ) document ; } else { return new BsonDocumentWrapper ( document , codecRegistry . get ( document . getClass ( ) ) ) ; }


signature:
public class GridFSTour { /** * Run this main method to see the output of this quick example .
 * @ param args takes an optional single argument for the connection string
 * @ throws FileNotFoundException if the sample file cannot be found
 * @ throws IOException if there was an exception closing an input stream
 * @ throws InterruptedException if a latch was interrupted */
public static void main ( final String [ ] args ) throws FileNotFoundException , InterruptedException , IOException { } }

implementation:
MongoClient mongoClient ; if ( args . length == 0 ) { // connect to the local database server
mongoClient = MongoClients . create ( ) ; } else { mongoClient = MongoClients . create ( args [ 0 ] ) ; } // get handle to " mydb " database
MongoDatabase database = mongoClient . getDatabase ( "mydb" ) ; final CountDownLatch dropLatch = new CountDownLatch ( 1 ) ; database . drop ( new SingleResultCallback < Void > ( ) { @ Override public void onResult ( final Void result , final Throwable t ) { dropLatch . countDown ( ) ; } } ) ; dropLatch . await ( ) ; GridFSBucket gridFSBucket = GridFSBuckets . create ( database ) ; /* * UploadFromStream Example */
// Get the input stream
final AsyncInputStream streamToUploadFrom = toAsyncInputStream ( "MongoDB Tutorial.." . getBytes ( StandardCharsets . UTF_8 ) ) ; // Create some custom options
GridFSUploadOptions options = new GridFSUploadOptions ( ) . chunkSizeBytes ( 1024 ) . metadata ( new Document ( "type" , "presentation" ) ) ; final AtomicReference < ObjectId > fileIdRef = new AtomicReference < ObjectId > ( ) ; final CountDownLatch uploadLatch = new CountDownLatch ( 1 ) ; gridFSBucket . uploadFromStream ( "mongodb-tutorial" , streamToUploadFrom , options , new SingleResultCallback < ObjectId > ( ) { @ Override public void onResult ( final ObjectId result , final Throwable t ) { fileIdRef . set ( result ) ; System . out . println ( "The fileId of the uploaded file is: " + result . toHexString ( ) ) ; streamToUploadFrom . close ( new SingleResultCallback < Void > ( ) { @ Override public void onResult ( final Void result , final Throwable t ) { uploadLatch . countDown ( ) ; } } ) ; } } ) ; uploadLatch . await ( ) ; ObjectId fileId = fileIdRef . get ( ) ; /* * OpenUploadStream Example */
// Get some data to write
ByteBuffer data = ByteBuffer . wrap ( "Data to upload into GridFS" . getBytes ( StandardCharsets . UTF_8 ) ) ; final CountDownLatch uploadLatch2 = new CountDownLatch ( 2 ) ; final GridFSUploadStream uploadStream = gridFSBucket . openUploadStream ( "sampleData" ) ; uploadStream . write ( data , new SingleResultCallback < Integer > ( ) { @ Override public void onResult ( final Integer result , final Throwable t ) { uploadLatch2 . countDown ( ) ; System . out . println ( "The fileId of the uploaded file is: " + uploadStream . getObjectId ( ) . toHexString ( ) ) ; uploadStream . close ( new SingleResultCallback < Void > ( ) { @ Override public void onResult ( final Void result , final Throwable t ) { uploadLatch2 . countDown ( ) ; } } ) ; } } ) ; uploadLatch2 . await ( ) ; /* * Find documents */
final CountDownLatch findLatch = new CountDownLatch ( 1 ) ; System . out . println ( "File names:" ) ; gridFSBucket . find ( ) . forEach ( new Block < GridFSFile > ( ) { @ Override public void apply ( final GridFSFile gridFSFile ) { System . out . println ( " - " + gridFSFile . getFilename ( ) ) ; } } , new SingleResultCallback < Void > ( ) { @ Override public void onResult ( final Void result , final Throwable t ) { findLatch . countDown ( ) ; } } ) ; findLatch . await ( ) ; /* * Find documents with a filter */
final CountDownLatch findLatch2 = new CountDownLatch ( 1 ) ; gridFSBucket . find ( eq ( "metadata.contentType" , "image/png" ) ) . forEach ( new Block < GridFSFile > ( ) { @ Override public void apply ( final GridFSFile gridFSFile ) { System . out . println ( gridFSFile . getFilename ( ) ) ; } } , new SingleResultCallback < Void > ( ) { @ Override public void onResult ( final Void result , final Throwable t ) { findLatch2 . countDown ( ) ; } } ) ; findLatch2 . await ( ) ; /* * DownloadToStream */
Path outputPath = Paths . get ( "/tmp/mongodb-tutorial.txt" ) ; AsynchronousFileChannel streamToDownloadTo = AsynchronousFileChannel . open ( outputPath , StandardOpenOption . CREATE_NEW , StandardOpenOption . WRITE , StandardOpenOption . DELETE_ON_CLOSE ) ; final CountDownLatch downloadLatch = new CountDownLatch ( 1 ) ; gridFSBucket . downloadToStream ( fileId , channelToOutputStream ( streamToDownloadTo ) , new SingleResultCallback < Long > ( ) { @ Override public void onResult ( final Long result , final Throwable t ) { downloadLatch . countDown ( ) ; System . out . println ( "downloaded file sized: " + result ) ; } } ) ; downloadLatch . await ( ) ; streamToDownloadTo . close ( ) ; /* * DownloadToStreamByName */
final CountDownLatch downloadLatch2 = new CountDownLatch ( 1 ) ; streamToDownloadTo = AsynchronousFileChannel . open ( outputPath , StandardOpenOption . CREATE_NEW , StandardOpenOption . WRITE , StandardOpenOption . DELETE_ON_CLOSE ) ; GridFSDownloadOptions downloadOptions = new GridFSDownloadOptions ( ) . revision ( 0 ) ; gridFSBucket . downloadToStream ( "mongodb-tutorial" , channelToOutputStream ( streamToDownloadTo ) , downloadOptions , new SingleResultCallback < Long > ( ) { @ Override public void onResult ( final Long result , final Throwable t ) { downloadLatch2 . countDown ( ) ; System . out . println ( "downloaded file sized: " + result ) ; } } ) ; downloadLatch2 . await ( ) ; streamToDownloadTo . close ( ) ; /* * OpenDownloadStream */
final CountDownLatch downloadLatch3 = new CountDownLatch ( 1 ) ; final ByteBuffer dstByteBuffer = ByteBuffer . allocate ( 1024 * 1024 ) ; final GridFSDownloadStream downloadStream = gridFSBucket . openDownloadStream ( fileId ) ; downloadStream . read ( dstByteBuffer , new SingleResultCallback < Integer > ( ) { @ Override public void onResult ( final Integer result , final Throwable t ) { dstByteBuffer . flip ( ) ; byte [ ] bytes = new byte [ result ] ; dstByteBuffer . get ( bytes ) ; System . out . println ( new String ( bytes , StandardCharsets . UTF_8 ) ) ; downloadStream . close ( new SingleResultCallback < Void > ( ) { @ Override public void onResult ( final Void result , final Throwable t ) { downloadLatch3 . countDown ( ) ; } } ) ; } } ) ; downloadLatch3 . await ( ) ; /* * OpenDownloadStreamByName */
System . out . println ( "ByName" ) ; dstByteBuffer . clear ( ) ; final CountDownLatch downloadLatch4 = new CountDownLatch ( 1 ) ; final GridFSDownloadStream downloadStreamByName = gridFSBucket . openDownloadStream ( "sampleData" ) ; downloadStreamByName . read ( dstByteBuffer , new SingleResultCallback < Integer > ( ) { @ Override public void onResult ( final Integer result , final Throwable t ) { dstByteBuffer . flip ( ) ; byte [ ] bytes = new byte [ result ] ; dstByteBuffer . get ( bytes ) ; System . out . println ( new String ( bytes , StandardCharsets . UTF_8 ) ) ; downloadStreamByName . close ( new SingleResultCallback < Void > ( ) { @ Override public void onResult ( final Void result , final Throwable t ) { downloadLatch4 . countDown ( ) ; } } ) ; } } ) ; downloadLatch4 . await ( ) ; /* * Rename */
final CountDownLatch renameLatch = new CountDownLatch ( 1 ) ; gridFSBucket . rename ( fileId , "mongodbTutorial" , new SingleResultCallback < Void > ( ) { @ Override public void onResult ( final Void result , final Throwable t ) { System . out . println ( "Renamed file" ) ; renameLatch . countDown ( ) ; } } ) ; renameLatch . await ( ) ; /* * Delete */
final CountDownLatch deleteLatch = new CountDownLatch ( 1 ) ; gridFSBucket . delete ( fileId , new SingleResultCallback < Void > ( ) { @ Override public void onResult ( final Void result , final Throwable t ) { System . out . println ( "Deleted file" ) ; deleteLatch . countDown ( ) ; } } ) ; deleteLatch . await ( ) ; // Final cleanup
final CountDownLatch dropLatch2 = new CountDownLatch ( 1 ) ; database . drop ( new SingleResultCallback < Void > ( ) { @ Override public void onResult ( final Void result , final Throwable t ) { dropLatch2 . countDown ( ) ; } } ) ; dropLatch2 . await ( ) ; System . out . println ( "Finished" ) ;


signature:
public class Assertions { /** * Throw IllegalArgumentException if the value is null .
 * @ param name the parameter name
 * @ param value the value that should not be null
 * @ param callback the callback that also is passed the exception if the value is null
 * @ param < T > the value type
 * @ return the value
 * @ throws java . lang . IllegalArgumentException if value is null */
public static < T > T notNull ( final String name , final T value , final SingleResultCallback < ? > callback ) { } }

implementation: if ( value == null ) { IllegalArgumentException exception = new IllegalArgumentException ( name + " can not be null" ) ; callback . onResult ( null , exception ) ; throw exception ; } return value ;


signature:
public class Assertions { /** * Throw IllegalStateException if the condition if false .
 * @ param name the name of the state that is being checked
 * @ param condition the condition about the parameter to check
 * @ param callback the callback that also is passed the exception if the condition is not true
 * @ throws java . lang . IllegalStateException if the condition is false */
public static void isTrue ( final String name , final boolean condition , final SingleResultCallback < ? > callback ) { } }

implementation: if ( ! condition ) { IllegalStateException exception = new IllegalStateException ( "state should be: " + name ) ; callback . onResult ( null , exception ) ; throw exception ; }


signature:
public class ClassModelBuilder { /** * Gets a property by the property name .
 * @ param propertyName the name of the property to find .
 * @ return the property or null if the property is not found */
public PropertyModelBuilder < ? > getProperty ( final String propertyName ) { } }

implementation: notNull ( "propertyName" , propertyName ) ; for ( PropertyModelBuilder < ? > propertyModelBuilder : propertyModelBuilders ) { if ( propertyModelBuilder . getName ( ) . equals ( propertyName ) ) { return propertyModelBuilder ; } } return null ;


signature:
public class ClassModelBuilder { /** * Creates a new ClassModel instance based on the mapping data provided .
 * @ return the new instance */
public ClassModel < T > build ( ) { } }

implementation: List < PropertyModel < ? > > propertyModels = new ArrayList < PropertyModel < ? > > ( ) ; PropertyModel < ? > idPropertyModel = null ; stateNotNull ( "type" , type ) ; for ( Convention convention : conventions ) { convention . apply ( this ) ; } stateNotNull ( "instanceCreatorFactory" , instanceCreatorFactory ) ; if ( discriminatorEnabled ) { stateNotNull ( "discriminatorKey" , discriminatorKey ) ; stateNotNull ( "discriminator" , discriminator ) ; } for ( PropertyModelBuilder < ? > propertyModelBuilder : propertyModelBuilders ) { boolean isIdProperty = propertyModelBuilder . getName ( ) . equals ( idPropertyName ) ; if ( isIdProperty ) { propertyModelBuilder . readName ( ID_PROPERTY_NAME ) . writeName ( ID_PROPERTY_NAME ) ; } PropertyModel < ? > model = propertyModelBuilder . build ( ) ; propertyModels . add ( model ) ; if ( isIdProperty ) { idPropertyModel = model ; } } validatePropertyModels ( type . getSimpleName ( ) , propertyModels ) ; return new ClassModel < T > ( type , propertyNameToTypeParameterMap , instanceCreatorFactory , discriminatorEnabled , discriminatorKey , discriminator , IdPropertyModelHolder . create ( type , idPropertyModel , idGenerator ) , unmodifiableList ( propertyModels ) ) ;


signature:
public class ReplaceOneModel { /** * Gets the options to apply .
 * @ return the update options
 * @ deprecated use { @ link # getReplaceOptions ( ) } instead */
@ Deprecated public UpdateOptions getOptions ( ) { } }

implementation: return new UpdateOptions ( ) . bypassDocumentValidation ( options . getBypassDocumentValidation ( ) ) . collation ( options . getCollation ( ) ) . upsert ( options . isUpsert ( ) ) ;


signature:
public class MongoException { /** * Static helper to create or cast a MongoException from a throwable
 * @ param t a throwable , which may be null
 * @ return a MongoException */
@ Nullable public static MongoException fromThrowable ( @ Nullable final Throwable t ) { } }

implementation: if ( t == null ) { return null ; } else { return fromThrowableNonNull ( t ) ; }


signature:
public class MongoException { /** * Static helper to create or cast a MongoException from a throwable
 * @ param t a throwable , which may not be null
 * @ return a MongoException
 * @ since 3.7 */
public static MongoException fromThrowableNonNull ( final Throwable t ) { } }

implementation: if ( t instanceof MongoException ) { return ( MongoException ) t ; } else { return new MongoException ( t . getMessage ( ) , t ) ; }


signature:
public class FindOperation { /** * Sets the maximum execution time on the server for this operation .
 * @ param maxTime the max time
 * @ param timeUnit the time unit , which may not be null
 * @ return this */
public FindOperation < T > maxTime ( final long maxTime , final TimeUnit timeUnit ) { } }

implementation: notNull ( "timeUnit" , timeUnit ) ; isTrueArgument ( "maxTime >= 0" , maxTime >= 0 ) ; this . maxTimeMS = TimeUnit . MILLISECONDS . convert ( maxTime , timeUnit ) ; return this ;


signature:
public class FindOperation { /** * Sets the maximum await execution time on the server for this operation .
 * @ param maxAwaitTime the max await time . A zero value will be ignored , and indicates that the driver should respect the server ' s
 * default value
 * @ param timeUnit the time unit , which may not be null
 * @ return this
 * @ since 3.2
 * @ mongodb . driver . manual reference / method / cursor . maxTimeMS / # cursor . maxTimeMS Max Time */
public FindOperation < T > maxAwaitTime ( final long maxAwaitTime , final TimeUnit timeUnit ) { } }

implementation: notNull ( "timeUnit" , timeUnit ) ; isTrueArgument ( "maxAwaitTime >= 0" , maxAwaitTime >= 0 ) ; this . maxAwaitTimeMS = TimeUnit . MILLISECONDS . convert ( maxAwaitTime , timeUnit ) ; return this ;


signature:
public class FindOperation { /** * Gets an operation whose execution explains this operation .
 * @ param explainVerbosity the explain verbosity
 * @ return a read operation that when executed will explain this operation */
public ReadOperation < BsonDocument > asExplainableOperation ( final ExplainVerbosity explainVerbosity ) { } }

implementation: notNull ( "explainVerbosity" , explainVerbosity ) ; return new ReadOperation < BsonDocument > ( ) { @ Override public BsonDocument execute ( final ReadBinding binding ) { return withConnection ( binding , new CallableWithConnectionAndSource < BsonDocument > ( ) { @ Override public BsonDocument call ( final ConnectionSource connectionSource , final Connection connection ) { ReadBinding singleConnectionBinding = new SingleConnectionReadBinding ( binding . getReadPreference ( ) , connectionSource . getServerDescription ( ) , connection ) ; try { if ( serverIsAtLeastVersionThreeDotTwo ( connection . getDescription ( ) ) ) { try { return new CommandReadOperation < BsonDocument > ( getNamespace ( ) . getDatabaseName ( ) , new BsonDocument ( "explain" , getCommand ( binding . getSessionContext ( ) ) ) , new BsonDocumentCodec ( ) ) . execute ( singleConnectionBinding ) ; } catch ( MongoCommandException e ) { throw new MongoQueryException ( e ) ; } } else { BatchCursor < BsonDocument > cursor = createExplainableQueryOperation ( ) . execute ( singleConnectionBinding ) ; try { return cursor . next ( ) . iterator ( ) . next ( ) ; } finally { cursor . close ( ) ; } } } finally { singleConnectionBinding . release ( ) ; } } } ) ; } } ;


signature:
public class FindOperation { /** * Gets an operation whose execution explains this operation .
 * @ param explainVerbosity the explain verbosity
 * @ return a read operation that when executed will explain this operation */
public AsyncReadOperation < BsonDocument > asExplainableOperationAsync ( final ExplainVerbosity explainVerbosity ) { } }

implementation: notNull ( "explainVerbosity" , explainVerbosity ) ; return new AsyncReadOperation < BsonDocument > ( ) { @ Override public void executeAsync ( final AsyncReadBinding binding , final SingleResultCallback < BsonDocument > callback ) { withConnection ( binding , new AsyncCallableWithConnectionAndSource ( ) { @ Override public void call ( final AsyncConnectionSource connectionSource , final AsyncConnection connection , final Throwable t ) { SingleResultCallback < BsonDocument > errHandlingCallback = errorHandlingCallback ( callback , LOGGER ) ; if ( t != null ) { errHandlingCallback . onResult ( null , t ) ; } else { AsyncReadBinding singleConnectionReadBinding = new AsyncSingleConnectionReadBinding ( binding . getReadPreference ( ) , connectionSource . getServerDescription ( ) , connection ) ; if ( serverIsAtLeastVersionThreeDotTwo ( connection . getDescription ( ) ) ) { new CommandReadOperation < BsonDocument > ( namespace . getDatabaseName ( ) , new BsonDocument ( "explain" , getCommand ( binding . getSessionContext ( ) ) ) , new BsonDocumentCodec ( ) ) . executeAsync ( singleConnectionReadBinding , releasingCallback ( exceptionTransformingCallback ( errHandlingCallback ) , singleConnectionReadBinding , connectionSource , connection ) ) ; } else { createExplainableQueryOperation ( ) . executeAsync ( singleConnectionReadBinding , releasingCallback ( new ExplainResultCallback ( errHandlingCallback ) , singleConnectionReadBinding , connectionSource , connection ) ) ; } } } } ) ; } } ;


signature:
public class ReflectionDBObject { /** * Returns the wrapper if this object can be assigned from this class .
 * @ param c the class to be wrapped
 * @ return the wrapper */
@ Nullable public static JavaWrapper getWrapperIfReflectionObject ( final Class c ) { } }

implementation: if ( ReflectionDBObject . class . isAssignableFrom ( c ) ) { return getWrapper ( c ) ; } return null ;


signature:
public class ReflectionDBObject { /** * Returns an existing Wrapper instance associated with a class , or creates a new one .
 * @ param c the class to be wrapped
 * @ return the wrapped */
public static JavaWrapper getWrapper ( final Class c ) { } }

implementation: JavaWrapper w = _wrappers . get ( c ) ; if ( w == null ) { w = new JavaWrapper ( c ) ; _wrappers . put ( c , w ) ; } return w ;


signature:
public class CountOptions { /** * Sets the maximum execution time on the server for this operation .
 * @ param maxTime the max time
 * @ param timeUnit the time unit , which may not be null
 * @ return this */
public CountOptions maxTime ( final long maxTime , final TimeUnit timeUnit ) { } }

implementation: notNull ( "timeUnit" , timeUnit ) ; this . maxTimeMS = TimeUnit . MILLISECONDS . convert ( maxTime , timeUnit ) ; return this ;


signature:
public class BsonBinary { /** * Returns the binary as a UUID . The binary type must be 4.
 * @ return the uuid
 * @ since 3.9 */
public UUID asUuid ( ) { } }

implementation: if ( ! BsonBinarySubType . isUuid ( type ) ) { throw new BsonInvalidOperationException ( "type must be a UUID subtype." ) ; } if ( type != BsonBinarySubType . UUID_STANDARD . getValue ( ) ) { throw new BsonInvalidOperationException ( "uuidRepresentation must be set to return the correct UUID." ) ; } return UuidHelper . decodeBinaryToUuid ( this . data . clone ( ) , this . type , UuidRepresentation . STANDARD ) ;


signature:
public class BsonBinary { /** * Returns the binary as a UUID .
 * @ param uuidRepresentation the UUID representation
 * @ return the uuid
 * @ since 3.9 */
public UUID asUuid ( final UuidRepresentation uuidRepresentation ) { } }

implementation: Assertions . notNull ( "uuidRepresentation" , uuidRepresentation ) ; final byte uuidType = uuidRepresentation == UuidRepresentation . STANDARD ? BsonBinarySubType . UUID_STANDARD . getValue ( ) : BsonBinarySubType . UUID_LEGACY . getValue ( ) ; if ( type != uuidType ) { throw new BsonInvalidOperationException ( "uuidRepresentation does not match current uuidRepresentation." ) ; } return UuidHelper . decodeBinaryToUuid ( data . clone ( ) , type , uuidRepresentation ) ;


signature:
public class RawBsonDocument { /** * Parses a string in MongoDB Extended JSON format to a { @ code RawBsonDocument }
 * @ param json the JSON string
 * @ return a corresponding { @ code RawBsonDocument } object
 * @ see org . bson . json . JsonReader
 * @ mongodb . driver . manual reference / mongodb - extended - json / MongoDB Extended JSON
 * @ since 3.3 */
public static RawBsonDocument parse ( final String json ) { } }

implementation: notNull ( "json" , json ) ; return new RawBsonDocumentCodec ( ) . decode ( new JsonReader ( json ) , DecoderContext . builder ( ) . build ( ) ) ;


signature:
public class RawBsonDocument { /** * Returns a { @ code ByteBuf } that wraps the byte array , with the proper byte order . Any changes made to the returned will be reflected
 * in the underlying byte array owned by this instance .
 * @ return a byte buffer that wraps the byte array owned by this instance . */
public ByteBuf getByteBuffer ( ) { } }

implementation: ByteBuffer buffer = ByteBuffer . wrap ( bytes , offset , length ) ; buffer . order ( ByteOrder . LITTLE_ENDIAN ) ; return new ByteBufNIO ( buffer ) ;


signature:
public class RawBsonDocument { /** * Decode this into a document .
 * @ param codec the codec to facilitate the transformation
 * @ param < T > the BSON type that the codec encodes / decodes
 * @ return the decoded document */
public < T > T decode ( final Codec < T > codec ) { } }

implementation: return decode ( ( Decoder < T > ) codec ) ;


signature:
public class RawBsonDocument { /** * Decode this into a document .
 * @ param decoder the decoder to facilitate the transformation
 * @ param < T > the BSON type that the codec encodes / decodes
 * @ return the decoded document
 * @ since 3.6 */
public < T > T decode ( final Decoder < T > decoder ) { } }

implementation: BsonBinaryReader reader = createReader ( ) ; try { return decoder . decode ( reader , DecoderContext . builder ( ) . build ( ) ) ; } finally { reader . close ( ) ; }


signature:
public class JSON { /** * < p > Serializes an object into its JSON form . < / p >
 * < p > This method delegates serialization to { @ code JSONSerializers . getLegacy } < / p >
 * @ param object object to serialize
 * @ return String containing JSON form of the object
 * @ see JSONSerializers # getLegacy ( ) */
public static String serialize ( final Object object ) { } }

implementation: StringBuilder buf = new StringBuilder ( ) ; serialize ( object , buf ) ; return buf . toString ( ) ;


signature:
public class JSON { /** * < p > Serializes an object into its JSON form . < / p >
 * < p > This method delegates serialization to { @ code JSONSerializers . getLegacy } < / p >
 * @ param object object to serialize
 * @ param buf StringBuilder containing the JSON representation under construction
 * @ see JSONSerializers # getLegacy ( ) */
public static void serialize ( final Object object , final StringBuilder buf ) { } }

implementation: JSONSerializers . getLegacy ( ) . serialize ( object , buf ) ;


signature:
public class JSON { /** * Parses a JSON string and constructs a corresponding Java object by calling the methods of a { @ link org . bson . BSONCallback
 * BSONCallback } during parsing . If the callback { @ code c } is null , this method is equivalent to { @ link JSON # parse ( String )
 * parse ( String ) } .
 * @ param s the string to parse
 * @ param c the BSONCallback to call during parsing
 * @ return a Java object representing the JSON data
 * @ throws JSONParseException if s is not valid JSON */
public static Object parse ( final String s , final BSONCallback c ) { } }

implementation: if ( s == null || ( s . trim ( ) ) . equals ( "" ) ) { return null ; } JSONParser p = new JSONParser ( s , c ) ; return p . parse ( ) ;


signature:
public class JSONParser { /** * Parse an unknown type .
 * @ return Object the next item
 * @ throws JSONParseException if invalid JSON is found */
protected Object parse ( final String name ) { } }

implementation:
Object value = null ; char current = get ( ) ; switch ( current ) { // null
case 'n' : read ( 'n' ) ; read ( 'u' ) ; read ( 'l' ) ; read ( 'l' ) ; value = null ; break ; // NaN
case 'N' : read ( 'N' ) ; read ( 'a' ) ; read ( 'N' ) ; value = Double . NaN ; break ; // true
case 't' : read ( 't' ) ; read ( 'r' ) ; read ( 'u' ) ; read ( 'e' ) ; value = true ; break ; // false
case 'f' : read ( 'f' ) ; read ( 'a' ) ; read ( 'l' ) ; read ( 's' ) ; read ( 'e' ) ; value = false ; break ; // string
case '\'' : case '\"' : value = parseString ( true ) ; break ; // number
case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : case '8' : case '9' : case '+' : case '-' : value = parseNumber ( ) ; break ; // array
case '[' : value = parseArray ( name ) ; break ; // object
case '{' : value = parseObject ( name ) ; break ; default : throw new JSONParseException ( s , pos ) ; } return value ;


signature:
public class JSONParser { /** * Parses an object for the form < i > { } < / i > and < i > { members } < / i > .
 * @ return DBObject the next object
 * @ throws JSONParseException if invalid JSON is found */
protected Object parseObject ( final String name ) { } }

implementation: if ( name != null ) { _callback . objectStart ( name ) ; } else { _callback . objectStart ( ) ; } read ( '{' ) ; char current = get ( ) ; while ( get ( ) != '}' ) { String key = parseString ( false ) ; read ( ':' ) ; Object value = parse ( key ) ; doCallback ( key , value ) ; if ( ( current = get ( ) ) == ',' ) { read ( ',' ) ; } else { break ; } } read ( '}' ) ; return _callback . objectDone ( ) ;


signature:
public class JSONParser { /** * Read the current character , making sure that it is a hexidecimal character .
 * @ throws JSONParseException if the current character is not a hexidecimal character */
public void readHex ( ) { } }

implementation: if ( pos < s . length ( ) && ( ( s . charAt ( pos ) >= '0' && s . charAt ( pos ) <= '9' ) || ( s . charAt ( pos ) >= 'A' && s . charAt ( pos ) <= 'F' ) || ( s . charAt ( pos ) >= 'a' && s . charAt ( pos ) <= 'f' ) ) ) { pos ++ ; } else { throw new JSONParseException ( s , pos ) ; }


signature:
public class JSONParser { /** * Advances the position in the string past any whitespace . */
public void skipWS ( ) { } }

implementation: while ( pos < s . length ( ) && Character . isWhitespace ( s . charAt ( pos ) ) ) { pos ++ ; }


signature:
public class JSONParser { /** * Parses a string .
 * @ return the next string .
 * @ throws JSONParseException if invalid JSON is found */
public String parseString ( final boolean needQuote ) { } }

implementation:
char quot = 0 ; if ( check ( '\'' ) ) { quot = '\'' ; } else if ( check ( '\"' ) ) { quot = '\"' ; } else if ( needQuote ) { throw new JSONParseException ( s , pos ) ; } char current ; if ( quot > 0 ) { read ( quot ) ; } StringBuilder buf = new StringBuilder ( ) ; int start = pos ; while ( pos < s . length ( ) ) { current = s . charAt ( pos ) ; if ( quot > 0 ) { if ( current == quot ) { break ; } } else { if ( current == ':' || current == ' ' ) { break ; } } if ( current == '\\' ) { pos ++ ; char x = get ( ) ; char special = 0 ; // CHECKSTYLE : OFF
switch ( x ) { case 'u' : // decode unicode
buf . append ( s . substring ( start , pos - 1 ) ) ; pos ++ ; int tempPos = pos ; readHex ( ) ; readHex ( ) ; readHex ( ) ; readHex ( ) ; int codePoint = Integer . parseInt ( s . substring ( tempPos , tempPos + 4 ) , 16 ) ; buf . append ( ( char ) codePoint ) ; start = pos ; continue ; case 'n' : special = '\n' ; break ; case 'r' : special = '\r' ; break ; case 't' : special = '\t' ; break ; case 'b' : special = '\b' ; break ; case '"' : special = '\"' ; break ; case '\\' : special = '\\' ; break ; default : break ; } // CHECKSTYLE : ON
buf . append ( s . substring ( start , pos - 1 ) ) ; if ( special != 0 ) { pos ++ ; buf . append ( special ) ; } start = pos ; continue ; } pos ++ ; } buf . append ( s . substring ( start , pos ) ) ; if ( quot > 0 ) { read ( quot ) ; } return buf . toString ( ) ;


signature:
public class JSONParser { /** * Parses a number .
 * @ return the next number ( int or double ) .
 * @ throws JSONParseException if invalid JSON is found */
public Number parseNumber ( ) { } }

implementation: get ( ) ; int start = this . pos ; boolean isDouble = false ; if ( check ( '-' ) || check ( '+' ) ) { pos ++ ; } outer : while ( pos < s . length ( ) ) { switch ( s . charAt ( pos ) ) { case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : case '8' : case '9' : pos ++ ; break ; case '.' : isDouble = true ; parseFraction ( ) ; break ; case 'e' : case 'E' : isDouble = true ; parseExponent ( ) ; break ; default : break outer ; } } try { if ( isDouble ) { return Double . valueOf ( s . substring ( start , pos ) ) ; } Long val = Long . valueOf ( s . substring ( start , pos ) ) ; if ( val <= Integer . MAX_VALUE && val >= Integer . MIN_VALUE ) { return val . intValue ( ) ; } return val ; } catch ( NumberFormatException e ) { throw new JSONParseException ( s , start , e ) ; }


signature:
public class JSONParser { /** * Advances the pointed through < i > . digits < / i > . */
public void parseFraction ( ) { } }

implementation:
// get past .
pos ++ ; outer : while ( pos < s . length ( ) ) { switch ( s . charAt ( pos ) ) { case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : case '8' : case '9' : pos ++ ; break ; case 'e' : case 'E' : parseExponent ( ) ; break ; default : break outer ; } }


signature:
public class JSONParser { /** * Advances the pointer through the exponent . */
public void parseExponent ( ) { } }

implementation:
// get past E
pos ++ ; if ( check ( '-' ) || check ( '+' ) ) { pos ++ ; } outer : while ( pos < s . length ( ) ) { switch ( s . charAt ( pos ) ) { case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : case '8' : case '9' : pos ++ ; break ; default : break outer ; } }


signature:
public class JSONParser { /** * Parses the next array .
 * @ return the array
 * @ throws JSONParseException if invalid JSON is found */
protected Object parseArray ( final String name ) { } }

implementation: if ( name != null ) { _callback . arrayStart ( name ) ; } else { _callback . arrayStart ( ) ; } read ( '[' ) ; int i = 0 ; char current = get ( ) ; while ( current != ']' ) { String elemName = String . valueOf ( i ++ ) ; Object elem = parse ( elemName ) ; doCallback ( elemName , elem ) ; if ( ( current = get ( ) ) == ',' ) { read ( ',' ) ; } else if ( current == ']' ) { break ; } else { throw new JSONParseException ( s , pos ) ; } } read ( ']' ) ; return _callback . arrayDone ( ) ;


signature:
public class BulkUpdateRequestBuilder { /** * Adds a request to replace one document in the collection that matches the query with which this builder was created .
 * @ param document the replacement document , which must be structured just as a document you would insert . It can not contain any
 * update operators . */
public void replaceOne ( final DBObject document ) { } }

implementation: bulkWriteOperation . addRequest ( new ReplaceRequest ( query , document , upsert , queryCodec , replacementCodec , collation ) ) ;


signature:
public class BulkUpdateRequestBuilder { /** * Adds a request to update all documents in the collection that match the query with which this builder was created .
 * @ param update the update criteria */
public void update ( final DBObject update ) { } }

implementation: bulkWriteOperation . addRequest ( new UpdateRequest ( query , update , true , upsert , queryCodec , collation , arrayFilters ) ) ;


signature:
public class BulkUpdateRequestBuilder { /** * Adds a request to update one document in the collection that matches the query with which this builder was created .
 * @ param update the update criteria */
public void updateOne ( final DBObject update ) { } }

implementation: bulkWriteOperation . addRequest ( new UpdateRequest ( query , update , false , upsert , queryCodec , collation , arrayFilters ) ) ;


signature:
public class ConnectionDescription { /** * Creates a new connection description with the set connection id
 * @ param connectionId the connection id
 * @ return the new connection description
 * @ since 3.8 */
public ConnectionDescription withConnectionId ( final ConnectionId connectionId ) { } }

implementation: notNull ( "connectionId" , connectionId ) ; return new ConnectionDescription ( connectionId , serverVersion , maxWireVersion , serverType , maxBatchCount , maxDocumentSize , maxMessageSize , compressors ) ;


signature:
public class WriteConcernResult { /** * Create an acknowledged WriteConcernResult
 * @ param count the count of matched documents
 * @ param isUpdateOfExisting whether an existing document was updated
 * @ param upsertedId if an upsert resulted in an inserted document , this is the _ id of that document . This may be null
 * @ return an acknowledged WriteConcernResult */
public static WriteConcernResult acknowledged ( final int count , final boolean isUpdateOfExisting , @ Nullable final BsonValue upsertedId ) { } }

implementation: return new WriteConcernResult ( ) { @ Override public boolean wasAcknowledged ( ) { return true ; } @ Override public int getCount ( ) { return count ; } @ Override public boolean isUpdateOfExisting ( ) { return isUpdateOfExisting ; } @ Override @ Nullable public BsonValue getUpsertedId ( ) { return upsertedId ; } @ Override public boolean equals ( final Object o ) { if ( this == o ) { return true ; } if ( o == null || getClass ( ) != o . getClass ( ) ) { return false ; } WriteConcernResult that = ( WriteConcernResult ) o ; if ( ! that . wasAcknowledged ( ) ) { return false ; } if ( count != that . getCount ( ) ) { return false ; } if ( isUpdateOfExisting != that . isUpdateOfExisting ( ) ) { return false ; } if ( upsertedId != null ? ! upsertedId . equals ( that . getUpsertedId ( ) ) : that . getUpsertedId ( ) != null ) { return false ; } return true ; } @ Override public int hashCode ( ) { int result = count ; result = 31 * result + ( isUpdateOfExisting ? 1 : 0 ) ; result = 31 * result + ( upsertedId != null ? upsertedId . hashCode ( ) : 0 ) ; return result ; } @ Override public String toString ( ) { return "AcknowledgedWriteResult{" + "count=" + count + ", isUpdateOfExisting=" + isUpdateOfExisting + ", upsertedId=" + upsertedId + '}' ; } } ;


signature:
public class WriteConcernResult { /** * Create an unacknowledged WriteConcernResult
 * @ return an unacknowledged WriteConcernResult */
public static WriteConcernResult unacknowledged ( ) { } }

implementation: return new WriteConcernResult ( ) { @ Override public boolean wasAcknowledged ( ) { return false ; } @ Override public int getCount ( ) { throw getUnacknowledgedWriteException ( ) ; } @ Override public boolean isUpdateOfExisting ( ) { throw getUnacknowledgedWriteException ( ) ; } @ Override public BsonValue getUpsertedId ( ) { throw getUnacknowledgedWriteException ( ) ; } @ Override public boolean equals ( final Object o ) { if ( this == o ) { return true ; } if ( o == null || getClass ( ) != o . getClass ( ) ) { return false ; } WriteConcernResult that = ( WriteConcernResult ) o ; return ! that . wasAcknowledged ( ) ; } @ Override public int hashCode ( ) { return 1 ; } @ Override public String toString ( ) { return "UnacknowledgedWriteResult{}" ; } private UnsupportedOperationException getUnacknowledgedWriteException ( ) { return new UnsupportedOperationException ( "Cannot get information about an unacknowledged write" ) ; } } ;


signature:
public class Document { /** * Parses a string in MongoDB Extended JSON format to a { @ code Document }
 * @ param json the JSON string
 * @ param decoder the { @ code Decoder } to use to parse the JSON string into a { @ code Document }
 * @ return a corresponding { @ code Document } object
 * @ see org . bson . json . JsonReader
 * @ mongodb . driver . manual reference / mongodb - extended - json / MongoDB Extended JSON */
public static Document parse ( final String json , final Decoder < Document > decoder ) { } }

implementation: notNull ( "codec" , decoder ) ; JsonReader bsonReader = new JsonReader ( json ) ; return decoder . decode ( bsonReader , DecoderContext . builder ( ) . build ( ) ) ;


signature:
public class Document { /** * Put the given key / value pair into this Document and return this . Useful for chaining puts in a single expression , e . g .
 * < pre >
 * doc . append ( " a " , 1 ) . append ( " b " , 2 ) }
 * < / pre >
 * @ param key key
 * @ param value value
 * @ return this */
public Document append ( final String key , final Object value ) { } }

implementation: documentAsMap . put ( key , value ) ; return this ;


signature:
public class Document { /** * Gets the value of the given key , casting it to the given { @ code Class < T > } . This is useful to avoid having casts in client code ,
 * though the effect is the same . So to get the value of a key that is of type String , you would write { @ code String name =
 * doc . get ( " name " , String . class ) } instead of { @ code String name = ( String ) doc . get ( " x " ) } .
 * @ param key the key
 * @ param clazz the non - null class to cast the value to
 * @ param < T > the type of the class
 * @ return the value of the given key , or null if the instance does not contain this key .
 * @ throws ClassCastException if the value of the given key is not of type T */
public < T > T get ( final Object key , final Class < T > clazz ) { } }

implementation: notNull ( "clazz" , clazz ) ; return clazz . cast ( documentAsMap . get ( key ) ) ;


signature:
public class Document { /** * Gets the value of the given key , casting it to { @ code Class < T > } or returning the default value if null .
 * This is useful to avoid having casts in client code , though the effect is the same .
 * @ param key the key
 * @ param defaultValue what to return if the value is null
 * @ param < T > the type of the class
 * @ return the value of the given key , or null if the instance does not contain this key .
 * @ throws ClassCastException if the value of the given key is not of type T
 * @ since 3.5 */
@ SuppressWarnings ( "unchecked" ) public < T > T get ( final Object key , final T defaultValue ) { } }

implementation: notNull ( "defaultValue" , defaultValue ) ; Object value = documentAsMap . get ( key ) ; return value == null ? defaultValue : ( T ) value ;


signature:
public class Document { /** * Gets the value in an embedded document , casting it to the given { @ code Class < T > } . The list of keys represents a path to the
 * embedded value , drilling down into an embedded document for each key . This is useful to avoid having casts in
 * client code , though the effect is the same .
 * The generic type of the keys list is { @ code ? } to be consistent with the corresponding { @ code get } methods , but in practice
 * the actual type of the argument should be { @ code List < String > } . So to get the embedded value of a key list that is of type String ,
 * you would write { @ code String name = doc . getEmbedded ( List . of ( " employee " , " manager " , " name " ) , String . class ) } instead of
 * { @ code String name = ( String ) doc . get ( " employee " , Document . class ) . get ( " manager " , Document . class ) . get ( " name " ) } .
 * @ param keys the list of keys
 * @ param clazz the non - null class to cast the value to
 * @ param < T > the type of the class
 * @ return the value of the given embedded key , or null if the instance does not contain this embedded key .
 * @ throws ClassCastException if the value of the given embedded key is not of type T
 * @ since 3.10 */
public < T > T getEmbedded ( final List < ? > keys , final Class < T > clazz ) { } }

implementation: notNull ( "keys" , keys ) ; isTrue ( "keys" , ! keys . isEmpty ( ) ) ; notNull ( "clazz" , clazz ) ; return getEmbeddedValue ( keys , clazz , null ) ;