private void appendTaskStackTrace(final Throwable error) {
    StackTraceElement[] taskStackTrace = _taskStackTraceHolder != null ? _taskStackTraceHolder.getStackTrace() : null;

    // At a minimum, any stack trace should have at least 3 stack frames (caller + BaseTask + getStackTrace).
    // So if there are less than 3 stack frames available then there's something fishy and it's better to ignore them.
    if (!ParSeqGlobalConfiguration.isCrossThreadStackTracesEnabled() || error == null ||
        taskStackTrace == null || taskStackTrace.length <= 2) {
      return;
    }

    StackTraceElement[] errorStackTrace = error.getStackTrace();
    if (errorStackTrace.length <= 2) {
      return;
    }

    // Skip stack frames up to the BaseTask (useless java.util.concurrent stuff)
    int skipErrorFrames = 1;
    while (skipErrorFrames < errorStackTrace.length) {
      int index = errorStackTrace.length - 1 - skipErrorFrames;
      if (!errorStackTrace[index].getClassName().equals(CANONICAL_NAME) &&
          errorStackTrace[index + 1].getClassName().equals(CANONICAL_NAME)) {
        break;
      }
      skipErrorFrames++;
    }

    // Safeguard against accidentally removing entire stack trace
    if (skipErrorFrames == errorStackTrace.length) {
      skipErrorFrames = 0;
    }

    // Skip stack frames up to the BaseTask (useless Thread.getStackTrace stuff)
    int skipTaskFrames = 1;
    while (skipTaskFrames < taskStackTrace.length) {
      if (!taskStackTrace[skipTaskFrames].getClassName().equals(CANONICAL_NAME) &&
          taskStackTrace[skipTaskFrames - 1].getClassName().equals(CANONICAL_NAME)) {
        break;
      }
      skipTaskFrames++;
    }

    // Safeguard against accidentally removing entire stack trace
    if (skipTaskFrames == taskStackTrace.length) {
      skipTaskFrames = 0;
    }

    int combinedLength = errorStackTrace.length - skipErrorFrames + taskStackTrace.length - skipTaskFrames;
    if (combinedLength <= 0) {
      return;
    }

    StackTraceElement[] concatenatedStackTrace = new StackTraceElement[combinedLength + 1];
    System.arraycopy(errorStackTrace, 0, concatenatedStackTrace,
        0, errorStackTrace.length - skipErrorFrames);
    concatenatedStackTrace[errorStackTrace.length - skipErrorFrames] =
        new StackTraceElement("********** Task \"" + getName() + "\" (above) was instantiated as following (below): **********", "",null, 0);
    System.arraycopy(taskStackTrace, skipTaskFrames, concatenatedStackTrace,
        errorStackTrace.length - skipErrorFrames + 1, taskStackTrace.length - skipTaskFrames);
    error.setStackTrace(concatenatedStackTrace);
  }

Concatenate stack traces if kept the original stack trace from the task creation


private void monitor() {
    _lastMonitoringStep = _clock.nanoTime();
    _nextAllowedLogging = _lastMonitoringStep;
    while(!_stopped) {
      try {
        _clock.sleepNano(_checkIntervalNano);
      } catch (InterruptedException e) {
        break;
      }
      monitorStep();
    }
  }

private void monitor ( ) { _lastMonitoringStep = _clock . nanoTime ( ) ; _nextAllowedLogging = _lastMonitoringStep ; while ( ! _stopped ) { try { _clock . sleepNano ( _checkIntervalNano ) ; } catch ( InterruptedException e ) { break ; } monitorStep ( ) ; } }


private void checkForStall(long currentTime) {
    long delta = currentTime - _lastMonitoringStep;
    if (delta < _shortestObservedDelta) {
      _shortestObservedDelta = delta;
    }
    long stall = Math.max(0, delta - _shortestObservedDelta);
    if (stall > _minStallNano) {
      _stalls.put(_lastMonitoringStep, stall);
      if (_stalls.size() > _stallsHistorySize) {
        _stalls.pollFirstEntry();
      }
    }
  }

private void checkForStall ( long currentTime ) { long delta = currentTime - _lastMonitoringStep ; if ( delta < _shortestObservedDelta ) { _shortestObservedDelta = delta ; } long stall = Math . max ( 0 , delta - _shortestObservedDelta ) ; if ( stall > _minStallNano ) { _stalls . put ( _lastMonitoringStep , stall ) ; if ( _stalls . size ( ) > _stallsHistorySize ) { _stalls . pollFirstEntry ( ) ; } } }

Check how much we missed scheduled wake up and if it is larger than _minStallNano
then consider it a stall and remember it.

Check how much we missed scheduled wake up and if it is larger than _minStallNano then consider it a stall and remember it .


public static <U> Task<U> withRetryPolicy(String name, RetryPolicy policy, Function1<Integer, Task<U>> taskFunction) {
    RetriableTask<U> retriableTask = new RetriableTask<>(name, policy, taskFunction);
    Task<U> retryTaskWrapper = Task.async(name + " retriableTask", retriableTask::run);
    retryTaskWrapper.getShallowTraceBuilder().setTaskType(TaskType.WITH_RETRY.getName());
    return retryTaskWrapper;
  }

public
static
<
U
>
Task
<
U
>
withRetryPolicy
(
String
name
,
RetryPolicy
policy
,
Function1
<
Integer
,
Task
<
U
>
>
taskFunction
)
{
RetriableTask
<
U
>
retriableTask
=
new
RetriableTask
<>
(
name
,
policy
,
taskFunction
)
;
Task
<
U
>
retryTaskWrapper
=
Task
.
async
(
name
+
" retriableTask"
,
retriableTask
::
run
)
;
retryTaskWrapper
.
getShallowTraceBuilder
(
)
.
setTaskType
(
TaskType
.
WITH_RETRY
.
getName
(
)
)
;
return
retryTaskWrapper
;
}

A helper for creating task wrapper with associated retry policy.

@param name A name of the task that needs to be retried.
@param policy Retry policy that will control this task's behavior.
@param taskFunction A task generator function. It will receive a zero-based attempt number as a parameter.
@param <U> Type of a task result.

A helper for creating task wrapper with associated retry policy .


private Task<T> wrap(int attempt) {
    Task<T> retryTask = Task.async(_policy.getName() + ", attempt " + attempt, context -> {
      final SettablePromise<T> result = Promises.settable();

      Task<T> task = _taskFunction.apply(attempt);

      final Task<T> recovery = Task.async(_name + " recovery", recoveryContext -> {
        final SettablePromise<T> recoveryResult = Promises.settable();

        if (task.isFailed()) {
          // Failed task will cause retry to be scheduled.
          ErrorClassification errorClassification = _policy.getErrorClassifier().apply(task.getError());
          retry(attempt + 1, task.getError(), errorClassification, recoveryContext, recoveryResult);
        } else {
          recoveryResult.done(task.get());
        }

        return recoveryResult;
      });

      // Recovery task should run immediately after the original task to process its error.
      recovery.setPriority(Priority.MAX_PRIORITY);
      recovery.getShallowTraceBuilder().setSystemHidden(true);
      Promises.propagateResult(recovery, result);
      context.after(task).run(recovery);
      context.run(task);

      return result;
    });
    retryTask.getShallowTraceBuilder().setTaskType(TaskType.RETRY.getName());
    return retryTask;
  }

Create a wrapped task with associated recovery task that will retry if necessary.

Create a wrapped task with associated recovery task that will retry if necessary .


private void retry(int attempt, Throwable error, ErrorClassification errorClassification, Context recoveryContext, SettablePromise<T> recoveryResult) {
    long backoffTime = _policy.getBackoffPolicy().nextBackoff(attempt, error);

    if (errorClassification == ErrorClassification.UNRECOVERABLE) {
      // For fatal errors there are no retries.
      LOGGER.debug(String.format("Attempt %s of %s interrupted: %s", attempt, _name, error.getMessage()));
      recoveryResult.fail(error);
    } else if (_policy.getTerminationPolicy().shouldTerminate(attempt, System.currentTimeMillis() - _startedAt + backoffTime)) {
      // Retry policy commands that no more retries should be done.
      LOGGER.debug(String.format("Too many exceptions after attempt %s of %s, aborting: %s", attempt, _name, error.getMessage()));
      recoveryResult.fail(error);
    } else {
      // Schedule a new retry task after a computed backoff timeout.
      LOGGER.debug(String.format("Attempt %s of %s failed and will be retried after %s millis: %s", attempt, _name, backoffTime, error.getMessage()));
      Task<T> retryTask = wrap(attempt);
      Promises.propagateResult(retryTask, recoveryResult);
      recoveryContext.createTimer(backoffTime, TimeUnit.MILLISECONDS, retryTask);
    }
  }

Invoke event monitors and schedule a retry if policy allows.

Invoke event monitors and schedule a retry if policy allows .


private Promise<? extends T> run(Context context) {
    _startedAt = System.currentTimeMillis();
    Task<T> task = wrap(0);
    context.run(task);
    return task;
  }

private Promise < ? extends T > run ( Context context ) { _startedAt = System . currentTimeMillis ( ) ; Task < T > task = wrap ( 0 ) ; context . run ( task ) ; return task ; }


private static Exception failCoercion(final Object object, final Class<?> targetType)
  {
    return new Exception("Could not convert object to " + targetType.getSimpleName() + ". Object is instance of: "
        + object.getClass().getName() + ", value: " + object.toString());
  }

private
static
Exception
failCoercion
(
final
Object
object
,
final
Class
<
>
targetType
)
{
return
new
Exception
(
"Could not convert object to "
+
targetType
.
getSimpleName
(
)
+
". Object is instance of: "
+
object
.
getClass
(
)
.
getName
(
)
+
", value: "
+
object
.
toString
(
)
)
;
}

Generates a consistent exception that can be used if coercion fails.

Generates a consistent exception that can be used if coercion fails .


@Deprecated
  public ParSeqRestliClientBuilder setRestClient(RestClient client) {
    ArgumentUtil.requireNotNull(client, "client");
    _client = client;
    return this;
  }

@ Deprecated public ParSeqRestliClientBuilder setRestClient ( RestClient client ) { ArgumentUtil . requireNotNull ( client , "client" ) ; _client = client ; return this ; }

Sets the underlying Rest.li client implementation.

@param client The underlying Rest.li client
@deprecated Use #setClient instead
@return The builder itself

Sets the underlying Rest . li client implementation .


private Task<String> acquire(long deadline) {
    final String uuid = UUID.randomUUID().toString();

    return
        /* Step 1: create znode with a pathname of "_locknode_/guid-lock-"
         * and the sequence and ephemeral flags set. */
        safeCreateLockNode(uuid, deadline, false)
            .onFailure(e -> _zkClient.deleteNodeHasUUID(_lockPath, uuid))
            .flatMap(lockNode -> tryAcquire(lockNode, deadline)
                .withTimeout(deadline - System.currentTimeMillis(), TimeUnit.MILLISECONDS)
                .onFailure(e -> _zkClient.deleteNode(lockNode)));
  }

Try to acquire the lock within the given deadline.

Try to acquire the lock within the given deadline .


private Task<Void> release() {
    return PlanLocal.get(getPlanLocalKey(), LockInternal.class).flatMap(lockInternal -> {
      // should never be null.
      if (lockInternal == null) {
        LOG.error("LockInternal is null when releasing lock: ", _lockPath);
      } else {
        lockInternal._lockCount--;
        if (lockInternal._lockCount == 0) {

          return PlanLocal.remove(getPlanLocalKey())
              .flatMap(unused ->
                  _zkClient.delete(lockInternal._lockNode, -1)
                      .recover(e -> {
                        _zkClient.deleteNode(lockInternal._lockNode);
                        return null;
                      })
              );
        }
      }
      return Task.value(null);
    });
  }


private boolean tryAcquirePermit(String planClass) {
    return _concurrentPlans.tryAcquire() &&
        (_planBasedRateLimiter == null || _planBasedRateLimiter.tryAcquire(planClass));
  }

