public static Bson geoWithinCenter(final String fieldName, final double x, final double y, final double radius) {
        BsonDocument center = new BsonDocument("$center",
                                                      new BsonArray(Arrays.<BsonValue>asList(new BsonArray(asList(new BsonDouble(x),
                                                              new BsonDouble(y))),
                                                              new BsonDouble(radius))));
        return new OperatorFilter<BsonDocument>("$geoWithin", fieldName, center);
    }

public static Bson geoWithinCenter ( final String fieldName , final double x , final double y , final double radius ) { BsonDocument center = new BsonDocument ( "$center" , new BsonArray ( Arrays . < BsonValue > asList ( new BsonArray ( asList ( new BsonDouble ( x ) , new BsonDouble ( y ) ) ) , new BsonDouble ( radius ) ) ) ) ; return new OperatorFilter < BsonDocument > ( "$geoWithin" , fieldName , center ) ; }

Creates a filter that matches all documents containing a field with grid coordinates data that exist entirely within the specified
circle.

@param fieldName the field name
@param x         the x coordinate of the circle
@param y         the y coordinate of the circle
@param radius    the radius of the circle, as measured in the units used by the coordinate system
@return the filter
@mongodb.driver.manual reference/operator/query/geoWithin/ $geoWithin
@mongodb.driver.manual reference/operator/query/center/#op._S_center $center
@mongodb.server.release 2.4
@since 3.1

Creates a filter that matches all documents containing a field with grid coordinates data that exist entirely within the specified circle .


public static Bson near(final String fieldName, final Point geometry, @Nullable final Double maxDistance,
                            @Nullable final Double minDistance) {
        return new GeometryOperatorFilter<Point>("$near", fieldName, geometry, maxDistance, minDistance);
    }

public static Bson near ( final String fieldName , final Point geometry , @ Nullable final Double maxDistance , @ Nullable final Double minDistance ) { return new GeometryOperatorFilter < Point > ( "$near" , fieldName , geometry , maxDistance , minDistance ) ; }

Creates a filter that matches all documents containing a field with geospatial data that is near the specified GeoJSON point.

@param fieldName   the field name
@param geometry    the bounding GeoJSON geometry object
@param maxDistance the maximum distance from the point, in meters. It may be null.
@param minDistance the minimum distance from the point, in meters. It may be null.
@return the filter
@since 3.1
@mongodb.driver.manual reference/operator/query/near/ $near
@mongodb.server.release 2.4

Creates a filter that matches all documents containing a field with geospatial data that is near the specified GeoJSON point .


public static Bson near(final String fieldName, final double x, final double y, @Nullable final Double maxDistance,
                            @Nullable final Double minDistance) {
        return createNearFilterDocument(fieldName, x, y, maxDistance, minDistance, "$near");
    }

public static Bson near ( final String fieldName , final double x , final double y , @ Nullable final Double maxDistance , @ Nullable final Double minDistance ) { return createNearFilterDocument ( fieldName , x , y , maxDistance , minDistance , "$near" ) ; }

Creates a filter that matches all documents containing a field with geospatial data that is near the specified point.

@param fieldName   the field name
@param x           the x coordinate
@param y           the y coordinate
@param maxDistance the maximum distance from the point, in radians. It may be null.
@param minDistance the minimum distance from the point, in radians. It may be null.
@return the filter
@since 3.1
@mongodb.driver.manual reference/operator/query/near/ $near
@mongodb.server.release 2.4

Creates a filter that matches all documents containing a field with geospatial data that is near the specified point .


public static int regexFlags(final String s) {
        int flags = 0;

        if (s == null) {
            return flags;
        }

        for (final char f : s.toLowerCase().toCharArray()) {
            flags |= regexFlag(f);
        }

        return flags;
    }

public static int regexFlags ( final String s ) { int flags = 0 ; if ( s == null ) { return flags ; } for ( final char f : s . toLowerCase ( ) . toCharArray ( ) ) { flags |= regexFlag ( f ) ; } return flags ; }

Converts a sequence of regular expression modifiers from the database into Java regular expression flags.

@param s regular expression modifiers
@return the Java flags
@throws IllegalArgumentException If sequence contains invalid flags.

Converts a sequence of regular expression modifiers from the database into Java regular expression flags .


public static int regexFlag(final char c) {

        int flag = FLAG_LOOKUP[c];

        if (flag == 0) {
            throw new IllegalArgumentException(String.format("Unrecognized flag [%c]", c));
        }

        return flag;
    }

public
static
int
regexFlag
(
final
char
c
)
{
int
flag
=
FLAG_LOOKUP
[
c
]
;
if
(
flag
==
0
)
{
throw
new
IllegalArgumentException
(
String
.
format
(
"Unrecognized flag [%c]"
,
c
)
)
;
}
return
flag
;
}

Converts a regular expression modifier from the database into Java regular expression flags.

@param c regular expression modifier
@return the Java flags
@throws IllegalArgumentException If sequence contains invalid flags.

Converts a regular expression modifier from the database into Java regular expression flags .


public static String regexFlags(final int flags) {
        int processedFlags = flags;
        StringBuilder buf = new StringBuilder();

        for (int i = 0; i < FLAG_LOOKUP.length; i++) {
            if ((processedFlags & FLAG_LOOKUP[i]) > 0) {
                buf.append((char) i);
                processedFlags -= FLAG_LOOKUP[i];
            }
        }

        if (processedFlags > 0) {
            throw new IllegalArgumentException("Some flags could not be recognized.");
        }

        return buf.toString();
    }

public
static
String
regexFlags
(
final
int
flags
)
{
int
processedFlags
=
flags
;
StringBuilder
buf
=
new
StringBuilder
(
)
;
for
(
int
i
=
0
;
i
<
FLAG_LOOKUP
.
length
;
i
++
)
{
if
(
(
processedFlags
&
FLAG_LOOKUP
[
i
]
)
>
0
)
{
buf
.
append
(
(
char
)
i
)
;
processedFlags
-=
FLAG_LOOKUP
[
i
]
;
}
}
if
(
processedFlags
>
0
)
{
throw
new
IllegalArgumentException
(
"Some flags could not be recognized."
)
;
}
return
buf
.
toString
(
)
;
}

Converts Java regular expression flags into regular expression modifiers from the database.

@param flags the Java flags
@return the Java flags
@throws IllegalArgumentException if some flags couldn't be recognized.

Converts Java regular expression flags into regular expression modifiers from the database .


public IndexRequest textVersion(final Integer textVersion) {
        if (textVersion != null) {
            isTrueArgument("textVersion must be 1, 2 or 3", VALID_TEXT_INDEX_VERSIONS.contains(textVersion));
        }
        this.textVersion = textVersion;
        return this;
    }

public
IndexRequest
textVersion
(
final
Integer
textVersion
)
{
if
(
textVersion
!=
)
{
isTrueArgument
(
"textVersion must be 1, 2 or 3"
,
VALID_TEXT_INDEX_VERSIONS
.
contains
(
textVersion
)
)
;
}
this
.
textVersion
=
textVersion
;
return
this
;
}

Set the text index version number.

@param textVersion the text index version number.
@return this