private boolean tryAcquirePermit ( String planClass ) { return _concurrentPlans . tryAcquire ( ) && ( _planBasedRateLimiter == null || _planBasedRateLimiter . tryAcquire ( planClass ) ) ; }

rate limiter and then from plan class level rate limit if specified.

rate limiter and then from plan class level rate limit if specified .


public static synchronized AsyncHttpClient getNingClient() {
    if (_client.get() == null) {
      initialize(new AsyncHttpClientConfig.Builder().build());
    }
    return _client.get();
  }

public static synchronized AsyncHttpClient getNingClient ( ) { if ( _client . get ( ) == null ) { initialize ( new AsyncHttpClientConfig . Builder ( ) . build ( ) ) ; } return _client . get ( ) ; }

Returns raw http client. If client has not been initialized yet
then new client is created with default configuration.
@return raw http client

Returns raw http client . If client has not been initialized yet then new client is created with default configuration .


@SuppressWarnings("resource")
  public static synchronized void initialize(AsyncHttpClientConfig cfg) {
    if (!_client.compareAndSet(null, new AsyncHttpClient(cfg))) {
      throw new RuntimeException("async http client concurrently initialized");
    }
  }

Initializes HttpClient with custom configuration.
@param cfg client configuration
@see AsyncHttpClientConfig

Initializes HttpClient with custom configuration .


public String consumeToAny(final char... chars) {
        bufferUp();
        final int start = bufPos;
        final int remaining = bufLength;
        final char[] val = charBuf;

        OUTER:
        while (bufPos < remaining) {
            for (char c : chars) {
                if (val[bufPos] == c)
                    break OUTER;
            }
            bufPos++;
        }

        return bufPos > start ? cacheString(charBuf, stringCache, start, bufPos - start) : "";
    }

public String consumeToAny ( final char ... chars ) { bufferUp ( ) ; final int start = bufPos ; final int remaining = bufLength ; final char [ ] val = charBuf ; OUTER : while ( bufPos < remaining ) { for ( char c : chars ) { if ( val [ bufPos ] == c ) break OUTER ; } bufPos ++ ; } return bufPos > start ? cacheString ( charBuf , stringCache , start , bufPos - start ) : "" ; }

Read characters until the first of any delimiters is found.

@param chars delimiters to scan for
@return characters read up to the matched delimiter.

Read characters until the first of any delimiters is found .


public static void noNullElements(Object[] objects, String msg) {
        for (Object obj : objects)
            if (obj == null)
                throw new IllegalArgumentException(msg);
    }

public static void noNullElements ( Object [ ] objects , String msg ) { for ( Object obj : objects ) if ( obj == null ) throw new IllegalArgumentException ( msg ) ; }

Validates that the array contains no null elements
@param objects the array to test
@param msg message to output if validation fails


public static void notEmpty(String string, String msg) {
        if (string == null || string.length() == 0)
            throw new IllegalArgumentException(msg);
    }

public static void notEmpty ( String string , String msg ) { if ( string == null || string . length ( ) == 0 ) throw new IllegalArgumentException ( msg ) ; }

Validates that the string is not empty
@param string the string to test
@param msg message to output if validation fails


static Matrix parseTransform(String s) {
        //Log.d(TAG, s);
        Matrix matrix = new Matrix();
        while (true) {
            parseTransformItem(s, matrix);
            int rparen = s.indexOf(")");
            if (rparen > 0 && s.length() > rparen + 1) {
                s = s.substring(rparen + 1).replaceFirst("[\\s,]*", "");
            } else {
                break;
            }
        }
        return matrix;
    }

static
Matrix
parseTransform
(
String
s
)
{
//Log.d(TAG, s);
Matrix
matrix
=
new
Matrix
(
)
;
while
(
true
)
{
parseTransformItem
(
s
,
matrix
)
;
int
rparen
=
s
.
indexOf
(
")"
)
;
if
(
rparen
>
0
&&
s
.
length
(
)
>
rparen
+
1
)
{
s
=
s
.
substring
(
rparen
+
1
)
.
replaceFirst
(
"[\\s,]*"
,
""
)
;
}
else
{
break
;
}
}
return
matrix
;
}


public DBCursor getFileList(final DBObject query, final DBObject sort) {
        return filesCollection.find(query).sort(sort);
    }

public DBCursor getFileList ( final DBObject query , final DBObject sort ) { return filesCollection . find ( query ) . sort ( sort ) ; }

Gets a sorted, filtered list of files stored in this gridfs.

@param query filter to apply
@param sort  sorting to apply
@return cursor of file objects

Gets a sorted filtered list of files stored in this gridfs .


public List<GridFSDBFile> find(final String filename, final DBObject sort) {
        return find(new BasicDBObject("filename", filename), sort);
    }

public List < GridFSDBFile > find ( final String filename , final DBObject sort ) { return find ( new BasicDBObject ( "filename" , filename ) , sort ) ; }

Finds a list of files matching the given filename.

@param filename the filename to look for
@param sort     the fields to sort with
@return list of gridfs files
@throws com.mongodb.MongoException if the operation fails

Finds a list of files matching the given filename .


public List<GridFSDBFile> find(final DBObject query, final DBObject sort) {
        List<GridFSDBFile> files = new ArrayList<GridFSDBFile>();

        DBCursor cursor = filesCollection.find(query);
        if (sort != null) {
            cursor.sort(sort);
        }

        try {
            while (cursor.hasNext()) {
                files.add(injectGridFSInstance(cursor.next()));
            }
        } finally {
            cursor.close();
        }
        return Collections.unmodifiableList(files);
    }

public List < GridFSDBFile > find ( final DBObject query , final DBObject sort ) { List < GridFSDBFile > files = new ArrayList < GridFSDBFile > ( ) ; DBCursor cursor = filesCollection . find ( query ) ; if ( sort != null ) { cursor . sort ( sort ) ; } try { while ( cursor . hasNext ( ) ) { files . add ( injectGridFSInstance ( cursor . next ( ) ) ) ; } } finally { cursor . close ( ) ; } return Collections . unmodifiableList ( files ) ; }

Finds a list of files matching the given query.

@param query the filter to apply
@param sort  the fields to sort with
@return list of gridfs files
@throws com.mongodb.MongoException if the operation fails

Finds a list of files matching the given query .


public void remove(final ObjectId id) {
        if (id == null) {
            throw new IllegalArgumentException("file id can not be null");
        }

        filesCollection.remove(new BasicDBObject("_id", id));
        chunksCollection.remove(new BasicDBObject("files_id", id));
    }

public
void
remove
(
final
ObjectId
id
)
{
if
(
id
==
)
{
throw
new
IllegalArgumentException
(
"file id can not be null"
)
;
}
filesCollection
.
remove
(
new
BasicDBObject
(
"_id"
,
id
)
)
;
chunksCollection
.
remove
(
new
BasicDBObject
(
"files_id"
,
id
)
)
;
}

Removes the file matching the given id.

@param id the id of the file to be removed
@throws com.mongodb.MongoException if the operation fails

Removes the file matching the given id .


public void remove(final DBObject query) {
        if (query == null) {
            throw new IllegalArgumentException("query can not be null");
        }

        for (final GridFSDBFile f : find(query)) {
            f.remove();
        }
    }

public
void
remove
(
final
DBObject
query
)
{
if
(
query
==
)
{
throw
new
IllegalArgumentException
(
"query can not be null"
)
;
}
for
(
final
GridFSDBFile
f
:
find
(
query
)
)
{
f
.
remove
(
)
;
}
}

Removes all files matching the given query.

@param query filter to apply
@throws com.mongodb.MongoException if the operation fails

Removes all files matching the given query .


@Override
    public Object put(final String key, final Object v) {
        return put(_getInt(key), v);
    }

@ Override public Object put ( final String key , final Object v ) { return put ( _getInt ( key ) , v ) ; }

Puts a value at an index. For interface compatibility.  Must be passed a String that is parsable to an int.

@param key the index at which to insert the value
@param v   the value to insert
@return the value
@throws IllegalArgumentException if {@code key} cannot be parsed into an {@code int}

Puts a value at an index . For interface compatibility . Must be passed a String that is parsable to an int .


public Object get(final String key) {
        int i = _getInt(key);
        if (i < 0) {
            return null;
        }
        if (i >= size()) {
            return null;
        }
        return get(i);
    }

public Object get ( final String key ) { int i = _getInt ( key ) ; if ( i < 0 ) { return null ; } if ( i >= size ( ) ) { return null ; } return get ( i ) ; }

Gets a value at an index. For interface compatibility.  Must be passed a String that is parsable to an int.

@param key the index
@return the value, if found, or null
@throws IllegalArgumentException if {@code key} cannot be parsed into an {@code int}

Gets a value at an index . For interface compatibility . Must be passed a String that is parsable to an int .


public static <T> Builder<T> builder(final Class<T> type) {
        return new Builder<T>(notNull("type", type));
    }

public static < T > Builder < T > builder ( final Class < T > type ) { return new Builder < T > ( notNull ( "type" , type ) ) ; }

Creates a new builder for ClassTypeData

@param type the class for the type
@param <T> the type
@return the builder


public long getMaxTime(final TimeUnit timeUnit) {
        notNull("timeUnit", timeUnit);
        return timeUnit.convert(maxTimeMS, TimeUnit.MILLISECONDS);
    }

public long getMaxTime ( final TimeUnit timeUnit ) { notNull ( "timeUnit" , timeUnit ) ; return timeUnit . convert ( maxTimeMS , TimeUnit . MILLISECONDS ) ; }

Gets the maximum execution time on the server for this operation.  The default is 0, which places no limit on the execution time.

@param timeUnit the time unit to return the result in
@return the maximum execution time in the given time unit
@mongodb.driver.manual reference/operator/meta/maxTimeMS/ Max Time

Gets the maximum execution time on the server for this operation . The default is 0 which places no limit on the execution time .


public <T> MongoCompressor withProperty(final String key, final T value) {
        return new MongoCompressor(this, key, value);
    }

public < T > MongoCompressor withProperty ( final String key , final T value ) { return new MongoCompressor ( this , key , value ) ; }

Creates a new compressor from this compressor with the given property added to it.

@param key the property key
@param value the property value
@param <T> the property value type
@return the new compressor

Creates a new compressor from this compressor with the given property added to it .


@SuppressWarnings("deprecation")
    @Nullable
    public String getName() {
        List<ServerDescription> any = getClusterDescription().getAnyPrimaryOrSecondary();
        return any.isEmpty() ? null : any.get(0).getSetName();
    }

@ SuppressWarnings ( "deprecation" ) @ Nullable public String getName ( ) { List < ServerDescription > any = getClusterDescription ( ) . getAnyPrimaryOrSecondary ( ) ; return any . isEmpty ( ) ? null : any . get ( 0 ) . getSetName ( ) ; }

Get the name of the replica set.

@return the name of the replica set.


@SuppressWarnings("deprecation")
    @Nullable
    public ServerAddress getMaster() {
        List<ServerDescription> primaries = getClusterDescription().getPrimaries();
        return primaries.isEmpty() ? null : primaries.get(0).getAddress();
    }

@ SuppressWarnings ( "deprecation" ) @ Nullable public ServerAddress getMaster ( ) { List < ServerDescription > primaries = getClusterDescription ( ) . getPrimaries ( ) ; return primaries . isEmpty ( ) ? null : primaries . get ( 0 ) . getAddress ( ) ; }

Gets the ServerAddress of the master server in this replica set.

@return master or null if don't have one
@throws MongoException if there's a failure

Gets the ServerAddress of the master server in this replica set .


public boolean isMaster(final ServerAddress serverAddress) {
        ServerAddress masterServerAddress = getMaster();
        return masterServerAddress != null && masterServerAddress.equals(serverAddress);
    }

public boolean isMaster ( final ServerAddress serverAddress ) { ServerAddress masterServerAddress = getMaster ( ) ; return masterServerAddress != null && masterServerAddress . equals ( serverAddress ) ; }

Checks to see if a given server is the primary server in this replica set.

@param serverAddress the server to compare
@return true if the given ServerAddress is the current Master/Primary

Checks to see if a given server is the primary server in this replica set .


@SuppressWarnings("deprecation")
    public int getMaxBsonObjectSize() {
        List<ServerDescription> primaries = getClusterDescription().getPrimaries();
        return primaries.isEmpty() ? ServerDescription.getDefaultMaxDocumentSize() : primaries.get(0).getMaxDocumentSize();
    }

@ SuppressWarnings ( "deprecation" ) public int getMaxBsonObjectSize ( ) { List < ServerDescription > primaries = getClusterDescription ( ) . getPrimaries ( ) ; return primaries . isEmpty ( ) ? ServerDescription . getDefaultMaxDocumentSize ( ) : primaries . get ( 0 ) . getMaxDocumentSize ( ) ; }

Gets the maximum size for a BSON object supported by the current master server. Note that this value may change over time depending
on which server is master.

@return the maximum size, or 0 if not obtained from servers yet.
@throws MongoException if there's a failure

Gets the maximum size for a BSON object supported by the current master server . Note that this value may change over time depending on which server is master .


public QueryBuilder put(final String key) {
        _currentKey = key;
        if (_query.get(key) == null) {
            _query.put(_currentKey, new NullObject());
        }
        return this;
    }

public QueryBuilder put ( final String key ) { _currentKey = key ; if ( _query . get ( key ) == null ) { _query . put ( _currentKey , new NullObject ( ) ) ; } return this ; }

Adds a new key to the query if not present yet. Sets this key as the current key.

@param key MongoDB document key
@return {@code this}

Adds a new key to the query if not present yet . Sets this key as the current key .


private void applyMajorityWriteConcernToTransactionOptions() {
        if (transactionOptions != null) {
            WriteConcern writeConcern = transactionOptions.getWriteConcern();
            if (writeConcern != null) {
                transactionOptions = TransactionOptions.merge(TransactionOptions.builder()
                        .writeConcern(writeConcern.withW("majority")).build(), transactionOptions);
            } else {
                transactionOptions = TransactionOptions.merge(TransactionOptions.builder()
                        .writeConcern(WriteConcern.MAJORITY).build(), transactionOptions);
            }
        } else {
            transactionOptions = TransactionOptions.builder().writeConcern(WriteConcern.MAJORITY).build();
        }
    }

Apply majority write concern if the commit is to be retried.

Apply majority write concern if the commit is to be retried .


public boolean ok() {
        Object okValue = get("ok");
        if (okValue instanceof Boolean) {
            return (Boolean) okValue;
        } else if (okValue instanceof Number) {
            return ((Number) okValue).intValue() == 1;
        } else {
            return false;
        }
    }

public boolean ok ( ) { Object okValue = get ( "ok" ) ; if ( okValue instanceof Boolean ) { return ( Boolean ) okValue ; } else if ( okValue instanceof Number ) { return ( ( Number ) okValue ) . intValue ( ) == 1 ; } else { return false ; } }

Gets the "ok" field, which is whether this command executed correctly or not.

@return true if the command executed without error.

Gets the ok field which is whether this command executed correctly or not .


@Nullable
    public String getErrorMessage() {
        Object foo = get("errmsg");
        if (foo == null) {
            return null;
        }
        return foo.toString();
    }

@ Nullable public String getErrorMessage ( ) { Object foo = get ( "errmsg" ) ; if ( foo == null ) { return null ; } return foo . toString ( ) ; }

Gets the error message associated with a failed command.

@return The error message or null

Gets the error message associated with a failed command .


public PropertyModelBuilder<T> readAnnotations(final List<Annotation> annotations) {
        this.readAnnotations = unmodifiableList(notNull("annotations", annotations));
        return this;
    }

public PropertyModelBuilder < T > readAnnotations ( final List < Annotation > annotations ) { this . readAnnotations = unmodifiableList ( notNull ( "annotations" , annotations ) ) ; return this ; }

Sets the read annotations, to be applied when serializing to BSON

@param annotations the read annotations
@return this

Sets the read annotations to be applied when serializing to BSON


public static List<String> getIndexNames(final List<IndexModel> indexes, final CodecRegistry codecRegistry) {
        List<String> indexNames = new ArrayList<String>(indexes.size());
        for (IndexModel index : indexes) {
            String name = index.getOptions().getName();
            if (name != null) {
                indexNames.add(name);
            } else {
                indexNames.add(IndexHelper.generateIndexName(index.getKeys().toBsonDocument(BsonDocument.class, codecRegistry)));
            }
        }
        return indexNames;
    }

public static List < String > getIndexNames ( final List < IndexModel > indexes , final CodecRegistry codecRegistry ) { List < String > indexNames = new ArrayList < String > ( indexes . size ( ) ) ; for ( IndexModel index : indexes ) { String name = index . getOptions ( ) . getName ( ) ; if ( name != null ) { indexNames . add ( name ) ; } else { indexNames . add ( IndexHelper . generateIndexName ( index . getKeys ( ) . toBsonDocument ( BsonDocument . class , codecRegistry ) ) ) ; } } return indexNames ; }

Get a list of index names for the given list of index models

@param indexes the index models
@param codecRegistry the codec registry to convert each Bson key to a BsonDocument
@return the list of index names


public static String generateIndexName(final BsonDocument index) {
        StringBuilder indexName = new StringBuilder();
        for (final String keyNames : index.keySet()) {
            if (indexName.length() != 0) {
                indexName.append('_');
            }
            indexName.append(keyNames).append('_');
            BsonValue ascOrDescValue = index.get(keyNames);
            if (ascOrDescValue instanceof BsonNumber) {
                indexName.append(((BsonNumber) ascOrDescValue).intValue());
            } else if (ascOrDescValue instanceof BsonString) {
                indexName.append(((BsonString) ascOrDescValue).getValue().replace(' ', '_'));
            }
        }
        return indexName.toString();
    }

public static String generateIndexName ( final BsonDocument index ) { StringBuilder indexName = new StringBuilder ( ) ; for ( final String keyNames : index . keySet ( ) ) { if ( indexName . length ( ) != 0 ) { indexName . append ( ' ' ) ; } indexName . append ( keyNames ) . append ( ' ' ) ; BsonValue ascOrDescValue = index . get ( keyNames ) ; if ( ascOrDescValue instanceof BsonNumber ) { indexName . append ( ( ( BsonNumber ) ascOrDescValue ) . intValue ( ) ) ; } else if ( ascOrDescValue instanceof BsonString ) { indexName . append ( ( ( BsonString ) ascOrDescValue ) . getValue ( ) . replace ( ' ' , ' ' ) ) ; } } return indexName . toString ( ) ; }

Convenience method to generate an index name from the set of fields it is over.

@return a string representation of this index's fields

Convenience method to generate an index name from the set of fields it is over .


@Deprecated
    public void validate() {
        if (fs == null) {
            throw new MongoException("no fs");
        }
        if (md5 == null) {
            throw new MongoException("no md5 stored");
        }

        DBObject cmd = new BasicDBObject("filemd5", id);
        cmd.put("root", fs.getBucketName());
        DBObject res = fs.getDB().command(cmd);
        if (res != null && res.containsField("md5")) {
            String m = res.get("md5").toString();
            if (m.equals(md5)) {
                return;
            }
            throw new MongoException("md5 differ.  mine [" + md5 + "] theirs [" + m + "]");
        }

        // no md5 from the server
        throw new MongoException("no md5 returned from server: " + res);

    }

@
Deprecated
public
void
validate
(
)
{
if
(
fs
==
)
{
throw
new
MongoException
(
"no fs"
)
;
}
if
(
md5
==
)
{
throw
new
MongoException
(
"no md5 stored"
)
;
}
DBObject
cmd
=
new
BasicDBObject
(
"filemd5"
,
id
)
;
cmd
.
put
(
"root"
,
fs
.
getBucketName
(
)
)
;
DBObject
res
=
fs
.
getDB
(
)
.
command
(
cmd
)
;
if
(
res
!=
&&
res
.
containsField
(
"md5"
)
)
{
String
m
=
res
.
get
(
"md5"
)
.
toString
(
)
;
if
(
m
.
equals
(
md5
)
)
{
return
;
}
throw
new
MongoException
(
"md5 differ.  mine ["
+
md5
+
"] theirs ["
+
m
+
"]"
)
;
}
// no md5 from the server
throw
new
MongoException
(
"no md5 returned from server: "
+
res
)
;
}

Verifies that the MD5 matches between the database and the local file. This should be called after transferring a file.

@throws MongoException if there's a failure
@deprecated there is no replacement for this method

Verifies that the MD5 matches between the database and the local file . This should be called after transferring a file .


public Codec<?> get(final BsonType bsonType) {
        Codec<?> codec = codecs[bsonType.getValue()];
        if (codec == null) {
            Class<?> clazz = bsonTypeClassMap.get(bsonType);
            if (clazz == null) {
                throw new CodecConfigurationException(format("No class mapped for BSON type %s.", bsonType));
            } else {
                throw new CodecConfigurationException(format("Can't find a codec for %s.", clazz));
            }
        }
        return codec;
    }

public
Codec
<
>
get
(
final
BsonType
bsonType
)
{
Codec
<
>
codec
=
codecs
[
bsonType
.
getValue
(
)
]
;
if
(
codec
==
)
{
Class
<
>
clazz
=
bsonTypeClassMap
.
get
(
bsonType
)
;
if
(
clazz
==
)
{
throw
new
CodecConfigurationException
(
format
(
"No class mapped for BSON type %s."
,
bsonType
)
)
;
}
else
{
throw
new
CodecConfigurationException
(
format
(
"Can't find a codec for %s."
,
clazz
)
)
;
}
}
return
codec
;
}

Gets the Codec mapped to the given bson type.

@param bsonType the non-null BsonType
@return the non-null Codec

Gets the Codec mapped to the given bson type .


private int calculateBatchSize() {
        Integer batchSize = mongoIterable.getBatchSize();
        if (batchSize != null) {
            return batchSize;
        }
        long requested = getRequested();
        if (requested <= 1) {
            return 2;
        } else if (requested < Integer.MAX_VALUE) {
            return (int) requested;
        } else {
            return Integer.MAX_VALUE;
        }
    }

private int calculateBatchSize ( ) { Integer batchSize = mongoIterable . getBatchSize ( ) ; if ( batchSize != null ) { return batchSize ; } long requested = getRequested ( ) ; if ( requested <= 1 ) { return 2 ; } else if ( requested < Integer . MAX_VALUE ) { return ( int ) requested ; } else { return Integer . MAX_VALUE ; } }

Returns the batchSize to be used with the cursor.

If the batch size has been set on the MongoIterable that is used, otherwise the requested demand is used. When using requested
demand, values less than 2 would close the cursor so that is the minimum batchSize and `Integer.MAX_VALUE` is the maximum.

@return the batchSize to use

Returns the batchSize to be used with the cursor .


public static long parse(final String string) {
        if (string.length() == 0) {
            throw new NumberFormatException("empty string");
        }
        int radix = 10;
        int maxSafePos = MAX_SAFE_DIGITS[radix] - 1;
        long value = 0;
        for (int pos = 0; pos < string.length(); pos++) {
            int digit = Character.digit(string.charAt(pos), radix);
            if (digit == -1) {
                throw new NumberFormatException(string);
            }
            if (pos > maxSafePos && overflowInParse(value, digit, radix)) {
                throw new NumberFormatException("Too large for unsigned long: " + string);
            }
            value = (value * radix) + digit;
        }

        return value;
    }