public IndexRequest sphereVersion(final Integer sphereVersion) {
        if (sphereVersion != null) {
            isTrueArgument("sphereIndexVersion must be 1, 2 or 3", VALID_SPHERE_INDEX_VERSIONS.contains(sphereVersion));
        }
        this.sphereVersion = sphereVersion;
        return this;
    }

public
IndexRequest
sphereVersion
(
final
Integer
sphereVersion
)
{
if
(
sphereVersion
!=
)
{
isTrueArgument
(
"sphereIndexVersion must be 1, 2 or 3"
,
VALID_SPHERE_INDEX_VERSIONS
.
contains
(
sphereVersion
)
)
;
}
this
.
sphereVersion
=
sphereVersion
;
return
this
;
}

Sets the 2dsphere index version number.

@param sphereVersion the 2dsphere index version number.
@return this

Sets the 2dsphere index version number .


public DBCollectionFindOptions copy() {
        DBCollectionFindOptions copiedOptions = new DBCollectionFindOptions();
        copiedOptions.batchSize(batchSize);
        copiedOptions.limit(limit);
        copiedOptions.modifiers(modifiers);
        copiedOptions.projection(projection);
        copiedOptions.maxTime(maxTimeMS, TimeUnit.MILLISECONDS);
        copiedOptions.maxAwaitTime(maxAwaitTimeMS, TimeUnit.MILLISECONDS);
        copiedOptions.skip(skip);
        copiedOptions.sort(sort);
        copiedOptions.cursorType(cursorType);
        copiedOptions.noCursorTimeout(noCursorTimeout);
        copiedOptions.oplogReplay(oplogReplay);
        copiedOptions.partial(partial);
        copiedOptions.readPreference(readPreference);
        copiedOptions.readConcern(readConcern);
        copiedOptions.collation(collation);
        copiedOptions.comment(comment);
        copiedOptions.hint(hint);
        copiedOptions.max(max);
        copiedOptions.min(min);
        copiedOptions.returnKey(returnKey);
        copiedOptions.showRecordId(showRecordId);
        return copiedOptions;
    }

public DBCollectionFindOptions copy ( ) { DBCollectionFindOptions copiedOptions = new DBCollectionFindOptions ( ) ; copiedOptions . batchSize ( batchSize ) ; copiedOptions . limit ( limit ) ; copiedOptions . modifiers ( modifiers ) ; copiedOptions . projection ( projection ) ; copiedOptions . maxTime ( maxTimeMS , TimeUnit . MILLISECONDS ) ; copiedOptions . maxAwaitTime ( maxAwaitTimeMS , TimeUnit . MILLISECONDS ) ; copiedOptions . skip ( skip ) ; copiedOptions . sort ( sort ) ; copiedOptions . cursorType ( cursorType ) ; copiedOptions . noCursorTimeout ( noCursorTimeout ) ; copiedOptions . oplogReplay ( oplogReplay ) ; copiedOptions . partial ( partial ) ; copiedOptions . readPreference ( readPreference ) ; copiedOptions . readConcern ( readConcern ) ; copiedOptions . collation ( collation ) ; copiedOptions . comment ( comment ) ; copiedOptions . hint ( hint ) ; copiedOptions . max ( max ) ; copiedOptions . min ( min ) ; copiedOptions . returnKey ( returnKey ) ; copiedOptions . showRecordId ( showRecordId ) ; return copiedOptions ; }

Copy this DBCollectionFindOptions instance into a new instance.

@return the new DBCollectionFindOptions with the same settings as this instance.

Copy this DBCollectionFindOptions instance into a new instance .


@SuppressWarnings("unchecked")
    public static <T> T convertToType(final Class<T> clazz, final Object value, final String errorMessage) {
        if (!clazz.isAssignableFrom(value.getClass())) {
            throw new IllegalArgumentException(errorMessage);
        }
        return (T) value;
    }

@ SuppressWarnings ( "unchecked" ) public static < T > T convertToType ( final Class < T > clazz , final Object value , final String errorMessage ) { if ( ! clazz . isAssignableFrom ( value . getClass ( ) ) ) { throw new IllegalArgumentException ( errorMessage ) ; } return ( T ) value ; }

Cast an object to the given class and return it, or throw IllegalArgumentException if it's not assignable to that class.

@param clazz        the class to cast to
@param value        the value to cast
@param errorMessage the error message to include in the exception
@param <T>          the Class type
@return value cast to clazz
@throws IllegalArgumentException if value is not assignable to clazz

Cast an object to the given class and return it or throw IllegalArgumentException if it s not assignable to that class .


@Override
    public void encode(final BsonWriter writer, final DBObject document, final EncoderContext encoderContext) {
        BasicOutputBuffer buffer = new BasicOutputBuffer();
        try {
            encoder.writeObject(buffer, document);
            BsonBinaryReader reader = new BsonBinaryReader(new ByteBufferBsonInput(new ByteBufNIO(wrap(buffer.toByteArray()))));
            try {
                writer.pipe(reader);
            } finally {
                reader.close();
            }
        } finally {
            buffer.close();
        }
    }

@ Override public void encode ( final BsonWriter writer , final DBObject document , final EncoderContext encoderContext ) { BasicOutputBuffer buffer = new BasicOutputBuffer ( ) ; try { encoder . writeObject ( buffer , document ) ; BsonBinaryReader reader = new BsonBinaryReader ( new ByteBufferBsonInput ( new ByteBufNIO ( wrap ( buffer . toByteArray ( ) ) ) ) ) ; try { writer . pipe ( reader ) ; } finally { reader . close ( ) ; } } finally { buffer . close ( ) ; } }

over an array of ByteBuffer instances from a PooledByteBufferOutputBuffer


@Override
    public BulkWriteResult execute(final WriteBinding binding) {
        return withReleasableConnection(binding, new CallableWithConnectionAndSource<BulkWriteResult>() {
            @Override
            public BulkWriteResult call(final ConnectionSource connectionSource, final Connection connection) {
                validateWriteRequestsAndReleaseConnectionIfError(connection);

                if (getWriteConcern().isAcknowledged() || serverIsAtLeastVersionThreeDotSix(connection.getDescription())) {
                    BulkWriteBatch bulkWriteBatch = BulkWriteBatch.createBulkWriteBatch(namespace, connectionSource.getServerDescription(),
                            connection.getDescription(), ordered, writeConcern, bypassDocumentValidation, retryWrites, writeRequests,
                            binding.getSessionContext());
                    return executeBulkWriteBatch(binding, connection, bulkWriteBatch);
                } else {
                    return executeLegacyBatches(connection);
                }
            }
        });
    }

Executes a bulk write operation.

@param binding the WriteBinding        for the operation
@return the bulk write result.
@throws MongoBulkWriteException if a failure to complete the bulk write is detected based on the server response


public BulkUpdateRequestBuilder upsert() {
        return new BulkUpdateRequestBuilder(bulkWriteOperation, query, true, codec, replacementCodec, collation, null);
    }

public BulkUpdateRequestBuilder upsert ( ) { return new BulkUpdateRequestBuilder ( bulkWriteOperation , query , true , codec , replacementCodec , collation , null ) ; }