public
static
long
parse
(
final
String
string
)
{
if
(
string
.
length
(
)
==
0
)
{
throw
new
NumberFormatException
(
"empty string"
)
;
}
int
radix
=
10
;
int
maxSafePos
=
MAX_SAFE_DIGITS
[
radix
]
1
;
long
value
=
0
;
for
(
int
pos
=
0
;
pos
<
string
.
length
(
)
;
pos
++
)
{
int
digit
=
Character
.
digit
(
string
.
charAt
(
pos
)
,
radix
)
;
if
(
digit
==
1
)
{
throw
new
NumberFormatException
(
string
)
;
}
if
(
pos
>
maxSafePos
&&
overflowInParse
(
value
,
digit
,
radix
)
)
{
throw
new
NumberFormatException
(
"Too large for unsigned long: "
+
string
)
;
}
value
=
(
value
*
radix
)
+
digit
;
}
return
value
;
}

Equivalent to Long.parseUnsignedLong in Java 8.

@param string the string representation of an unsigned long
@return the unsigned long

Equivalent to Long . parseUnsignedLong in Java 8 .


public <T> T decodeWithChildContext(final Decoder<T> decoder, final BsonReader reader) {
        return decoder.decode(reader, DEFAULT_CONTEXT);
    }

public < T > T decodeWithChildContext ( final Decoder < T > decoder , final BsonReader reader ) { return decoder . decode ( reader , DEFAULT_CONTEXT ) ; }

Creates a child context and then deserializes using the reader.

@param decoder the decoder to decode with
@param reader the reader to decode to
@param <T> the type of the decoder
@return the decoded value
@since 3.5

Creates a child context and then deserializes using the reader .


protected boolean checkState(final State[] validStates) {
        for (final State cur : validStates) {
            if (cur == getState()) {
                return true;
            }
        }
        return false;
    }

protected boolean checkState ( final State [ ] validStates ) { for ( final State cur : validStates ) { if ( cur == getState ( ) ) { return true ; } } return false ; }

Checks if this writer's current state is in the list of given states.

@param validStates an array of {@code State}s to compare this writer's state to.
@return true if this writer's state is in the given list.

Checks if this writer s current state is in the list of given states .


public void pipe(final BsonReader reader, final List<BsonElement> extraElements) {
        notNull("reader", reader);
        notNull("extraElements", extraElements);
        pipeDocument(reader, extraElements);
    }

public void pipe ( final BsonReader reader , final List < BsonElement > extraElements ) { notNull ( "reader" , reader ) ; notNull ( "extraElements" , extraElements ) ; pipeDocument ( reader , extraElements ) ; }

Reads a single document from the given BsonReader and writes it to this, appending the given extra elements to the document.

@param reader the source of the document
@param extraElements the extra elements to append to the document
@since 3.6

Reads a single document from the given BsonReader and writes it to this appending the given extra elements to the document .


protected void pipeExtraElements(final List<BsonElement> extraElements) {
        notNull("extraElements", extraElements);
        for (BsonElement cur : extraElements) {
            writeName(cur.getName());
            pipeValue(cur.getValue());
        }
    }

protected void pipeExtraElements ( final List < BsonElement > extraElements ) { notNull ( "extraElements" , extraElements ) ; for ( BsonElement cur : extraElements ) { writeName ( cur . getName ( ) ) ; pipeValue ( cur . getValue ( ) ) ; } }

Pipe a list of extra element to this writer

@param extraElements the extra elements


public byte[] toByteArray() {
        ByteBuffer buffer = ByteBuffer.allocate(OBJECT_ID_LENGTH);
        putToByteBuffer(buffer);
        return buffer.array();  // using .allocate ensures there is a backing array that can be returned
    }

Convert to a byte array.  Note that the numbers are stored in big-endian order.

@return the byte array

Convert to a byte array . Note that the numbers are stored in big - endian order .


public void putToByteBuffer(final ByteBuffer buffer) {
        notNull("buffer", buffer);
        isTrueArgument("buffer.remaining() >=12", buffer.remaining() >= OBJECT_ID_LENGTH);

        buffer.put(int3(timestamp));
        buffer.put(int2(timestamp));
        buffer.put(int1(timestamp));
        buffer.put(int0(timestamp));
        buffer.put(int2(randomValue1));
        buffer.put(int1(randomValue1));
        buffer.put(int0(randomValue1));
        buffer.put(short1(randomValue2));
        buffer.put(short0(randomValue2));
        buffer.put(int2(counter));
        buffer.put(int1(counter));
        buffer.put(int0(counter));
    }

public
void
putToByteBuffer
(
final
ByteBuffer
buffer
)
{
notNull
(
"buffer"
,
buffer
)
;
isTrueArgument
(
"buffer.remaining() >=12"
,
buffer
.
remaining
(
)
>=
OBJECT_ID_LENGTH
)
;
buffer
.
put
(
int3
(
timestamp
)
)
;
buffer
.
put
(
int2
(
timestamp
)
)
;
buffer
.
put
(
int1
(
timestamp
)
)
;
buffer
.
put
(
int0
(
timestamp
)
)
;
buffer
.
put
(
int2
(
randomValue1
)
)
;
buffer
.
put
(
int1
(
randomValue1
)
)
;
buffer
.
put
(
int0
(
randomValue1
)
)
;
buffer
.
put
(
short1
(
randomValue2
)
)
;
buffer
.
put
(
short0
(
randomValue2
)
)
;
buffer
.
put
(
int2
(
counter
)
)
;
buffer
.
put
(
int1
(
counter
)
)
;
buffer
.
put
(
int0
(
counter
)
)
;
}

Convert to bytes and put those bytes to the provided ByteBuffer.
Note that the numbers are stored in big-endian order.

@param buffer the ByteBuffer
@throws IllegalArgumentException if the buffer is null or does not have at least 12 bytes remaining
@since 3.4

Convert to bytes and put those bytes to the provided ByteBuffer . Note that the numbers are stored in big - endian order .


public String toHexString() {
        char[] chars = new char[OBJECT_ID_LENGTH * 2];
        int i = 0;
        for (byte b : toByteArray()) {
            chars[i++] = HEX_CHARS[b >> 4 & 0xF];
            chars[i++] = HEX_CHARS[b & 0xF];
        }
        return new String(chars);
    }

public String toHexString ( ) { char [ ] chars = new char [ OBJECT_ID_LENGTH * 2 ] ; int i = 0 ; for ( byte b : toByteArray ( ) ) { chars [ i ++ ] = HEX_CHARS [ b >> 4 & 0xF ] ; chars [ i ++ ] = HEX_CHARS [ b & 0xF ] ; } return new String ( chars ) ; }

Converts this instance into a 24-byte hexadecimal string representation.

@return a string representation of the ObjectId in hexadecimal format

Converts this instance into a 24 - byte hexadecimal string representation .


public String getShortDescription() {
        return "{"
               + "address=" + address
               + ", type=" + type
               + (!tagSet.iterator().hasNext() ? "" : ", " + tagSet)
               + (state == CONNECTED ? (", roundTripTime=" + getRoundTripFormattedInMilliseconds() + " ms") : "")
               + ", state=" + state
               + (exception == null ? "" : ", exception=" + translateExceptionToString())
               + '}';
    }

public
String
getShortDescription
(
)
{
return
"{"
+
"address="
+
address
+
", type="
+
type
+
(
!
tagSet
.
iterator
(
)
.
hasNext
(
)
""
:
", "
+
tagSet
)
+
(
state
==
CONNECTED
(
", roundTripTime="
+
getRoundTripFormattedInMilliseconds
(
)
+
" ms"
)
:
""
)
+
", state="
+
state
+
(
exception
==
""
:
", exception="
+
translateExceptionToString
(
)
)
+
'
'
;
}

Returns a short, pretty description for this ServerDescription.

@return a String containing the most pertinent information about this ServerDescription

Returns a short pretty description for this ServerDescription .


@SuppressWarnings("unchecked")
    public static BasicDBObjectBuilder start(final Map documentAsMap) {
        BasicDBObjectBuilder builder = new BasicDBObjectBuilder();
        Iterator<Map.Entry> i = documentAsMap.entrySet().iterator();
        while (i.hasNext()) {
            Map.Entry entry = i.next();
            builder.add(entry.getKey().toString(), entry.getValue());
        }
        return builder;
    }

@ SuppressWarnings ( "unchecked" ) public static BasicDBObjectBuilder start ( final Map documentAsMap ) { BasicDBObjectBuilder builder = new BasicDBObjectBuilder ( ) ; Iterator < Map . Entry > i = documentAsMap . entrySet ( ) . iterator ( ) ; while ( i . hasNext ( ) ) { Map . Entry entry = i . next ( ) ; builder . add ( entry . getKey ( ) . toString ( ) , entry . getValue ( ) ) ; } return builder ; }

Creates an object builder from an existing map of key value pairs.

@param documentAsMap a document in Map form.
@return the new builder

Creates an object builder from an existing map of key value pairs .


public BasicDBObjectBuilder push(final String key) {
        BasicDBObject o = new BasicDBObject();
        _cur().put(key, o);
        _stack.addLast(o);
        return this;
    }

public BasicDBObjectBuilder push ( final String key ) { BasicDBObject o = new BasicDBObject ( ) ; _cur ( ) . put ( key , o ) ; _stack . addLast ( o ) ; return this ; }

Creates an new empty object and inserts it into the current object with the given key. The new child object becomes the active one.

@param key the field name
@return {@code this} so calls can be chained

Creates an new empty object and inserts it into the current object with the given key . The new child object becomes the active one .


public void addResult(final BulkWriteResult result, final IndexMap indexMap) {
        insertedCount += result.getInsertedCount();
        matchedCount += result.getMatchedCount();
        deletedCount += result.getDeletedCount();
        modifiedCount += result.getModifiedCount();
        mergeUpserts(result.getUpserts(), indexMap);
    }

public void addResult ( final BulkWriteResult result , final IndexMap indexMap ) { insertedCount += result . getInsertedCount ( ) ; matchedCount += result . getMatchedCount ( ) ; deletedCount += result . getDeletedCount ( ) ; modifiedCount += result . getModifiedCount ( ) ; mergeUpserts ( result . getUpserts ( ) , indexMap ) ; }

Add a result

@param result   the result
@param indexMap the index map


public void addErrorResult(final MongoBulkWriteException exception, final IndexMap indexMap) {
        addResult(exception.getWriteResult(), indexMap);
        mergeWriteErrors(exception.getWriteErrors(), indexMap);
        mergeWriteConcernError(exception.getWriteConcernError());
    }

public void addErrorResult ( final MongoBulkWriteException exception , final IndexMap indexMap ) { addResult ( exception . getWriteResult ( ) , indexMap ) ; mergeWriteErrors ( exception . getWriteErrors ( ) , indexMap ) ; mergeWriteConcernError ( exception . getWriteConcernError ( ) ) ; }

Add an error result

@param exception the exception
@param indexMap  the index map


public void addWriteErrorResult(final BulkWriteError writeError, final IndexMap indexMap) {
        notNull("writeError", writeError);
        mergeWriteErrors(asList(writeError), indexMap);
    }

public void addWriteErrorResult ( final BulkWriteError writeError , final IndexMap indexMap ) { notNull ( "writeError" , writeError ) ; mergeWriteErrors ( asList ( writeError ) , indexMap ) ; }

Add a write error result

@param writeError the write error
@param indexMap   the index map


public void addErrorResult(final List<BulkWriteError> writeErrors,
                               final WriteConcernError writeConcernError, final IndexMap indexMap) {
        mergeWriteErrors(writeErrors, indexMap);
        mergeWriteConcernError(writeConcernError);
    }

public void addErrorResult ( final List < BulkWriteError > writeErrors , final WriteConcernError writeConcernError , final IndexMap indexMap ) { mergeWriteErrors ( writeErrors , indexMap ) ; mergeWriteConcernError ( writeConcernError ) ; }

Add a list of error results and a write concern error

@param writeErrors       the errors
@param writeConcernError the write concern error
@param indexMap          the index map