Specifies that the request being built should be an upsert.

@return a new builder that allows only update and replace, since upsert does not apply to remove.
@mongodb.driver.manual tutorial/modify-documents/#upsert-option Upsert

Specifies that the request being built should be an upsert .


public BulkUpdateRequestBuilder arrayFilters(final List<? extends DBObject> arrayFilters) {
        return new BulkUpdateRequestBuilder(bulkWriteOperation, query, false, codec, replacementCodec, collation, arrayFilters);
    }

public BulkUpdateRequestBuilder arrayFilters ( final List < ? extends DBObject > arrayFilters ) { return new BulkUpdateRequestBuilder ( bulkWriteOperation , query , false , codec , replacementCodec , collation , arrayFilters ) ; }

Specifies that the request being built should use the given array filters for an update.  Note that this option only applies to
update operations and will be ignored for replace operations

@param arrayFilters the array filters to apply to the update operation
@return a new builder that allows only update and replace, since upsert does not apply to remove.
@since 3.6
@mongodb.server.release 3.6

Specifies that the request being built should use the given array filters for an update . Note that this option only applies to update operations and will be ignored for replace operations


@Override
    public MapReduceStatistics execute(final WriteBinding binding) {
        return withConnection(binding, new OperationHelper.CallableWithConnection<MapReduceStatistics>() {
            @Override
            public MapReduceStatistics call(final Connection connection) {
                validateCollation(connection, collation);
                return executeCommand(binding, namespace.getDatabaseName(), getCommand(connection.getDescription()),
                        connection, transformer());
            }
        });
    }

@ Override public MapReduceStatistics execute ( final WriteBinding binding ) { return withConnection ( binding , new OperationHelper . CallableWithConnection < MapReduceStatistics > ( ) { @ Override public MapReduceStatistics call ( final Connection connection ) { validateCollation ( connection , collation ) ; return executeCommand ( binding , namespace . getDatabaseName ( ) , getCommand ( connection . getDescription ( ) ) , connection , transformer ( ) ) ; } } ) ; }

Executing this will return a cursor with your results in.

@param binding the binding
@return a MongoCursor that can be iterated over to find all the results of the Map Reduce operation.

Executing this will return a cursor with your results in .


public static synchronized void init(final MongoEmbeddedSettings mongoEmbeddedSettings) {
        if (mongoEmbeddedLibrary != null) {
            throw new MongoClientEmbeddedException("The mongo embedded library has already been initialized");
        }
        try {
            mongoEmbeddedLibrary = MongoEmbeddedCAPI.create(mongoEmbeddedSettings.getYamlConfig(),
                    mongoEmbeddedSettings.getLogLevel().toCapiLogLevel(), mongoEmbeddedSettings.getLibraryPath());
        } catch (Exception e) {
            throw new MongoClientEmbeddedException(format("The mongo embedded library could not be initialized%n"
                    + "Server error message: %s", e.getMessage()), e);
        }

    }

Initializes the mongod library for use.

The library must be called at most once per process before calling {@link #create(MongoClientSettings)}.

@param mongoEmbeddedSettings the settings for the embedded driver.

Initializes the mongod library for use .


public static synchronized MongoClient create(final MongoClientSettings mongoClientSettings) {
        if (mongoEmbeddedLibrary == null) {
            throw new MongoClientEmbeddedException("The mongo embedded library must be initialized first.");
        }
        try {
            Cluster cluster = new EmbeddedCluster(mongoEmbeddedLibrary, mongoClientSettings);
            return new MongoClientImpl(cluster, mongoClientSettings.getWrappedMongoClientSettings(), null);
        } catch (Exception e) {
            throw new MongoClientEmbeddedException(format("Could not create a new embedded cluster.%n"
                    + "Please ensure any existing MongoClients are fully closed before trying to create a new one.%n"
                    + "Server error message: %s", e.getMessage()), e);
        }
    }

Creates a new client.

@param mongoClientSettings the mongoClientSettings
@return the client


public static synchronized void close() {
        if (mongoEmbeddedLibrary != null) {
            try {
                mongoEmbeddedLibrary.close();
            } catch (Exception e) {
                throw new MongoClientEmbeddedException(format("Could not close the mongo embedded library.%n"
                        + "Please ensure that any MongoClient instances have been closed first.%n"
                        + "Server error message: %s", e.getMessage()), e);
            }
            mongoEmbeddedLibrary = null;

        }
    }


public static void enableSni(final String host, final SSLParameters sslParameters) {
        if (SNI_SSL_HELPER != null) {
            SNI_SSL_HELPER.enableSni(host, sslParameters);
        }
    }

public static void enableSni ( final String host , final SSLParameters sslParameters ) { if ( SNI_SSL_HELPER != null ) { SNI_SSL_HELPER . enableSni ( host , sslParameters ) ; } }

Enable SNI if running on Java 8 or later.  Otherwise fail silently to enable SNI.

@param host          the server host
@param sslParameters the SSL parameters

Enable SNI if running on Java 8 or later . Otherwise fail silently to enable SNI .


@SuppressWarnings("deprecation")
    public static byte getType(final Object object) {
        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;
    }

@ SuppressWarnings ( "deprecation" ) public static byte getType ( final Object object ) { 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 ; }

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


public DBObject toDBObject() {
        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;
    }

public
DBObject
toDBObject
(
)
{
BasicDBObject
cmd
=
new
BasicDBObject
(
)
;
cmd
.
put
(
"mapreduce"
,
mapReduce
)
;
cmd
.
put
(
"map"
,
map
)
;
cmd
.
put
(
"reduce"
,
reduce
)
;
if
(
verbose
!=
)
{
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
!=
)
{
out
.
put
(
"db"
,
outputDB
)
;
}
cmd
.
put
(
"out"
,
out
)
;
if
(
query
!=
)
{
cmd
.
put
(
"query"
,
query
)
;
}
if
(
finalize
!=
)
{
cmd
.
put
(
"finalize"
,
finalize
)
;
}
if
(
sort
!=
)
{
cmd
.
put
(
"sort"
,
sort
)
;
}
if
(
limit
>
0
)
{
cmd
.
put
(
"limit"
,
limit
)
;
}
if
(
scope
!=
)
{
cmd
.
put
(
"scope"
,
scope
)
;
}
if
(
jsMode
!=
)
{
cmd
.
put
(
"jsMode"
,
jsMode
)
;
}
if
(
maxTimeMS
!=
0
)
{
cmd
.
put
(
"maxTimeMS"
,
maxTimeMS
)
;
}
return
cmd
;
}

Turns this command into a DBObject representation of this map reduce command.

@return a DBObject that contains the MongoDB document representation of this command.

Turns this command into a DBObject representation of this map reduce command .


public String getShortDescription() {
        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 + '\'')
               + '}';
    }

public
String
getShortDescription
(
)
{
return
"{"
+
(
hosts
.
isEmpty
(
)
""
:
"hosts="
+
hosts
)
+
(
srvHost
==
""
:
", srvHost="
+
srvHost
)
+
", mode="
+
mode
+
", requiredClusterType="
+
requiredClusterType
+
", serverSelectionTimeout='"
+
serverSelectionTimeoutMS
+
" ms"
+
'
'
+
", maxWaitQueueSize="
+
maxWaitQueueSize
+
(
requiredReplicaSetName
==
""
:
", requiredReplicaSetName='"
+
requiredReplicaSetName
+
'
'
)
+
(
description
==
""
:
", description='"
+
description
+
'
'
)
+
'
'
;
}

Returns a short, pretty description for these ClusterSettings.

@return a String description of the relevant settings.

Returns a short pretty description for these ClusterSettings .


public static UpdateResult acknowledged(final long matchedCount, @Nullable final Long modifiedCount,
                                            @Nullable final BsonValue upsertedId) {
        return new AcknowledgedUpdateResult(matchedCount, modifiedCount, upsertedId);
    }

public static UpdateResult acknowledged ( final long matchedCount , @ Nullable final Long modifiedCount , @ Nullable final BsonValue upsertedId ) { return new AcknowledgedUpdateResult ( matchedCount , modifiedCount , upsertedId ) ; }

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


@Deprecated
    public String getContentType() {
        if (extraElements != null && extraElements.containsKey("contentType")) {
            return extraElements.getString("contentType");
        } else {
            throw new MongoGridFSException("No contentType data for this GridFS file");
        }
    }

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
    @SuppressWarnings("unchecked")
    public List<String> getAliases() {
        if (extraElements != null && extraElements.containsKey("aliases")) {
            return (List<String>) extraElements.get("aliases");
        } else {
            throw new MongoGridFSException("No aliases data for this GridFS file");
        }
    }

@
Deprecated
@
SuppressWarnings
(
"unchecked"
)
public
List
<
String
>
getAliases
(
)
{
if
(
extraElements
!=
&&
extraElements
.
containsKey
(
"aliases"
)
)
{
return
(
List
<
String
>
)
extraElements
.
get
(
"aliases"
)
;
}
else
{
throw
new
MongoGridFSException
(
"No aliases data for this GridFS file"
)
;
}
}

The aliases for the file

@return the aliases of the file
@deprecated any aliases should be stored in the metadata document instead.


public String getFirstKey() {
        return findInDocument(new Finder<String>() {
            @Override
            public String find(final BsonReader bsonReader) {
                return bsonReader.readName();
            }

            @Override
            public String notFound() {
                throw new NoSuchElementException();
            }
        });
    }

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

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

Gets the first key in this document or null if the document is empty .


public <T> void encodeWithChildContext(final Encoder<T> encoder, final BsonWriter writer, final T value) {
        encoder.encode(writer, value, DEFAULT_CONTEXT);
    }

public < T > void encodeWithChildContext ( final Encoder < T > encoder , final BsonWriter writer , final T value ) { encoder . encode ( writer , value , DEFAULT_CONTEXT ) ; }

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

Creates a child context based on this and serializes the value with it to the writer .


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

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

Gets this read concern as a document.

@return The read concern as a BsonDocument


@Override
    public void compress(final List<ByteBuf> source, final BsonOutput target) {
        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);
        }
    }

@
Override
public
void
compress
(
final
List
<
ByteBuf
>
source
,
final
BsonOutput
target
)
{
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
)
;
}
}

be copied into a single byte array.  For that reason the compress method defined in the base class can't be used.

be copied into a single byte array . For that reason the compress method defined in the base class can t be used .


public String getString(final String key) {
        Object foo = get(key);
        if (foo == null) {
            return null;
        }
        return foo.toString();
    }

public String getString ( final String key ) { Object foo = get ( key ) ; if ( foo == null ) { return null ; } return foo . toString ( ) ; }

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 boolean getBoolean(final String key, final boolean def) {
        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());
    }

public
boolean
getBoolean
(
final
String
key
,
final
boolean
def
)
{
Object
foo
=
get
(
key
)
;
if
(
foo
==
)
{
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
(
)
)
;
}

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 ObjectId getObjectId(final String field, final ObjectId def) {
        Object foo = get(field);
        return (foo != null) ? (ObjectId) foo : def;
    }

public ObjectId getObjectId ( final String field , final ObjectId def ) { Object foo = get ( field ) ; return ( foo != null ) ? ( ObjectId ) foo : def ; }

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.

Returns the object id or def if not set .


public Date getDate(final String field, final Date def) {
        Object foo = get(field);
        return (foo != null) ? (Date) foo : def;
    }

public Date getDate ( final String field , final Date def ) { Object foo = get ( field ) ; return ( foo != null ) ? ( Date ) foo : def ; }

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.


@SuppressWarnings("unchecked")
    private static Object canonicalize(final Object from) {
        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;
        }
    }

@ SuppressWarnings ( "unchecked" ) private static Object canonicalize ( final Object from ) { 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 ; } }

create a copy of "from", but with keys ordered alphabetically

create a copy of from but with keys ordered alphabetically


@Nullable
    public MongoCredential getCredential() {
        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);
        }
    }

Gets the credential that this client authenticates all connections with

@return the credential, which may be null in unsecured deployments
@since 3.9


public ClientSession startSession(final ClientSessionOptions options) {
        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;
    }

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


@Nullable
    public Integer getWTimeout(final TimeUnit timeUnit) {
        notNull("timeUnit", timeUnit);
        return wTimeoutMS == null ? null : (int) timeUnit.convert(wTimeoutMS, TimeUnit.MILLISECONDS);
    }

@ Nullable public Integer getWTimeout ( final TimeUnit timeUnit ) { notNull ( "timeUnit" , timeUnit ) ; return wTimeoutMS == null ? null : ( int ) timeUnit . convert ( wTimeoutMS , TimeUnit . MILLISECONDS ) ; }

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

Gets the wTimeout in the given time unit .


public BsonDocument asDocument() {
        BsonDocument document = new BsonDocument();

        addW(document);

        addWTimeout(document);
        addFSync(document);
        addJ(document);

        return document;
    }

public BsonDocument asDocument ( ) { BsonDocument document = new BsonDocument ( ) ; addW ( document ) ; addWTimeout ( document ) ; addFSync ( document ) ; addJ ( document ) ; return document ; }

Gets this write concern as a document.

@return The write concern as a BsonDocument, even if {@code w <= 0}


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

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

Returns true if this write concern indicates that write operations must be acknowledged.

@return true w != null or w > 0 or journal is true or fsync is true
@mongodb.driver.manual core/write-concern/#acknowledged Acknowledged

Returns true if this write concern indicates that write operations must be acknowledged .


public WriteConcern withW(final int w) {
        return new WriteConcern(Integer.valueOf(w), wTimeoutMS, fsync, journal);
    }

public WriteConcern withW ( final int w ) { return new WriteConcern ( Integer . valueOf ( w ) , wTimeoutMS , fsync , journal ) ; }

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

Constructs a new WriteConcern from the current one and the specified integer - based value for w


public WriteConcern withW(final String w) {
        notNull("w", w);
        return new WriteConcern(w, wTimeoutMS, fsync, journal);
    }

public WriteConcern withW ( final String w ) { notNull ( "w" , w ) ; return new WriteConcern ( w , wTimeoutMS , fsync , journal ) ; }

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