public MongoBulkWriteException getError() {
        return hasErrors() ? new MongoBulkWriteException(createResult(),
                                                    new ArrayList<BulkWriteError>(writeErrors),
                                                    writeConcernErrors.isEmpty() ? null
                                                                                : writeConcernErrors.get(writeConcernErrors.size() - 1),
                                                    serverAddress) : null;
    }

public MongoBulkWriteException getError ( ) { return hasErrors ( ) ? new MongoBulkWriteException ( createResult ( ) , new ArrayList < BulkWriteError > ( writeErrors ) , writeConcernErrors . isEmpty ( ) ? null : writeConcernErrors . get ( writeConcernErrors . size ( ) - 1 ) , serverAddress ) : null ; }

Gets the combined errors as an exception
@return the bulk write exception, or null if there were no errors


private boolean casNext(Node<E> cmp, Node<E> val) {
            return compareAndSet(cmp, val);
        }

private boolean casNext ( Node < E > cmp , Node < E > val ) { return compareAndSet ( cmp , val ) ; }


private Node<E> nextNonmarker() {
            Node<E> f = getNext();
            return (f == null || !f.isMarker()) ? f : f.getNext();
        }

private Node < E > nextNonmarker ( ) { Node < E > f = getNext ( ) ; return ( f == null || ! f . isMarker ( ) ) ? f : f . getNext ( ) ; }

Returns next node, ignoring deletion marker.

Returns next node ignoring deletion marker .


Node<E> successor() {
            Node<E> f = nextNonmarker();
            for (;;) {
                if (f == null)
                    return null;
                if (!f.isDeleted()) {
                    if (f.getPrev() != this && !isDeleted())
                        f.setPrev(this);       // relink f's prev
                    return f;
                }
                Node<E> s = f.nextNonmarker();
                if (f == getNext())
                    casNext(f, s);             // unlink f
                f = s;
            }
        }

Node
<
E
>
successor
(
)
{
Node
<
E
>
f
=
nextNonmarker
(
)
;
for
(
;
;
)
{
if
(
f
==
)
return
;
if
(
!
f
.
isDeleted
(
)
)
{
if
(
f
.
getPrev
(
)
!=
this
&&
!
isDeleted
(
)
)
f
.
setPrev
(
this
)
;
// relink f's prev
return
f
;
}
Node
<
E
>
s
=
f
.
nextNonmarker
(
)
;
if
(
f
==
getNext
(
)
)
casNext
(
f
,
s
)
;
// unlink f
f
=
s
;
}
}

Returns the next non-deleted node, swinging next pointer
around any encountered deleted nodes, and also patching up
successor's prev link to point back to this.  Returns
null if this node is trailer so has no successor.

@return successor, or null if no such

Returns the next non - deleted node swinging next pointer around any encountered deleted nodes and also patching up successor s prev link to point back to this . Returns null if this node is trailer so has no successor .


Node<E> predecessor() {
            Node<E> n = this;
            for (;;) {
                Node<E> b = n.getPrev();
                if (b == null)
                    return n.findPredecessorOf(this);
                Node<E> s = b.getNext();
                if (s == this)
                    return b;
                if (s == null || !s.isMarker()) {
                    Node<E> p = b.findPredecessorOf(this);
                    if (p != null)
                        return p;
                }
                n = b;
            }
        }

Node < E > predecessor ( ) { Node < E > n = this ; for ( ; ; ) { Node < E > b = n . getPrev ( ) ; if ( b == null ) return n . findPredecessorOf ( this ) ; Node < E > s = b . getNext ( ) ; if ( s == this ) return b ; if ( s == null || ! s . isMarker ( ) ) { Node < E > p = b . findPredecessorOf ( this ) ; if ( p != null ) return p ; } n = b ; } }

Returns the previous non-deleted node, patching up pointers
as needed.  Returns null if this node is header so has no
successor.  May also return null if this node is deleted,
so doesn't have a distinct predecessor.

@return predecessor, or null if not found

Returns the previous non - deleted node patching up pointers as needed . Returns null if this node is header so has no successor . May also return null if this node is deleted so doesn t have a distinct predecessor .


Node<E> forward() {
            Node<E> f = successor();
            return (f == null || f.isSpecial()) ? null : f;
        }

Node < E > forward ( ) { Node < E > f = successor ( ) ; return ( f == null || f . isSpecial ( ) ) ? null : f ; }

Returns the next node containing a nondeleted user element.
Use for forward list traversal.

@return successor, or null if no such

Returns the next node containing a nondeleted user element . Use for forward list traversal .


Node<E> back() {
            Node<E> f = predecessor();
            return (f == null || f.isSpecial()) ? null : f;
        }

Node < E > back ( ) { Node < E > f = predecessor ( ) ; return ( f == null || f . isSpecial ( ) ) ? null : f ; }

Returns previous node containing a nondeleted user element, if
possible.  Use for backward list traversal, but beware that
if this method is called from a deleted node, it might not
be able to determine a usable predecessor.

@return predecessor, or null if no such could be found

Returns previous node containing a nondeleted user element if possible . Use for backward list traversal but beware that if this method is called from a deleted node it might not be able to determine a usable predecessor .


Node<E> append(E element) {
            for (;;) {
                Node<E> f = getNext();
                if (f == null || f.isMarker())
                    return null;
                Node<E> x = new Node<E>(element, f, this);
                if (casNext(f, x)) {
                    f.setPrev(x); // optimistically link
                    return x;
                }
            }
        }

Node
<
E
>
append
(
E
element
)
{
for
(
;
;
)
{
Node
<
E
>
f
=
getNext
(
)
;
if
(
f
==
||
f
.
isMarker
(
)
)
return
;
Node
<
E
>
x
=
new
Node
<
E
>
(
element
,
f
,
this
)
;
if
(
casNext
(
f
,
x
)
)
{
f
.
setPrev
(
x
)
;
// optimistically link
return
x
;
}
}
}

Tries to insert a node holding element as successor, failing
if this node is deleted.

@param element the element
@return the new node, or null on failure

Tries to insert a node holding element as successor failing if this node is deleted .


Node<E> prepend(E element) {
            for (;;) {
                Node<E> b = predecessor();
                if (b == null)
                    return null;
                Node<E> x = new Node<E>(element, this, b);
                if (b.casNext(this, x)) {
                    setPrev(x); // optimistically link
                    return x;
                }
            }
        }

Node
<
E
>
prepend
(
E
element
)
{
for
(
;
;
)
{
Node
<
E
>
b
=
predecessor
(
)
;
if
(
b
==
)
return
;
Node
<
E
>
x
=
new
Node
<
E
>
(
element
,
this
,
b
)
;
if
(
b
.
casNext
(
this
,
x
)
)
{
setPrev
(
x
)
;
// optimistically link
return
x
;
}
}
}

Tries to insert a node holding element as predecessor, failing
if no live predecessor can be found to link to.

@param element the element
@return the new node, or null on failure

Tries to insert a node holding element as predecessor failing if no live predecessor can be found to link to .


boolean delete() {
            Node<E> b = getPrev();
            Node<E> f = getNext();
            if (b != null && f != null && !f.isMarker() &&
                casNext(f, new Node<E>(f))) {
                if (b.casNext(this, f))
                    f.setPrev(b);
                return true;
            }
            return false;
        }

boolean delete ( ) { Node < E > b = getPrev ( ) ; Node < E > f = getNext ( ) ; if ( b != null && f != null && ! f . isMarker ( ) && casNext ( f , new Node < E > ( f ) ) ) { if ( b . casNext ( this , f ) ) f . setPrev ( b ) ; return true ; } return false ; }

Tries to mark this node as deleted, failing if already
deleted or if this node is header or trailer.

@return true if successful

Tries to mark this node as deleted failing if already deleted or if this node is header or trailer .


Node<E> replace(E newElement) {
            for (;;) {
                Node<E> b = getPrev();
                Node<E> f = getNext();
                if (b == null || f == null || f.isMarker())
                    return null;
                Node<E> x = new Node<E>(newElement, f, b);
                if (casNext(f, new Node<E>(x))) {
                    b.successor(); // to relink b
                    x.successor(); // to relink f
                    return x;
                }
            }
        }

Node
<
E
>
replace
(
E
newElement
)
{
for
(
;
;
)
{
Node
<
E
>
b
=
getPrev
(
)
;
Node
<
E
>
f
=
getNext
(
)
;
if
(
b
==
||
f
==
||
f
.
isMarker
(
)
)
return
;
Node
<
E
>
x
=
new
Node
<
E
>
(
newElement
,
f
,
b
)
;
if
(
casNext
(
f
,
new
Node
<
E
>
(
x
)
)
)
{
b
.
successor
(
)
;
// to relink b
x
.
successor
(
)
;
// to relink f
return
x
;
}
}
}

Tries to insert a node holding element to replace this node.
failing if already deleted.  A currently unused proof of
concept that demonstrates atomic node content replacement.

Although this implementation ensures that exactly one
version of this Node is alive at a given time, it fails to
maintain atomicity in the sense that iterators may
encounter both the old and new versions of the element.

@param newElement the new element
@return the new node, or null on failure

Tries to insert a node holding element to replace this node . failing if already deleted . A currently unused proof of concept that demonstrates atomic node content replacement .


@Deprecated
    @Override
    public BsonDocument execute(final WriteBinding binding) {
        return withConnection(binding, new CallableWithConnection<BsonDocument>() {
            @Override
            public BsonDocument call(final Connection connection) {
                if (serverIsAtLeastVersionThreeDotTwo(connection.getDescription())) {
                    return executeCommand(binding, "admin", FSYNC_UNLOCK_COMMAND, connection);
                } else {
                    return queryUnlock(connection);
                }
            }
        });
    }

@ Deprecated @ Override public BsonDocument execute ( final WriteBinding binding ) { return withConnection ( binding , new CallableWithConnection < BsonDocument > ( ) { @ Override public BsonDocument call ( final Connection connection ) { if ( serverIsAtLeastVersionThreeDotTwo ( connection . getDescription ( ) ) ) { return executeCommand ( binding , "admin" , FSYNC_UNLOCK_COMMAND , connection ) ; } else { return queryUnlock ( connection ) ; } } } ) ; }

Unlocks the MongoDB server, allowing write operations to go through.