Constructs a new WriteConcern from the current one and the specified tag - set based value for w


public WriteConcern withWTimeout(final long wTimeout, final TimeUnit timeUnit) {
        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);
    }

public
WriteConcern
withWTimeout
(
final
long
wTimeout
,
final
TimeUnit
timeUnit
)
{
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
)
;
}

Constructs a new WriteConcern from the current one and the specified wTimeout in the given time unit.

@param wTimeout the wTimeout, which must be >= 0 and <= 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

Constructs a new WriteConcern from the current one and the specified wTimeout in the given time unit .


@Deprecated
    public static Majority majorityWriteConcern(final int wtimeout, final boolean fsync, final boolean j) {
        return new Majority(wtimeout, fsync, j);
    }

@ Deprecated public static Majority majorityWriteConcern ( final int wtimeout , final boolean fsync , final boolean j ) { return new Majority ( wtimeout , fsync , j ) ; }

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)}

Create a Majority Write Concern that requires a majority of servers to acknowledge the write .


public void insert(final DBObject document) {
        isTrue("already executed", !closed);
        if (document.get(ID_FIELD_NAME) == null) {
            document.put(ID_FIELD_NAME, new ObjectId());
        }
        addRequest(new InsertRequest(document, collection.getObjectCodec()));
    }

public
void
insert
(
final
DBObject
document
)
{
isTrue
(
"already executed"
,
!
closed
)
;
if
(
document
.
get
(
ID_FIELD_NAME
)
==
)
{
document
.
put
(
ID_FIELD_NAME
,
new
ObjectId
(
)
)
;
}
addRequest
(
new
InsertRequest
(
document
,
collection
.
getObjectCodec
(
)
)
)
;
}

Add an insert request to the bulk operation

@param document the document to insert


public BulkWriteRequestBuilder find(final DBObject query) {
        isTrue("already executed", !closed);
        return new BulkWriteRequestBuilder(this, query, collection.getDefaultDBObjectCodec(), collection.getObjectCodec());
    }

public
BulkWriteRequestBuilder
find
(
final
DBObject
query
)
{
isTrue
(
"already executed"
,
!
closed
)
;
return
new
BulkWriteRequestBuilder
(
this
,
query
,
collection
.
getDefaultDBObjectCodec
(
)
,
collection
.
getObjectCodec
(
)
)
;
}

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

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 .


public BulkWriteResult execute() {
        isTrue("already executed", !closed);
        closed = true;
        return collection.executeBulkWriteOperation(ordered, bypassDocumentValidation, requests);
    }

public
BulkWriteResult
execute
(
)
{
isTrue
(
"already executed"
,
!
closed
)
;
closed
=
true
;
return
collection
.
executeBulkWriteOperation
(
ordered
,
bypassDocumentValidation
,
requests
)
;
}

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

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 .


public Object copy() {
        // 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;
    }

public
Object
copy
(
)
{
// 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
;
}

Creates a new instance which is a copy of this BasicDBObject.

@return a BasicDBObject with exactly the same values as this instance.

Creates a new instance which is a copy of this BasicDBObject .


public static Bson geoHaystack(final String fieldName, final Bson additional) {
        notNull("fieldName", fieldName);
        return compoundIndex(new BsonDocument(fieldName, new BsonString("geoHaystack")), additional);
    }

public static Bson geoHaystack ( final String fieldName , final Bson additional ) { notNull ( "fieldName" , fieldName ) ; return compoundIndex ( new BsonDocument ( fieldName , new BsonString ( "geoHaystack" ) ) , additional ) ; }

Create an index key for a geohaystack index on the given field.

Note: 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

Create an index key for a geohaystack index on the given field .


public List<String> getIndexNames() {
        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;
    }

public List < String > getIndexNames ( ) { 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 ; }

Gets the index names.

@return a list of index names


public BsonValue get(final Object key, final BsonValue defaultValue) {
        BsonValue value = get(key);
        return value != null ? value : defaultValue;
    }

public BsonValue get ( final Object key , final BsonValue defaultValue ) { BsonValue value = get ( key ) ; return value != null ? value : defaultValue ; }

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

If the document does not contain the given key return the given default value . Otherwise gets the value of the key .


public BsonDocument getDocument(final Object key, final BsonDocument defaultValue) {
        if (!containsKey(key)) {
            return defaultValue;
        }
        return get(key).asDocument();
    }

public BsonDocument getDocument ( final Object key , final BsonDocument defaultValue ) { if ( ! containsKey ( key ) ) { return defaultValue ; } return get ( key ) . asDocument ( ) ; }

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

If the document does not contain the given key return the given default value . Otherwise gets the value of the key as a BsonDocument .


public BsonArray getArray(final Object key, final BsonArray defaultValue) {
        if (!containsKey(key)) {
            return defaultValue;
        }
        return get(key).asArray();
    }

public BsonArray getArray ( final Object key , final BsonArray defaultValue ) { if ( ! containsKey ( key ) ) { return defaultValue ; } return get ( key ) . asArray ( ) ; }

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

If the document does not contain the given key return the given default value . Otherwise gets the value of the key as a BsonArray .


public BsonNumber getNumber(final Object key, final BsonNumber defaultValue) {
        if (!containsKey(key)) {
            return defaultValue;
        }
        return get(key).asNumber();
    }

public BsonNumber getNumber ( final Object key , final BsonNumber defaultValue ) { if ( ! containsKey ( key ) ) { return defaultValue ; } return get ( key ) . asNumber ( ) ; }

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

If the document does not contain the given key return the given default value . Otherwise gets the value of the key as a BsonNumber .


public BsonInt32 getInt32(final Object key, final BsonInt32 defaultValue) {
        if (!containsKey(key)) {
            return defaultValue;
        }
        return get(key).asInt32();
    }

public BsonInt32 getInt32 ( final Object key , final BsonInt32 defaultValue ) { if ( ! containsKey ( key ) ) { return defaultValue ; } return get ( key ) . asInt32 ( ) ; }

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

If the document does not contain the given key return the given default value . Otherwise gets the value of the key as a BsonInt32 .


public BsonInt64 getInt64(final Object key, final BsonInt64 defaultValue) {
        if (!containsKey(key)) {
            return defaultValue;
        }
        return get(key).asInt64();
    }

public BsonInt64 getInt64 ( final Object key , final BsonInt64 defaultValue ) { if ( ! containsKey ( key ) ) { return defaultValue ; } return get ( key ) . asInt64 ( ) ; }

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

If the document does not contain the given key return the given default value . Otherwise gets the value of the key as a BsonInt64 .


public BsonDecimal128 getDecimal128(final Object key, final BsonDecimal128 defaultValue) {
        if (!containsKey(key)) {
            return defaultValue;
        }
        return get(key).asDecimal128();
    }

public BsonDecimal128 getDecimal128 ( final Object key , final BsonDecimal128 defaultValue ) { if ( ! containsKey ( key ) ) { return defaultValue ; } return get ( key ) . asDecimal128 ( ) ; }

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

If the document does not contain the given key return the given default value . Otherwise gets the value of the key as a BsonDecimal128 .


public BsonDouble getDouble(final Object key, final BsonDouble defaultValue) {
        if (!containsKey(key)) {
            return defaultValue;
        }
        return get(key).asDouble();
    }

public BsonDouble getDouble ( final Object key , final BsonDouble defaultValue ) { if ( ! containsKey ( key ) ) { return defaultValue ; } return get ( key ) . asDouble ( ) ; }

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

If the document does not contain the given key return the given default value . Otherwise gets the value of the key as a BsonDouble .


public BsonBoolean getBoolean(final Object key, final BsonBoolean defaultValue) {
        if (!containsKey(key)) {
            return defaultValue;
        }
        return get(key).asBoolean();
    }

public BsonBoolean getBoolean ( final Object key , final BsonBoolean defaultValue ) { if ( ! containsKey ( key ) ) { return defaultValue ; } return get ( key ) . asBoolean ( ) ; }

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

If the document does not contain the given key return the given default value . Otherwise gets the value of the key as a BsonBoolean .


public BsonString getString(final Object key, final BsonString defaultValue) {
        if (!containsKey(key)) {
            return defaultValue;
        }
        return get(key).asString();
    }

public BsonString getString ( final Object key , final BsonString defaultValue ) { if ( ! containsKey ( key ) ) { return defaultValue ; } return get ( key ) . asString ( ) ; }

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

If the document does not contain the given key return the given default value . Otherwise gets the value of the key as a BsonString .


public BsonDateTime getDateTime(final Object key, final BsonDateTime defaultValue) {
        if (!containsKey(key)) {
            return defaultValue;
        }
        return get(key).asDateTime();
    }

public BsonDateTime getDateTime ( final Object key , final BsonDateTime defaultValue ) { if ( ! containsKey ( key ) ) { return defaultValue ; } return get ( key ) . asDateTime ( ) ; }

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

If the document does not contain the given key return the given default value . Otherwise gets the value of the key as a BsonDateTime .


public BsonTimestamp getTimestamp(final Object key, final BsonTimestamp defaultValue) {
        if (!containsKey(key)) {
            return defaultValue;
        }
        return get(key).asTimestamp();
    }

public BsonTimestamp getTimestamp ( final Object key , final BsonTimestamp defaultValue ) { if ( ! containsKey ( key ) ) { return defaultValue ; } return get ( key ) . asTimestamp ( ) ; }

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

If the document does not contain the given key return the given default value . Otherwise gets the value of the key as a BsonTimestamp .


public BsonObjectId getObjectId(final Object key, final BsonObjectId defaultValue) {
        if (!containsKey(key)) {
            return defaultValue;
        }
        return get(key).asObjectId();
    }

public BsonObjectId getObjectId ( final Object key , final BsonObjectId defaultValue ) { if ( ! containsKey ( key ) ) { return defaultValue ; } return get ( key ) . asObjectId ( ) ; }

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

If the document does not contain the given key return the given default value . Otherwise gets the value of the key as a BsonObjectId .


public BsonBinary getBinary(final Object key, final BsonBinary defaultValue) {
        if (!containsKey(key)) {
            return defaultValue;
        }
        return get(key).asBinary();
    }

public BsonBinary getBinary ( final Object key , final BsonBinary defaultValue ) { if ( ! containsKey ( key ) ) { return defaultValue ; } return get ( key ) . asBinary ( ) ; }

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

If the document does not contain the given key return the given default value . Otherwise gets the value of the key as a BsonBinary .


public BsonRegularExpression getRegularExpression(final Object key, final BsonRegularExpression defaultValue) {
        if (!containsKey(key)) {
            return defaultValue;
        }
        return get(key).asRegularExpression();
    }

public BsonRegularExpression getRegularExpression ( final Object key , final BsonRegularExpression defaultValue ) { if ( ! containsKey ( key ) ) { return defaultValue ; } return get ( key ) . asRegularExpression ( ) ; }

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

If the document does not contain the given key return the given default value . Otherwise gets the value of the key as a BsonRegularExpression .


private void writeHandlingTasks(final RegisteredSocket socket, final WriteOperation op) throws IOException {
        while (true) {
            try {
                socket.tlsChannel.write(op.bufferSet.array, op.bufferSet.offset, op.bufferSet.length);
                return;
            } catch (NeedsTaskException e) {
                warnAboutNeedTask();
                e.getTask().run();
            }
        }
    }

private void writeHandlingTasks ( final RegisteredSocket socket , final WriteOperation op ) throws IOException { while ( true ) { try { socket . tlsChannel . write ( op . bufferSet . array , op . bufferSet . offset , op . bufferSet . length ) ; return ; } catch ( NeedsTaskException e ) { warnAboutNeedTask ( ) ; e . getTask ( ) . run ( ) ; } } }

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.

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 .


@SuppressWarnings({"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()));
        }
    }

@ SuppressWarnings ( { "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 ( ) ) ) ; } }

A helper to convert an document of type Object to a BsonDocument

If not already a BsonDocument it looks up the documents' class in the codecRegistry and wraps it into a BsonDocumentWrapper

@param document      the document to convert
@param codecRegistry the codecRegistry that can be used in the conversion of the Object
@return a BsonDocument


public static <T> T notNull(final String name, final T value, final SingleResultCallback<?> callback) {
        if (value == null) {
            IllegalArgumentException exception = new IllegalArgumentException(name + " can not be null");
            callback.onResult(null, exception);
            throw exception;
        }
        return value;
    }

public
static
<
T
>
T
notNull
(
final
String
name
,
final
T
value
,
final
SingleResultCallback
<
>
callback
)
{
if
(
value
==
)
{
IllegalArgumentException
exception
=
new
IllegalArgumentException
(
name
+
" can not be null"
)
;
callback
.
onResult
(
,
exception
)
;
throw
exception
;
}
return
value
;
}

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

Throw IllegalArgumentException if the value is null .


public static void isTrue(final String name, final boolean condition, final SingleResultCallback<?> callback) {
        if (!condition) {
            IllegalStateException exception = new IllegalStateException("state should be: " + name);
            callback.onResult(null, exception);
            throw exception;
        }
    }

public
static
void
isTrue
(
final
String
name
,
final
boolean
condition
,
final
SingleResultCallback
<
>
callback
)
{
if
(
!
condition
)
{
IllegalStateException
exception
=
new
IllegalStateException
(
"state should be: "
+
name
)
;
callback
.
onResult
(
,
exception
)
;
throw
exception
;
}
}

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

Throw IllegalStateException if the condition if false .


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

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

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 ClassModel<T> build() {
        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));
    }

public ClassModel < T > build ( ) { 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 ) ) ; }

Creates a new ClassModel instance based on the mapping data provided.

@return the new instance

Creates a new ClassModel instance based on the mapping data provided .


@Deprecated
    public UpdateOptions getOptions() {
        return new UpdateOptions()
                .bypassDocumentValidation(options.getBypassDocumentValidation())
                .collation(options.getCollation())
                .upsert(options.isUpsert());
    }

@ Deprecated public UpdateOptions getOptions ( ) { return new UpdateOptions ( ) . bypassDocumentValidation ( options . getBypassDocumentValidation ( ) ) . collation ( options . getCollation ( ) ) . upsert ( options . isUpsert ( ) ) ; }