@param binding the binding to execute in the context of
@return the result of the operation
@deprecated use {@link #execute(ReadBinding)} instead.

Unlocks the MongoDB server allowing write operations to go through .


public final List<ServerDescription> choose(final ClusterDescription clusterDescription) {
        switch (clusterDescription.getType()) {
            case REPLICA_SET:
                return chooseForReplicaSet(clusterDescription);
            case SHARDED:
            case STANDALONE:
                return chooseForNonReplicaSet(clusterDescription);
            case UNKNOWN:
                return Collections.emptyList();
            default:
                throw new UnsupportedOperationException("Unsupported cluster type: " + clusterDescription.getType());
        }
    }

public
final
List
<
ServerDescription
>
choose
(
final
ClusterDescription
clusterDescription
)
{
switch
(
clusterDescription
.
getType
(
)
)
{
case
REPLICA_SET
:
return
chooseForReplicaSet
(
clusterDescription
)
;
case
SHARDED
:
case
STANDALONE
:
return
chooseForNonReplicaSet
(
clusterDescription
)
;
case
UNKNOWN
:
return
Collections
.
emptyList
(
)
;
default
:
throw
new
UnsupportedOperationException
(
"Unsupported cluster type: "
+
clusterDescription
.
getType
(
)
)
;
}
}

Chooses the servers from the given cluster than match this read preference.

@param clusterDescription the cluster description
@return a list of matching server descriptions, which may be empty but may not be null

Chooses the servers from the given cluster than match this read preference .


public static ReadPreference primaryPreferred(final long maxStaleness, final TimeUnit timeUnit) {
        return new PrimaryPreferredReadPreference(Collections.<TagSet>emptyList(), maxStaleness, timeUnit);
    }

public static ReadPreference primaryPreferred ( final long maxStaleness , final TimeUnit timeUnit ) { return new PrimaryPreferredReadPreference ( Collections . < TagSet > emptyList ( ) , maxStaleness , timeUnit ) ; }

Gets a read preference that forces reads to the primary if available, otherwise to a secondary.

@param maxStaleness the max allowable staleness of secondaries. The minimum value is either 90 seconds, or the heartbeat frequency
plus 10 seconds, whichever is greatest.
@param timeUnit the time unit of maxStaleness
@return ReadPreference which reads primary if available.
@since 3.4
@see TaggableReadPreference#getMaxStaleness(TimeUnit)

Gets a read preference that forces reads to the primary if available otherwise to a secondary .


public static ReadPreference secondary(final long maxStaleness, final TimeUnit timeUnit) {
        return new SecondaryReadPreference(Collections.<TagSet>emptyList(), maxStaleness, timeUnit);
    }

public static ReadPreference secondary ( final long maxStaleness , final TimeUnit timeUnit ) { return new SecondaryReadPreference ( Collections . < TagSet > emptyList ( ) , maxStaleness , timeUnit ) ; }

Gets a read preference that forces reads to a secondary that is less stale than the given maximum.

<p>
The driver estimates the staleness of each secondary, based on lastWriteDate values provided in server isMaster responses,
and selects only those secondaries whose staleness is less than or equal to maxStaleness.
</p>

@param maxStaleness the max allowable staleness of secondaries. The minimum value is either 90 seconds, or the heartbeat frequency
plus 10 seconds, whichever is greatest.
@param timeUnit the time unit of maxStaleness
@return ReadPreference which reads secondary.
@since 3.4
@see TaggableReadPreference#getMaxStaleness(TimeUnit)

Gets a read preference that forces reads to a secondary that is less stale than the given maximum .


public static ReadPreference secondaryPreferred(final long maxStaleness, final TimeUnit timeUnit) {
        return new SecondaryPreferredReadPreference(Collections.<TagSet>emptyList(), maxStaleness, timeUnit);
    }

public static ReadPreference secondaryPreferred ( final long maxStaleness , final TimeUnit timeUnit ) { return new SecondaryPreferredReadPreference ( Collections . < TagSet > emptyList ( ) , maxStaleness , timeUnit ) ; }

Gets a read preference that forces reads to a secondary that is less stale than the given maximumm if one is available,
otherwise to the primary.

<p>
The driver estimates the staleness of each secondary, based on lastWriteDate values provided in server isMaster responses,
and selects only those secondaries whose staleness is less than or equal to maxStaleness.
</p>     *
@param maxStaleness the max allowable staleness of secondaries. The minimum value is either 90 seconds, or the heartbeat frequency
plus 10 seconds, whichever is greatest.
@param timeUnit the time unit of maxStaleness
@return ReadPreference which reads secondary if available, otherwise from primary.
@since 3.4
@see TaggableReadPreference#getMaxStaleness(TimeUnit)

Gets a read preference that forces reads to a secondary that is less stale than the given maximumm if one is available otherwise to the primary .


public static ReadPreference nearest(final long maxStaleness, final TimeUnit timeUnit) {
        return new NearestReadPreference(Collections.<TagSet>emptyList(), maxStaleness, timeUnit);
    }

public static ReadPreference nearest ( final long maxStaleness , final TimeUnit timeUnit ) { return new NearestReadPreference ( Collections . < TagSet > emptyList ( ) , maxStaleness , timeUnit ) ; }

Gets a read preference that forces reads to a primary or a secondary that is less stale than the given maximum.

<p>
The driver estimates the staleness of each secondary, based on lastWriteDate values provided in server isMaster responses,
and selects only those secondaries whose staleness is less than or equal to maxStaleness.
</p>

@param maxStaleness the max allowable staleness of secondaries. The minimum value is either 90 seconds, or the heartbeat frequency
plus 10 seconds, whichever is greatest.
@param timeUnit the time unit of maxStaleness
@return ReadPreference which reads nearest
@since 3.4
@see TaggableReadPreference#getMaxStaleness(TimeUnit)

Gets a read preference that forces reads to a primary or a secondary that is less stale than the given maximum .


public static TaggableReadPreference primaryPreferred(final TagSet tagSet,
                                                          final long maxStaleness, final TimeUnit timeUnit) {
        return new PrimaryPreferredReadPreference(singletonList(tagSet), maxStaleness, timeUnit);
    }

public static TaggableReadPreference primaryPreferred ( final TagSet tagSet , final long maxStaleness , final TimeUnit timeUnit ) { return new PrimaryPreferredReadPreference ( singletonList ( tagSet ) , maxStaleness , timeUnit ) ; }

Gets a read preference that forces reads to the primary if available, otherwise to a secondary with the given set of tags
that is less stale than the given maximum.

<p>
The driver estimates the staleness of each secondary, based on lastWriteDate values provided in server isMaster responses,
and selects only those secondaries whose staleness is less than or equal to maxStaleness.
</p>

@param tagSet the set of tags to limit the list of secondaries to.
@param maxStaleness the max allowable staleness of secondaries. The minimum value is either 90 seconds, or the heartbeat frequency
plus 10 seconds, whichever is greatest.
@param timeUnit the time unit of maxStaleness
@return ReadPreference which reads primary if available, otherwise a secondary respective of tags.\
@since 3.4
@see TaggableReadPreference#getMaxStaleness(TimeUnit)

Gets a read preference that forces reads to the primary if available otherwise to a secondary with the given set of tags that is less stale than the given maximum .


public static TaggableReadPreference secondary(final TagSet tagSet,
                                                   final long maxStaleness, final TimeUnit timeUnit) {
        return new SecondaryReadPreference(singletonList(tagSet), maxStaleness, timeUnit);
    }

public static TaggableReadPreference secondary ( final TagSet tagSet , final long maxStaleness , final TimeUnit timeUnit ) { return new SecondaryReadPreference ( singletonList ( tagSet ) , maxStaleness , timeUnit ) ; }

Gets a read preference that forces reads to a secondary with the given set of tags that is less stale than the given maximum.

<p>
The driver estimates the staleness of each secondary, based on lastWriteDate values provided in server isMaster responses,
and selects only those secondaries whose staleness is less than or equal to maxStaleness.
</p>

@param tagSet the set of tags to limit the list of secondaries to
@param maxStaleness the max allowable staleness of secondaries. The minimum value is either 90 seconds, or the heartbeat frequency
plus 10 seconds, whichever is greatest.
@param timeUnit the time unit of maxStaleness
@return ReadPreference which reads secondary respective of tags.
@since 3.4
@see TaggableReadPreference#getMaxStaleness(TimeUnit)

Gets a read preference that forces reads to a secondary with the given set of tags that is less stale than the given maximum .


public static TaggableReadPreference secondaryPreferred(final TagSet tagSet,
                                                            final long maxStaleness, final TimeUnit timeUnit) {
        return new SecondaryPreferredReadPreference(singletonList(tagSet), maxStaleness, timeUnit);
    }

public static TaggableReadPreference secondaryPreferred ( final TagSet tagSet , final long maxStaleness , final TimeUnit timeUnit ) { return new SecondaryPreferredReadPreference ( singletonList ( tagSet ) , maxStaleness , timeUnit ) ; }

Gets a read preference that forces reads to a secondary with the given set of tags that is less stale than the given maximum,
or the primary is none are available.

<p>
The driver estimates the staleness of each secondary, based on lastWriteDate values provided in server isMaster responses,
and selects only those secondaries whose staleness is less than or equal to maxStaleness.
</p>     *
@param tagSet the set of tags to limit the list of secondaries to
@param maxStaleness the max allowable staleness of secondaries. The minimum value is either 90 seconds, or the heartbeat frequency
plus 10 seconds, whichever is greatest.
@param timeUnit the time unit of maxStaleness
@return ReadPreference which reads secondary if available respective of tags, otherwise from primary irrespective of tags.
@since 3.4
@see TaggableReadPreference#getMaxStaleness(TimeUnit)

Gets a read preference that forces reads to a secondary with the given set of tags that is less stale than the given maximum or the primary is none are available .


public static TaggableReadPreference nearest(final TagSet tagSet,
                                                 final long maxStaleness, final TimeUnit timeUnit) {
        return new NearestReadPreference(singletonList(tagSet), maxStaleness, timeUnit);
    }

public static TaggableReadPreference nearest ( final TagSet tagSet , final long maxStaleness , final TimeUnit timeUnit ) { return new NearestReadPreference ( singletonList ( tagSet ) , maxStaleness , timeUnit ) ; }

Gets a read preference that forces reads to the primary or a secondary with the given set of tags that is less stale than the
given maximum.

<p>
The driver estimates the staleness of each secondary, based on lastWriteDate values provided in server isMaster responses,
and selects only those secondaries whose staleness is less than or equal to maxStaleness.
</p>

@param tagSet the set of tags to limit the list of secondaries to
@param maxStaleness the max allowable staleness of secondaries. The minimum value is either 90 seconds, or the heartbeat frequency
plus 10 seconds, whichever is greatest.
@param timeUnit the time unit of maxStaleness
@return ReadPreference which reads nearest node respective of tags.
@since 3.4
@see TaggableReadPreference#getMaxStaleness(TimeUnit)

Gets a read preference that forces reads to the primary or a secondary with the given set of tags that is less stale than the given maximum .


public static TaggableReadPreference primaryPreferred(final List<TagSet> tagSetList,
                                                          final long maxStaleness, final TimeUnit timeUnit) {
        return new PrimaryPreferredReadPreference(tagSetList, maxStaleness, timeUnit);
    }

public static TaggableReadPreference primaryPreferred ( final List < TagSet > tagSetList , final long maxStaleness , final TimeUnit timeUnit ) { return new PrimaryPreferredReadPreference ( tagSetList , maxStaleness , timeUnit ) ; }

Gets a read preference that forces reads to the primary if available, otherwise to a secondary with one of the given sets of tags
that is less stale than the given maximum.

The driver will look for a secondary with each tag set in the given list, stopping after one is found,
or failing if no secondary can be found that matches any of the tag sets in the list.

The driver estimates the staleness of each secondary, based on lastWriteDate values provided in server isMaster responses,
and selects only those secondaries whose staleness is less than or equal to maxStaleness.

@param tagSetList the list of tag sets to limit the list of secondaries to
@param maxStaleness the max allowable staleness of secondaries. The minimum value is either 90 seconds, or the heartbeat frequency
plus 10 seconds, whichever is greatest.
@param timeUnit the time unit of maxStaleness
@return ReadPreference which reads primary if available, otherwise a secondary respective of tags.
@since 3.4
@see TaggableReadPreference#getMaxStaleness(TimeUnit)

Gets a read preference that forces reads to the primary if available otherwise to a secondary with one of the given sets of tags that is less stale than the given maximum .


public static TaggableReadPreference nearest(final List<TagSet> tagSetList,
                                                 final long maxStaleness, final TimeUnit timeUnit) {
        return new NearestReadPreference(tagSetList, maxStaleness, timeUnit);
    }

public static TaggableReadPreference nearest ( final List < TagSet > tagSetList , final long maxStaleness , final TimeUnit timeUnit ) { return new NearestReadPreference ( tagSetList , maxStaleness , timeUnit ) ; }

Gets a read preference that forces reads to the primary or a secondary with one of the given sets of tags that is less stale than
the given maximum.

The driver will look for a secondary with each tag set in the given list, stopping after one is found,
or the primary if none are available.

The driver estimates the staleness of each secondary, based on lastWriteDate values provided in server isMaster responses,
and selects only those secondaries whose staleness is less than or equal to maxStaleness.

@param tagSetList the list of tag sets to limit the list of secondaries to
@param maxStaleness the max allowable staleness of secondaries. The minimum value is either 90 seconds, or the heartbeat frequency
plus 10 seconds, whichever is greatest.
@param timeUnit the time unit of maxStaleness
@return ReadPreference which reads nearest node respective of tags.
@since 3.4
@see TaggableReadPreference#getMaxStaleness(TimeUnit)

Gets a read preference that forces reads to the primary or a secondary with one of the given sets of tags that is less stale than the given maximum .


public static ReadPreference valueOf(final String name) {
        notNull("name", name);

        String nameToCheck = name.toLowerCase();

        if (nameToCheck.equals(PRIMARY.getName().toLowerCase())) {
            return PRIMARY;
        }
        if (nameToCheck.equals(SECONDARY.getName().toLowerCase())) {
            return SECONDARY;
        }
        if (nameToCheck.equals(SECONDARY_PREFERRED.getName().toLowerCase())) {
            return SECONDARY_PREFERRED;
        }
        if (nameToCheck.equals(PRIMARY_PREFERRED.getName().toLowerCase())) {
            return PRIMARY_PREFERRED;
        }
        if (nameToCheck.equals(NEAREST.getName().toLowerCase())) {
            return NEAREST;
        }

        throw new IllegalArgumentException("No match for read preference of " + name);
    }

public
static
ReadPreference
valueOf
(
final
String
name
)
{
notNull
(
"name"
,
name
)
;
String
nameToCheck
=
name
.
toLowerCase
(
)
;
if
(
nameToCheck
.
equals
(
PRIMARY
.
getName
(
)
.
toLowerCase
(
)
)
)
{
return
PRIMARY
;
}
if
(
nameToCheck
.
equals
(
SECONDARY
.
getName
(
)
.
toLowerCase
(
)
)
)
{
return
SECONDARY
;
}
if
(
nameToCheck
.
equals
(
SECONDARY_PREFERRED
.
getName
(
)
.
toLowerCase
(
)
)
)
{
return
SECONDARY_PREFERRED
;
}
if
(
nameToCheck
.
equals
(
PRIMARY_PREFERRED
.
getName
(
)
.
toLowerCase
(
)
)
)
{
return
PRIMARY_PREFERRED
;
}
if
(
nameToCheck
.
equals
(
NEAREST
.
getName
(
)
.
toLowerCase
(
)
)
)
{
return
NEAREST
;
}
throw
new
IllegalArgumentException
(
"No match for read preference of "
+
name
)
;
}

Creates a read preference from the given read preference name.

@param name the name of the read preference
@return the read preference

Creates a read preference from the given read preference name .


public static TaggableReadPreference valueOf(final String name, final List<TagSet> tagSetList) {
        return valueOf(name, tagSetList, null, MILLISECONDS);
    }

public static TaggableReadPreference valueOf ( final String name , final List < TagSet > tagSetList ) { return valueOf ( name , tagSetList , null , MILLISECONDS ) ; }

Creates a taggable read preference from the given read preference name and list of tag sets.

@param name the name of the read preference
@param tagSetList the list of tag sets
@return the taggable read preference
@since 2.13

Creates a taggable read preference from the given read preference name and list of tag sets .


public static TaggableReadPreference valueOf(final String name, final List<TagSet> tagSetList, final long maxStaleness,
                                                 final TimeUnit timeUnit) {
        return valueOf(name, tagSetList, (Long) maxStaleness, timeUnit);
    }

public static TaggableReadPreference valueOf ( final String name , final List < TagSet > tagSetList , final long maxStaleness , final TimeUnit timeUnit ) { return valueOf ( name , tagSetList , ( Long ) maxStaleness , timeUnit ) ; }

Creates a taggable read preference from the given read preference name, list of tag sets, and max allowable staleness of secondaries.

<p>
The driver estimates the staleness of each secondary, based on lastWriteDate values provided in server isMaster responses,
and selects only those secondaries whose staleness is less than or equal to maxStaleness.
</p>

@param name the name of the read preference
@param tagSetList the list of tag sets
@param maxStaleness the max allowable staleness of secondaries. The minimum value is either 90 seconds, or the heartbeat frequency
plus 10 seconds, whichever is greatest.
@param timeUnit the time unit of maxStaleness
@return the taggable read preference
@since 3.4
@see TaggableReadPreference#getMaxStaleness(TimeUnit)

Creates a taggable read preference from the given read preference name list of tag sets and max allowable staleness of secondaries .


public static void readFully(final InputStream inputStream, final byte[] buffer, final int offset, final int length)
    throws IOException {
        if (buffer.length < length + offset) {
            throw new IllegalArgumentException("Buffer is too small");
        }

        int arrayOffset = offset;
        int bytesToRead = length;
        while (bytesToRead > 0) {
            int bytesRead = inputStream.read(buffer, arrayOffset, bytesToRead);
            if (bytesRead < 0) {
                throw new EOFException();
            }
            bytesToRead -= bytesRead;
            arrayOffset += bytesRead;
        }
    }

public
static
void
readFully
(
final
InputStream
inputStream
,
final
byte
[
]
buffer
,
final
int
offset
,
final
int
length
)
throws
IOException
{
if
(
buffer
.
length
<
length
+
offset
)
{
throw
new
IllegalArgumentException
(
"Buffer is too small"
)
;
}
int
arrayOffset
=
offset
;
int
bytesToRead
=
length
;
while
(
bytesToRead
>
0
)
{
int
bytesRead
=
inputStream
.
read
(
buffer
,
arrayOffset
,
bytesToRead
)
;
if
(
bytesRead
<
0
)
{
throw
new
EOFException
(
)
;
}
bytesToRead
-=
bytesRead
;
arrayOffset
+=
bytesRead
;
}
}

Reads bytes from the input stream and puts them into the given byte buffer.

@param inputStream the input stream to read from
@param buffer      the buffer into which the data is read.
@param offset      the start offset in array {@code buffer} at which the data is written.
@param length      the maximum number of bytes to read.
@throws IOException if there's an error reading from the {@code inputStream}
@see java.io.InputStream#read(byte[], int, int)

Reads bytes from the input stream and puts them into the given byte buffer .


public static int readInt(final InputStream inputStream, final byte[] buffer) throws IOException {
        readFully(inputStream, buffer, 4);
        return readInt(buffer);
    }

public static int readInt ( final InputStream inputStream , final byte [ ] buffer ) throws IOException { readFully ( inputStream , buffer , 4 ) ; return readInt ( buffer ) ; }

Reads and returns a single integer value from the input stream.

@param inputStream the input stream to read from
@param buffer the buffer to write the input stream bytes into
@return the integer value
@throws IOException if there's an error reading from the {@code inputStream}

Reads and returns a single integer value from the input stream .


public static int readInt(final byte[] buffer, final int offset) {
        int x = 0;
        x |= (0xFF & buffer[offset + 0]) << 0;
        x |= (0xFF & buffer[offset + 1]) << 8;
        x |= (0xFF & buffer[offset + 2]) << 16;
        x |= (0xFF & buffer[offset + 3]) << 24;
        return x;
    }

public static int readInt ( final byte [ ] buffer , final int offset ) { int x = 0 ; x |= ( 0xFF & buffer [ offset + 0 ] ) << 0 ; x |= ( 0xFF & buffer [ offset + 1 ] ) << 8 ; x |= ( 0xFF & buffer [ offset + 2 ] ) << 16 ; x |= ( 0xFF & buffer [ offset + 3 ] ) << 24 ; return x ; }

Reads and returns a single integer value from the buffer.

@param buffer the buffer to read from
@param offset the position to start reading from the buffer
@return the integer value

Reads and returns a single integer value from the buffer .


public static int readIntBE(final byte[] buffer, final int offset) {
        int x = 0;
        x |= (0xFF & buffer[offset + 0]) << 24;
        x |= (0xFF & buffer[offset + 1]) << 16;
        x |= (0xFF & buffer[offset + 2]) << 8;
        x |= (0xFF & buffer[offset + 3]) << 0;
        return x;
    }

public static int readIntBE ( final byte [ ] buffer , final int offset ) { int x = 0 ; x |= ( 0xFF & buffer [ offset + 0 ] ) << 24 ; x |= ( 0xFF & buffer [ offset + 1 ] ) << 16 ; x |= ( 0xFF & buffer [ offset + 2 ] ) << 8 ; x |= ( 0xFF & buffer [ offset + 3 ] ) << 0 ; return x ; }

Reads and returns a single big-endian integer value

@param buffer the buffer to read from
@param offset the position to start reading from the buffer
@return the integer value

Reads and returns a single big - endian integer value


public static long readLong(final InputStream inputStream, final byte[] buffer) throws IOException {
        readFully(inputStream, buffer, 8);
        return readLong(buffer);
    }

public static long readLong ( final InputStream inputStream , final byte [ ] buffer ) throws IOException { readFully ( inputStream , buffer , 8 ) ; return readLong ( buffer ) ; }

Reads and returns a single long value from the input stream.

@param inputStream the input stream to read from
@param buffer the buffer to write the input stream bytes into
@return the long value
@throws IOException if there's an error reading from the {@code inputStream}

Reads and returns a single long value from the input stream .


@Deprecated
    public List<MongoCredential> getCredentialList() {
        return credential != null ? singletonList(credential) : Collections.<MongoCredential>emptyList();
    }

@ Deprecated public List < MongoCredential > getCredentialList ( ) { return credential != null ? singletonList ( credential ) : Collections . < MongoCredential > emptyList ( ) ; }

Gets the credentials in an immutable list.  The list will be empty if no credentials were specified in the connection string.

@return the credentials in an immutable list
@deprecated Prefer {@link #getCredential()}

Gets the credentials in an immutable list . The list will be empty if no credentials were specified in the connection string .


private ClusterableServer getRandomServer(final List<ServerDescription> serverDescriptions) {
        while (!serverDescriptions.isEmpty()) {
            int serverPos = getRandom().nextInt(serverDescriptions.size());
            ClusterableServer server = getServer(serverDescriptions.get(serverPos).getAddress());
            if (server != null) {
                return server;
            } else {
                serverDescriptions.remove(serverPos);
            }
        }
        return null;
    }

private ClusterableServer getRandomServer ( final List < ServerDescription > serverDescriptions ) { while ( ! serverDescriptions . isEmpty ( ) ) { int serverPos = getRandom ( ) . nextInt ( serverDescriptions . size ( ) ) ; ClusterableServer server = getServer ( serverDescriptions . get ( serverPos ) . getAddress ( ) ) ; if ( server != null ) { return server ; } else { serverDescriptions . remove ( serverPos ) ; } } return null ; }

gets a random server that still exists in the cluster.  Returns null if there are none.

gets a random server that still exists in the cluster . Returns null if there are none .


public static MongoClient create(final ConnectionString connectionString,
                                     @Nullable final MongoDriverInformation mongoDriverInformation) {

        return create(MongoClientSettings.builder().applyConnectionString(connectionString).build(),
                mongoDriverInformation, connectionString.getStreamType());
    }

public static MongoClient create ( final ConnectionString connectionString , @ Nullable final MongoDriverInformation mongoDriverInformation ) { return create ( MongoClientSettings . builder ( ) . applyConnectionString ( connectionString ) . build ( ) , mongoDriverInformation , connectionString . getStreamType ( ) ) ; }

Create a new client with the given connection string.

Note: Intended for driver and library authors to associate extra driver metadata with the connections.

@param connectionString       the settings
@param mongoDriverInformation any driver information to associate with the MongoClient
@return the client
@throws IllegalArgumentException if the connection string's stream type is not one of "netty" or "nio2"
@see MongoClients#create(ConnectionString)

Create a new client with the given connection string .


public Object copy() {
        // copy field values into new object
        BasicDBList newobj = new BasicDBList();
        // need to clone the sub obj
        for (int i = 0; i < size(); ++i) {
            Object val = get(i);
            if (val instanceof BasicDBObject) {
                val = ((BasicDBObject) val).copy();
            } else if (val instanceof BasicDBList) {
                val = ((BasicDBList) val).copy();
            }
            newobj.add(val);
        }
        return newobj;
    }

public
Object
copy
(
)
{
// copy field values into new object
BasicDBList
newobj
=
new
BasicDBList
(
)
;
// need to clone the sub obj
for
(
int
i
=
0
;
i
<
size
(
)
;
++
i
)
{
Object
val
=
get
(
i
)
;
if
(
val
instanceof
BasicDBObject
)
{
val
=
(
(
BasicDBObject
)
val
)
.
copy
(
)
;
}
else
if
(
val
instanceof
BasicDBList
)
{
val
=
(
(
BasicDBList
)
val
)
.
copy
(
)
;
}
newobj
.
add
(
val
)
;
}
return
newobj
;
}

Copies this instance into a new Object.

@return a new BasicDBList with the same values as this instance

Copies this instance into a new Object .


public static <S> ClassModelBuilder<S> builder(final Class<S> type) {
        return new ClassModelBuilder<S>(type);
    }

public static < S > ClassModelBuilder < S > builder ( final Class < S > type ) { return new ClassModelBuilder < S > ( type ) ; }

Creates a new Class Model builder instance using reflection.

@param type the POJO class to reflect and configure the builder with.
@param <S> the type of the class
@return a new Class Model builder instance using reflection on the {@code clazz}.

Creates a new Class Model builder instance using reflection .


public DBCollection getCollection(final String name) {
        DBCollection collection = collectionCache.get(name);
        if (collection != null) {
            return collection;
        }

        collection = new DBCollection(name, this, executor);
        if (mongo.getMongoClientOptions().getDbDecoderFactory() != DefaultDBDecoder.FACTORY) {
            collection.setDBDecoderFactory(mongo.getMongoClientOptions().getDbDecoderFactory());
        }
        if (mongo.getMongoClientOptions().getDbEncoderFactory() != DefaultDBEncoder.FACTORY) {
            collection.setDBEncoderFactory(mongo.getMongoClientOptions().getDbEncoderFactory());
        }
        DBCollection old = collectionCache.putIfAbsent(name, collection);
        return old != null ? old : collection;
    }

public DBCollection getCollection ( final String name ) { DBCollection collection = collectionCache . get ( name ) ; if ( collection != null ) { return collection ; } collection = new DBCollection ( name , this , executor ) ; if ( mongo . getMongoClientOptions ( ) . getDbDecoderFactory ( ) != DefaultDBDecoder . FACTORY ) { collection . setDBDecoderFactory ( mongo . getMongoClientOptions ( ) . getDbDecoderFactory ( ) ) ; } if ( mongo . getMongoClientOptions ( ) . getDbEncoderFactory ( ) != DefaultDBEncoder . FACTORY ) { collection . setDBEncoderFactory ( mongo . getMongoClientOptions ( ) . getDbEncoderFactory ( ) ) ; } DBCollection old = collectionCache . putIfAbsent ( name , collection ) ; return old != null ? old : collection ; }

Gets a collection with a given name.

@param name the name of the collection to return
@return the collection
@throws IllegalArgumentException if the name is invalid
@see MongoNamespace#checkCollectionNameValidity(String)


public void dropDatabase() {
        try {
            getExecutor().execute(new DropDatabaseOperation(getName(), getWriteConcern()), getReadConcern());
        } catch (MongoWriteConcernException e) {
            throw createWriteConcernException(e);
        }
    }

public void dropDatabase ( ) { try { getExecutor ( ) . execute ( new DropDatabaseOperation ( getName ( ) , getWriteConcern ( ) ) , getReadConcern ( ) ) ; } catch ( MongoWriteConcernException e ) { throw createWriteConcernException ( e ) ; } }

Drops this database. Removes all data on disk. Use with caution.

@throws MongoException if the operation failed
@mongodb.driver.manual reference/command/dropDatabase/ Drop Database

Drops this database . Removes all data on disk . Use with caution .


public Set<String> getCollectionNames() {
        List<String> collectionNames =
                new MongoIterableImpl<DBObject>(null, executor, ReadConcern.DEFAULT, primary(),
                        mongo.getMongoClientOptions().getRetryReads()) {
                    @Override
                    public ReadOperation<BatchCursor<DBObject>> asReadOperation() {
                        return new ListCollectionsOperation<DBObject>(name, commandCodec)
                                .nameOnly(true);
                    }
                }.map(new Function<DBObject, String>() {
                            @Override
                            public String apply(final DBObject result) {
                                return (String) result.get("name");
                            }
                        }).into(new ArrayList<String>());
        Collections.sort(collectionNames);
        return new LinkedHashSet<String>(collectionNames);
    }

public Set < String > getCollectionNames ( ) { List < String > collectionNames = new MongoIterableImpl < DBObject > ( null , executor , ReadConcern . DEFAULT , primary ( ) , mongo . getMongoClientOptions ( ) . getRetryReads ( ) ) { @ Override public ReadOperation < BatchCursor < DBObject > > asReadOperation ( ) { return new ListCollectionsOperation < DBObject > ( name , commandCodec ) . nameOnly ( true ) ; } } . map ( new Function < DBObject , String > ( ) { @ Override public String apply ( final DBObject result ) { return ( String ) result . get ( "name" ) ; } } ) . into ( new ArrayList < String > ( ) ) ; Collections . sort ( collectionNames ) ; return new LinkedHashSet < String > ( collectionNames ) ; }

Returns a set containing the names of all collections in this database.

@return the names of collections in this database
@throws MongoException if the operation failed
@mongodb.driver.manual reference/method/db.getCollectionNames/ getCollectionNames()

Returns a set containing the names of all collections in this database .


public CommandResult command(final DBObject command, final ReadPreference readPreference, @Nullable final DBEncoder encoder) {
        try {
            return executeCommand(wrap(command, encoder), getCommandReadPreference(command, readPreference));
        } catch (MongoCommandException ex) {
            return new CommandResult(ex.getResponse(), ex.getServerAddress());
        }
    }

public CommandResult command ( final DBObject command , final ReadPreference readPreference , @ Nullable final DBEncoder encoder ) { try { return executeCommand ( wrap ( command , encoder ) , getCommandReadPreference ( command , readPreference ) ) ; } catch ( MongoCommandException ex ) { return new CommandResult ( ex . getResponse ( ) , ex . getServerAddress ( ) ) ; } }

Executes a database command with the selected readPreference, and encodes the command using the given encoder.

@param command        The {@code DBObject} representation the command to be executed
@param readPreference Where to execute the command - this will only be applied for a subset of commands
@param encoder        The DBEncoder that knows how to serialise the command
@return The result of executing the command, success or failure
@mongodb.driver.manual tutorial/use-database-commands Commands
@since 2.12

Executes a database command with the selected readPreference and encodes the command using the given encoder .


public CommandResult command(final DBObject command, final ReadPreference readPreference) {
        return command(command, readPreference, null);
    }

public CommandResult command ( final DBObject command , final ReadPreference readPreference ) { return command ( command , readPreference , null ) ; }

Executes the command against the database with the given read preference.

@param command        The {@code DBObject} representation the command to be executed
@param readPreference Where to execute the command - this will only be applied for a subset of commands
@return The result of executing the command, success or failure
@mongodb.driver.manual tutorial/use-database-commands Commands
@since 2.12

Executes the command against the database with the given read preference .


public boolean collectionExists(final String collectionName) {
        Set<String> collectionNames = getCollectionNames();
        for (final String name : collectionNames) {
            if (name.equalsIgnoreCase(collectionName)) {
                return true;
            }
        }
        return false;
    }

public boolean collectionExists ( final String collectionName ) { Set < String > collectionNames = getCollectionNames ( ) ; for ( final String name : collectionNames ) { if ( name . equalsIgnoreCase ( collectionName ) ) { return true ; } } return false ; }

Checks to see if a collection with a given name exists on a server.

@param collectionName a name of the collection to test for existence
@return {@code false} if no collection by that name exists, {@code true} if a match to an existing collection was found
@throws MongoException if the operation failed

Checks to see if a collection with a given name exists on a server .


@Deprecated
    public CommandResult doEval(final String code, final Object... args) {
        DBObject commandDocument = new BasicDBObject("$eval", code).append("args", asList(args));
        return executeCommand(wrap(commandDocument));
    }

@ Deprecated public CommandResult doEval ( final String code , final Object ... args ) { DBObject commandDocument = new BasicDBObject ( "$eval" , code ) . append ( "args" , asList ( args ) ) ; return executeCommand ( wrap ( commandDocument ) ) ; }

Evaluates JavaScript functions on the database server. This is useful if you need to touch a lot of data lightly, in which case
network transfer could be a bottleneck.

@param code {@code String} representation of JavaScript function
@param args arguments to pass to the JavaScript function
@return result of the command execution
@throws MongoException if the operation failed
@mongodb.driver.manual reference/method/db.eval/ db.eval()
@deprecated The eval command was deprecated in MongoDB 3.0

Evaluates JavaScript functions on the database server . This is useful if you need to touch a lot of data lightly in which case network transfer could be a bottleneck .


@Deprecated
    public CommandResult getStats() {
        BsonDocument commandDocument = new BsonDocument("dbStats", new BsonInt32(1)).append("scale", new BsonInt32(1));
        return executeCommand(commandDocument);
    }

@ Deprecated public CommandResult getStats ( ) { BsonDocument commandDocument = new BsonDocument ( "dbStats" , new BsonInt32 ( 1 ) ) . append ( "scale" , new BsonInt32 ( 1 ) ) ; return executeCommand ( commandDocument ) ; }

Helper method for calling a 'dbStats' command. It returns storage statistics for a given database.

@return result of the execution
@throws MongoException if the operation failed
@mongodb.driver.manual reference/command/dbStats/ Database Stats
@deprecated Prefer {@link #command(DBObject)} to run the dbStats command

Helper method for calling a dbStats command . It returns storage statistics for a given database .


@Deprecated
    public WriteResult removeUser(final String userName) {
        try {
            executor.execute(new com.mongodb.operation.DropUserOperation(getName(), userName, getWriteConcern()), getReadConcern());
            return new WriteResult(1, true, null);
        } catch (MongoWriteConcernException e) {
            throw createWriteConcernException(e);
        }
    }

@ Deprecated public WriteResult removeUser ( final String userName ) { try { executor . execute ( new com . mongodb . operation . DropUserOperation ( getName ( ) , userName , getWriteConcern ( ) ) , getReadConcern ( ) ) ; return new WriteResult ( 1 , true , null ) ; } catch ( MongoWriteConcernException e ) { throw createWriteConcernException ( e ) ; } }

Removes the specified user from the database.

@param userName user to be removed
@return the result of executing this operation
@throws MongoException if the operation failed
@mongodb.driver.manual administration/security-access-control/  Access Control
@deprecated Use {@code DB.command} to call the dropUser command

Removes the specified user from the database .


ReadPreference getCommandReadPreference(final DBObject command, @Nullable final ReadPreference requestedPreference) {
        String comString = command.keySet().iterator().next().toLowerCase();
        boolean primaryRequired = !OBEDIENT_COMMANDS.contains(comString);

        if (primaryRequired) {
            return ReadPreference.primary();
        } else if (requestedPreference == null) {
            return ReadPreference.primary();
        } else {
            return requestedPreference;
        }
    }

ReadPreference getCommandReadPreference ( final DBObject command , @ Nullable final ReadPreference requestedPreference ) { String comString = command . keySet ( ) . iterator ( ) . next ( ) . toLowerCase ( ) ; boolean primaryRequired = ! OBEDIENT_COMMANDS . contains ( comString ) ; if ( primaryRequired ) { return ReadPreference . primary ( ) ; } else if ( requestedPreference == null ) { return ReadPreference . primary ( ) ; } else { return requestedPreference ; } }

Determines the read preference that should be used for the given command.

@param command             the {@link DBObject} representing the command
@param requestedPreference the preference requested by the client.
@return the read preference to use for the given command.  It will never return {@code null}.
@see com.mongodb.ReadPreference

Determines the read preference that should be used for the given command .