Gets the options to apply.

@return the update options
@deprecated use {@link #getReplaceOptions()} instead


@Nullable
    public static JavaWrapper getWrapperIfReflectionObject(final Class c) {
        if (ReflectionDBObject.class.isAssignableFrom(c)) {
            return getWrapper(c);
        }
        return null;
    }

@ Nullable public static JavaWrapper getWrapperIfReflectionObject ( final Class c ) { if ( ReflectionDBObject . class . isAssignableFrom ( c ) ) { return getWrapper ( c ) ; } return null ; }

Returns the wrapper if this object can be assigned from this class.

@param c the class to be wrapped
@return the wrapper

Returns the wrapper if this object can be assigned from this class .


public static JavaWrapper getWrapper(final Class c) {
        JavaWrapper w = _wrappers.get(c);
        if (w == null) {
            w = new JavaWrapper(c);
            _wrappers.put(c, w);
        }
        return w;
    }

public static JavaWrapper getWrapper ( final Class c ) { JavaWrapper w = _wrappers . get ( c ) ; if ( w == null ) { w = new JavaWrapper ( c ) ; _wrappers . put ( c , w ) ; } return w ; }

Returns an existing Wrapper instance associated with a class, or creates a new one.

@param c the class to be wrapped
@return the wrapped

Returns an existing Wrapper instance associated with a class or creates a new one .


public UUID asUuid() {
        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);
    }

Returns the binary as a UUID. The binary type must be 4.

@return the uuid
@since 3.9

Returns the binary as a UUID . The binary type must be 4 .


public UUID asUuid(final UuidRepresentation uuidRepresentation) {
        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);
    }

Returns the binary as a UUID.

@param uuidRepresentation the UUID representation
@return the uuid
@since 3.9


protected Object parse(final String name) {
        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;
    }

protected
Object
parse
(
final
String
name
)
{
Object
value
=
;
char
current
=
get
(
)
;
switch
(
current
)
{
// null
case
'
'
:
read
(
'
'
)
;
read
(
'
'
)
;
read
(
'
'
)
;
read
(
'
'
)
;
value
=
;
break
;
// NaN
case
'
'
:
read
(
'
'
)
;
read
(
'
'
)
;
read
(
'
'
)
;
value
=
Double
.
;
break
;
// true
case
'
'
:
read
(
'
'
)
;
read
(
'
'
)
;
read
(
'
'
)
;
read
(
'
'
)
;
value
=
true
;
break
;
// false
case
'
'
:
read
(
'
'
)
;
read
(
'
'
)
;
read
(
'
'
)
;
read
(
'
'
)
;
read
(
'
'
)
;
value
=
false
;
break
;
// string
case
'
'
:
case
'
'
:
value
=
parseString
(
true
)
;
break
;
// number
case
'
'
:
case
'
'
:
case
'
'
:
case
'
'
:
case
'
'
:
case
'
'
:
case
'
'
:
case
'
'
:
case
'
'
:
case
'
'
:
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
;
}

Parse an unknown type.

@return Object the next item
@throws JSONParseException if invalid JSON is found


public void readHex() {
        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);
        }
    }

public void readHex ( ) { if ( pos < s . length ( ) && ( ( s . charAt ( pos ) >= ' ' && s . charAt ( pos ) <= ' ' ) || ( s . charAt ( pos ) >= ' ' && s . charAt ( pos ) <= ' ' ) || ( s . charAt ( pos ) >= ' ' && s . charAt ( pos ) <= ' ' ) ) ) { pos ++ ; } else { throw new JSONParseException ( s , pos ) ; } }

Read the current character, making sure that it is a hexidecimal character.

@throws JSONParseException if the current character is not a hexidecimal character

Read the current character making sure that it is a hexidecimal character .


public void skipWS() {
        while (pos < s.length() && Character.isWhitespace(s.charAt(pos))) {
            pos++;
        }
    }

public void skipWS ( ) { while ( pos < s . length ( ) && Character . isWhitespace ( s . charAt ( pos ) ) ) { pos ++ ; } }

Advances the position in the string past any whitespace.

Advances the position in the string past any whitespace .


public String parseString(final boolean needQuote) {
        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();
    }

public
String
parseString
(
final
boolean
needQuote
)
{
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
'
'
:
// 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
'
'
:
special
=
'
'
;
break
;
case
'
'
:
special
=
'
'
;
break
;
case
'
'
:
special
=
'
'
;
break
;
case
'
'
:
special
=
'
'
;
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
(
)
;
}

Parses a string.

@return the next string.
@throws JSONParseException if invalid JSON is found


public Number parseNumber() {

        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);
        }
    }

public Number parseNumber ( ) { get ( ) ; int start = this . pos ; boolean isDouble = false ; if ( check ( ' ' ) || check ( ' ' ) ) { pos ++ ; } outer : while ( pos < s . length ( ) ) { switch ( s . charAt ( pos ) ) { case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : case ' ' : pos ++ ; break ; case ' ' : isDouble = true ; parseFraction ( ) ; break ; case ' ' : case ' ' : 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 ) ; } }

Parses a number.

@return the next number (int or double).
@throws JSONParseException if invalid JSON is found


public void parseExponent() {
        // 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;
            }
        }
    }

public
void
parseExponent
(
)
{
// get past E
pos
++
;
if
(
check
(
'
'
)
||
check
(
'
'
)
)
{
pos
++
;
}
outer
:
while
(
pos
<
s
.
length
(
)
)
{
switch
(
s
.
charAt
(
pos
)
)
{
case
'
'
:
case
'
'
:
case
'
'
:
case
'
'
:
case
'
'
:
case
'
'
:
case
'
'
:
case
'
'
:
case
'
'
:
case
'
'
:
pos
++
;
break
;
default
:
break
outer
;
}
}
}

Advances the pointer through the exponent.

Advances the pointer through the exponent .


protected Object parseArray(final String name) {
        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();
    }

protected Object parseArray ( final String name ) { 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 ( ) ; }

Parses the next array.

@return the array
@throws JSONParseException if invalid JSON is found


public void updateOne(final DBObject update) {
        bulkWriteOperation.addRequest(new UpdateRequest(query, update, false, upsert, queryCodec, collation, arrayFilters));
    }

public void updateOne ( final DBObject update ) { bulkWriteOperation . addRequest ( new UpdateRequest ( query , update , false , upsert , queryCodec , collation , arrayFilters ) ) ; }

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

Adds a request to update one document in the collection that matches the query with which this builder was created .


public ConnectionDescription withConnectionId(final ConnectionId connectionId) {
        notNull("connectionId", connectionId);
        return new ConnectionDescription(connectionId, serverVersion, maxWireVersion, serverType, maxBatchCount, maxDocumentSize,
                maxMessageSize, compressors);
    }

public ConnectionDescription withConnectionId ( final ConnectionId connectionId ) { notNull ( "connectionId" , connectionId ) ; return new ConnectionDescription ( connectionId , serverVersion , maxWireVersion , serverType , maxBatchCount , maxDocumentSize , maxMessageSize , compressors ) ; }

Creates a new connection description with the set connection id

@param connectionId the connection id
@return the new connection description
@since 3.8


public static WriteConcernResult acknowledged(final int count, final boolean isUpdateOfExisting, @Nullable final BsonValue upsertedId) {
        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
                       + '}';
            }
        };
    }

public
static
WriteConcernResult
acknowledged
(
final
int
count
,
final
boolean
isUpdateOfExisting
,
@
Nullable
final
BsonValue
upsertedId
)
{
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
==
||
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
!=
!
upsertedId
.
equals
(
that
.
getUpsertedId
(
)
)
:
that
.
getUpsertedId
(
)
!=
)
{
return
false
;
}
return
true
;
}
@
Override
public
int
hashCode
(
)
{
int
result
=
count
;
result
=
31
*
result
+
(
isUpdateOfExisting
1
:
0
)
;
result
=
31
*
result
+
(
upsertedId
!=
upsertedId
.
hashCode
(
)
:
0
)
;
return
result
;
}
@
Override
public
String
toString
(
)
{
return
"AcknowledgedWriteResult{"
+
"count="
+
count
+
", isUpdateOfExisting="
+
isUpdateOfExisting
+
", upsertedId="
+
upsertedId
+
'
'
;
}
}
;
}

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 unacknowledged() {
        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");
            }
        };
    }

Create an unacknowledged WriteConcernResult

@return an unacknowledged WriteConcernResult


@SuppressWarnings("unchecked")
    private <T> T getEmbeddedValue(final List<?> keys, final Class<T> clazz, final T defaultValue) {
        Object value = this;
        Iterator<?> keyIterator = keys.iterator();
        while (keyIterator.hasNext()) {
            Object key = keyIterator.next();
            value = ((Document) value).get(key);
            if (!(value instanceof Document)) {
                if (value == null) {
                    return defaultValue;
                } else if (keyIterator.hasNext()) {
                    throw new ClassCastException(format("At key %s, the value is not a Document (%s)",
                            key, value.getClass().getName()));
                }
            }
        }
        return clazz != null ? clazz.cast(value) : (T) value;
    }

Throws ClassCastException if any of the intermediate embedded values is not a Document.

Throws ClassCastException if any of the intermediate embedded values is not a Document .


@SuppressWarnings("unchecked")
    private <T> List<T> constructValuesList(final Object key, final Class<T> clazz, final List<T> defaultValue) {
        List<?> value = get(key, List.class);
        if (value == null) {
            return defaultValue;
        }

        for (Object item : value) {
            if (!clazz.isAssignableFrom(item.getClass())) {
                throw new ClassCastException(format("List element cannot be cast to %s", clazz.getName()));
            }
        }
        return (List<T>) value;
    }

@
SuppressWarnings
(
"unchecked"
)
private
<
T
>
List
<
T
>
constructValuesList
(
final
Object
key
,
final
Class
<
T
>
clazz
,
final
List
<
T
>
defaultValue
)
{
List
<
>
value
=
get
(
key
,
List
.
class
)
;
if
(
value
==
)
{
return
defaultValue
;
}
for
(
Object
item
:
value
)
{
if
(
!
clazz
.
isAssignableFrom
(
item
.
getClass
(
)
)
)
{
throw
new
ClassCastException
(
format
(
"List element cannot be cast to %s"
,
clazz
.
getName
(
)
)
)
;
}
}
return
(
List
<
T
>
)
value
;
}

A ClassCastException will be thrown if an element in the list is not of type T.

A ClassCastException will be thrown if an element in the list is not of type T .


public static TransactionOptions merge(final TransactionOptions options, final TransactionOptions defaultOptions) {
        notNull("options", options);
        notNull("defaultOptions", defaultOptions);
        return TransactionOptions.builder()
                .writeConcern(options.getWriteConcern() == null
                        ? defaultOptions.getWriteConcern() : options.getWriteConcern())
                .readConcern(options.getReadConcern() == null
                        ? defaultOptions.getReadConcern() : options.getReadConcern())
                .readPreference(options.getReadPreference() == null
                        ? defaultOptions.getReadPreference() : options.getReadPreference())
                .build();
    }

public static TransactionOptions merge ( final TransactionOptions options , final TransactionOptions defaultOptions ) { notNull ( "options" , options ) ; notNull ( "defaultOptions" , defaultOptions ) ; return TransactionOptions . builder ( ) . writeConcern ( options . getWriteConcern ( ) == null ? defaultOptions . getWriteConcern ( ) : options . getWriteConcern ( ) ) . readConcern ( options . getReadConcern ( ) == null ? defaultOptions . getReadConcern ( ) : options . getReadConcern ( ) ) . readPreference ( options . getReadPreference ( ) == null ? defaultOptions . getReadPreference ( ) : options . getReadPreference ( ) ) . build ( ) ; }

Merge the two provided transaction options, with the first taking precedence over the second.

@param options the transaction options, which take precedence for any property that is non-null
@param defaultOptions the default transaction options
@return the merged transaction options

Merge the two provided transaction options with the first taking precedence over the second .


@Override
    public void release(final T t, final boolean prune) {
        if (t == null) {
            throw new IllegalArgumentException("Can not return a null item to the pool");
        }
        if (closed) {
            close(t);
            return;
        }

        if (prune) {
            close(t);
        } else {
            available.addLast(t);
        }

        releasePermit();
    }

call done when you are done with an object from the pool if there is room and the object is ok will get added

@param t     item to return to the pool
@param prune true if the item should be closed, false if it should be put back in the pool


@Override
    public T get(final long timeout, final TimeUnit timeUnit) {
        if (closed) {
            throw new IllegalStateException("The pool is closed");
        }

        if (!acquirePermit(timeout, timeUnit)) {
            throw new MongoTimeoutException(String.format("Timeout waiting for a pooled item after %d %s", timeout, timeUnit));
        }

        T t = available.pollLast();
        if (t == null) {
            t = createNewAndReleasePermitIfFailure(false);
        }

        return t;
    }

Gets an object from the pool - will block if none are available

@param timeout  negative - forever 0        - return immediately no matter what positive ms to wait
@param timeUnit the time unit of the timeout
@return An object from the pool, or null if can't get one in the given waitTime
@throws MongoTimeoutException if the timeout has been exceeded


@Override
    public void close() {
        closed = true;
        Iterator<T> iter = available.iterator();
        while (iter.hasNext()) {
            T t = iter.next();
            close(t);
            iter.remove();
        }
    }

@ Override public void close ( ) { closed = true ; Iterator < T > iter = available . iterator ( ) ; while ( iter . hasNext ( ) ) { T t = iter . next ( ) ; close ( t ) ; iter . remove ( ) ; } }


public int pipe(final OutputStream os) throws IOException {
        WritableByteChannel channel = Channels.newChannel(os);
        return channel.write(getBufferForInternalBytes());
    }

public int pipe ( final OutputStream os ) throws IOException { WritableByteChannel channel = Channels . newChannel ( os ) ; return channel . write ( getBufferForInternalBytes ( ) ) ; }

Pipe the raw bytes into the given output stream.

@param os the output stream
@return the number of bytes written
@throws IOException any IOException thrown by the output stream

Pipe the raw bytes into the given output stream .