signature:
public class Engine { /** * Runs the given task if Engine has a capacity to start new plan as specified by
 * { @ value # MAX _ CONCURRENT _ PLANS } configuration parameter within specified amount of time .
 * For the sake of backwards compatibility default value for a { @ value # MAX _ CONCURRENT _ PLANS } is
 * { @ value # DEFUALT _ MAX _ CONCURRENT _ PLANS } which essentially means " unbounded capacity " .
 * Task passed in as a parameter becomes a root on a new Plan .
 * All tasks created and started as a consequence of a root task will belong to that plan and will share a Trace .
 * If Engine does not have capacity to start the task , this method will block up to specified amount of
 * time waiting for other concurrently running Plans to complete . If there is no capacity to start the task
 * within specified amount of time this method will return false . It returns { @ code true } if Plan was successfully started .
 * @ param task the task to run
 * @ param timeout amount of time to wait for Engine ' s capacity to run the task
 * @ param unit
 * @ return true if Plan was started within the given waiting time and the current thread has not
 * been { @ linkplain Thread # interrupt interrupted } . */
public boolean tryRun ( final Task < ? > task , final long timeout , final TimeUnit unit ) throws InterruptedException { } }

implementation: return tryRun ( task , defaultPlanClass ( task ) , timeout , unit ) ;


signature:
public class Engine { /** * Runs the given task if Engine has a capacity to start new plan as specified by
 * { @ value # MAX _ CONCURRENT _ PLANS } configuration parameter within specified amount of time .
 * For the sake of backwards compatibility default value for a { @ value # MAX _ CONCURRENT _ PLANS } is
 * { @ value # DEFUALT _ MAX _ CONCURRENT _ PLANS } which essentially means " unbounded capacity " .
 * Task passed in as a parameter becomes a root on a new Plan .
 * All tasks created and started as a consequence of a root task will belong to that plan and will share a Trace .
 * If Engine does not have capacity to start the task , this method will block up to specified amount of
 * time waiting for other concurrently running Plans to complete . If there is no capacity to start the task
 * within specified amount of time this method will return false . It returns { @ code true } if Plan was successfully started .
 * @ param task the task to run
 * @ param planClass string that identifies a " class " of the Plan
 * @ param timeout amount of time to wait for Engine ' s capacity to run the task
 * @ param unit
 * @ return true if Plan was started within the given waiting time and the current thread has not
 * been { @ linkplain Thread # interrupt interrupted } . */
public boolean tryRun ( final Task < ? > task , final String planClass , final long timeout , final TimeUnit unit ) throws InterruptedException { } }

implementation: if ( tryAcquirePermit ( planClass , timeout , unit ) ) { runWithPermit ( task , planClass ) ; return true ; } else { return false ; }


signature:
public class Engine { /** * Runs the given task with its own context . Use { @ code Tasks . seq } and
 * { @ code Tasks . par } to create and run composite tasks .
 * @ param task the task to run */
private void runWithPermit ( final Task < ? > task , final String planClass ) { } }

implementation: ArgumentUtil . requireNotNull ( task , "task" ) ; ArgumentUtil . requireNotNull ( planClass , "planClass" ) ; State currState , newState ; do { currState = _stateRef . get ( ) ; if ( currState . _stateName != StateName . RUN ) { task . cancel ( new EngineShutdownException ( "Task submitted after engine shutdown" ) ) ; return ; } newState = new State ( StateName . RUN , currState . _pendingCount + 1 ) ; } while ( ! _stateRef . compareAndSet ( currState , newState ) ) ; PlanContext planContext = new PlanContext ( this , _taskExecutor , _timerExecutor , _loggerFactory , _allLogger , _rootLogger , planClass , task , _maxRelationshipsPerTrace , _planDeactivationListener , _planCompletionListener , _taskQueueFactory . newTaskQueue ( ) , _drainSerialExecutorQueue , _executionMonitor ) ; new ContextImpl ( planContext , task ) . runTask ( ) ;


signature:
public class Engine { /** * rate limiter and then from plan class level rate limit if specified . */
private boolean tryAcquirePermit ( String planClass ) { } }

implementation: return _concurrentPlans . tryAcquire ( ) && ( _planBasedRateLimiter == null || _planBasedRateLimiter . tryAcquire ( planClass ) ) ;


signature:
public class FibonacciBackoff { /** * { @ inheritDoc } */
@ Override public long nextBackoff ( int attempts , Throwable error ) { } }

implementation: return Math . round ( Math . pow ( 1.6 , attempts - 1 ) * _backoff ) ;


signature:
public class HttpClient { /** * Returns raw http client . If client has not been initialized yet
 * then new client is created with default configuration .
 * @ return raw http client */
public static synchronized AsyncHttpClient getNingClient ( ) { } }

implementation: if ( _client . get ( ) == null ) { initialize ( new AsyncHttpClientConfig . Builder ( ) . build ( ) ) ; } return _client . get ( ) ;


signature:
public class HttpClient { /** * Initializes HttpClient with custom configuration .
 * @ param cfg client configuration
 * @ see AsyncHttpClientConfig */
@ SuppressWarnings ( "resource" ) public static synchronized void initialize ( AsyncHttpClientConfig cfg ) { } }

implementation: if ( ! _client . compareAndSet ( null , new AsyncHttpClient ( cfg ) ) ) { throw new RuntimeException ( "async http client concurrently initialized" ) ; }


signature:
public class Table { /** * Factory method to obtain an instance of { @ link Table }
 * @ param markwon Markwon
 * @ param tableBlock TableBlock to parse
 * @ return parsed { @ link Table } or null */
@ Nullable public static Table parse ( @ NonNull Markwon markwon , @ NonNull TableBlock tableBlock ) { } }

implementation: final Table table ; final ParseVisitor visitor = new ParseVisitor ( markwon ) ; tableBlock . accept ( visitor ) ; final List < Row > rows = visitor . rows ( ) ; if ( rows == null ) { table = null ; } else { table = new Table ( rows ) ; } return table ;


signature:
public class CustomExtensionActivity { /** * used , this is fully functional sample on all SDK levels */
@ Override public void onCreate ( @ Nullable Bundle savedInstanceState ) { } }

implementation:
super . onCreate ( savedInstanceState ) ; setContentView ( R . layout . activity_text_view ) ; final TextView textView = findViewById ( R . id . text_view ) ; // note that we haven ' t registered CorePlugin , as it ' s the only one that can be
// implicitly deducted and added automatically . All other plugins require explicit
// ` usePlugin ` call
final Markwon markwon = Markwon . builder ( this ) // try commenting out this line to see runtime dependency resolution
. usePlugin ( ImagesPlugin . create ( this ) ) . usePlugin ( IconPlugin . create ( IconSpanProvider . create ( this , 0 ) ) ) . build ( ) ; markwon . setMarkdown ( textView , getString ( R . string . input ) ) ;


signature:
public class IconProcessor { /** * Should be used when input string does not wrap icon definition with ` @ ` from both ends .
 * So , ` @ ic - home - white - 24 ` would become ` @ ic - home - white - 24 @ ` . This way parsing is easier
 * and more predictable ( cannot specify multiple ending delimiters , as we would require them :
 * space , newline , end of a document , and a lot of more )
 * @ param input to process
 * @ return processed string
 * @ see # prepare ( StringBuilder ) */
@ NonNull public static String prepare ( @ NonNull String input ) { } }

implementation: final StringBuilder builder = new StringBuilder ( input ) ; prepare ( builder ) ; return builder . toString ( ) ;


signature:
public class MarkwonBuilderImpl { /** * that depends on CorePlugin */
@ VisibleForTesting @ NonNull static List < MarkwonPlugin > ensureImplicitCoreIfHasDependents ( @ NonNull List < MarkwonPlugin > plugins ) { } }

implementation:
// loop over plugins - > if CorePlugin is found - > break ;
// iterate over all plugins and check if CorePlugin is requested
boolean hasCore = false ; boolean hasCoreDependents = false ; for ( MarkwonPlugin plugin : plugins ) { // here we do not check for exact match ( a user could ' ve subclasses CorePlugin
// and supplied it . In this case we DO NOT implicitly add CorePlugin
// if core is present already we do not need to iterate anymore - > as nothing
// will be changed ( and we actually do not care if there are any dependents of Core
// as it ' s present anyway )
if ( CorePlugin . class . isAssignableFrom ( plugin . getClass ( ) ) ) { hasCore = true ; break ; } // if plugin has CorePlugin in dependencies - > mark for addition
if ( ! hasCoreDependents ) { // here we check for direct CorePlugin , if it ' s not CorePlugin ( exact , not a subclass
// or something - > ignore )
if ( plugin . priority ( ) . after ( ) . contains ( CorePlugin . class ) ) { hasCoreDependents = true ; } } } // important thing here is to check if corePlugin is added
// add it _ only _ if it ' s not present
if ( hasCoreDependents && ! hasCore ) { final List < MarkwonPlugin > out = new ArrayList < > ( plugins . size ( ) + 1 ) ; // add default instance of CorePlugin
out . add ( CorePlugin . create ( ) ) ; out . addAll ( plugins ) ; return out ; } return plugins ;


signature:
public class OrderedListItemSpan { /** * Process supplied ` text ` argument and supply TextView paint to all OrderedListItemSpans
 * in order for them to measure number .
 * NB , this method must be called < em > before < / em > setting text to a TextView ( ` TextView # setText `
 * internally can trigger new Layout creation which will ask for leading margins right away )
 * @ param textView to which markdown will be applied
 * @ param text parsed markdown to process
 * @ since 2.0.1 */
public static void measure ( @ NonNull TextView textView , @ NonNull CharSequence text ) { } }

implementation:
if ( ! ( text instanceof Spanned ) ) { // nothing to do here
return ; } final OrderedListItemSpan [ ] spans = ( ( Spanned ) text ) . getSpans ( 0 , text . length ( ) , OrderedListItemSpan . class ) ; if ( spans != null ) { final TextPaint paint = textView . getPaint ( ) ; for ( OrderedListItemSpan span : spans ) { span . margin = ( int ) ( paint . measureText ( span . number ) + .5F ) ; } }


signature:
public class BasicPluginsActivity { /** * In order to apply paragraph spans a custom plugin should be created ( CorePlugin will take care
 * of everything else ) .
 * Please note that when a plugin is registered and it < em > depends < / em > on CorePlugin , there is no
 * need to explicitly specify it . By default all plugins that extend AbstractMarkwonPlugin do declare
 * it \ ' s dependency on CorePlugin ( { @ link MarkwonPlugin # priority ( ) } ) .
 * Order in which plugins are specified to the builder is of little importance as long as each
 * plugin clearly states what dependencies it has */
private void step_1 ( ) { } }

implementation: final String markdown = "# Hello!\n\nA paragraph?\n\nIt should be!" ; final Markwon markwon = Markwon . builder ( this ) . usePlugin ( new AbstractMarkwonPlugin ( ) { @ Override public void configureSpansFactory ( @ NonNull MarkwonSpansFactory . Builder builder ) { builder . setFactory ( Paragraph . class , ( configuration , props ) -> new ForegroundColorSpan ( Color . GREEN ) ) ; } } ) . build ( ) ; markwon . setMarkdown ( textView , markdown ) ;


signature:
public class BasicPluginsActivity { /** * To disable some nodes from rendering another custom plugin can be used */
private void step_2 ( ) { } }

implementation:
final String markdown = "# Heading 1\n\n## Heading 2\n\n**other** content [here](#)" ; final Markwon markwon = Markwon . builder ( this ) . usePlugin ( new AbstractMarkwonPlugin ( ) { @ Override public void configureVisitor ( @ NonNull MarkwonVisitor . Builder builder ) { // for example to disable rendering of heading :
// try commenting this out to see that otherwise headings will be rendered
builder . on ( Heading . class , null ) ; // same method can be used to override existing visitor by specifying
// a new NodeVisitor instance
} } ) . build ( ) ; markwon . setMarkdown ( textView , markdown ) ;


signature:
public class BasicPluginsActivity { /** * To customize core theme plugin can be used again */
private void step_3 ( ) { } }

implementation: final String markdown = "`A code` that is rendered differently\n\n```\nHello!\n```" ; final Markwon markwon = Markwon . builder ( this ) . usePlugin ( new AbstractMarkwonPlugin ( ) { @ Override public void configureTheme ( @ NonNull MarkwonTheme . Builder builder ) { builder . codeBackgroundColor ( Color . BLACK ) . codeTextColor ( Color . RED ) ; } } ) . build ( ) ; markwon . setMarkdown ( textView , markdown ) ;


signature:
public class BasicPluginsActivity { /** * MarkwonConfiguration contains these < em > utilities < / em > :
 * < ul >
 * < li > SyntaxHighlight < / li >
 * < li > LinkSpan . Resolver < / li >
 * < li > UrlProcessor < / li >
 * < li > ImageSizeResolver < / li >
 * < / ul >
 * In order to customize them a custom plugin should be used */
private void step_4 ( ) { } }

implementation:
final String markdown = "[a link without scheme](github.com)" ; final Markwon markwon = Markwon . builder ( this ) // please note that Markwon does not handle MovementMethod ,
// so if your markdown has links your should apply MovementMethod manually
// or use MovementMethodPlugin ( which uses system LinkMovementMethod by default )
. usePlugin ( MovementMethodPlugin . create ( ) ) . usePlugin ( new AbstractMarkwonPlugin ( ) { @ Override public void configureConfiguration ( @ NonNull MarkwonConfiguration . Builder builder ) { // for example if specified destination has no scheme info , we will
// _ assume _ that it ' s network request and append HTTPS scheme
builder . urlProcessor ( destination -> { final Uri uri = Uri . parse ( destination ) ; if ( TextUtils . isEmpty ( uri . getScheme ( ) ) ) { return "https://" + destination ; } return destination ; } ) ; } } ) . build ( ) ; markwon . setMarkdown ( textView , markdown ) ;


signature:
public class BasicPluginsActivity { /** * Images configuration . Can be used with ( or without ) ImagesPlugin , which does some basic
 * images handling ( parsing markdown containing images , obtain an image from network
 * file system or assets ) . Please note that */
private void step_5 ( ) { } }

implementation:
final String markdown = "![image](myownscheme://en.wikipedia.org/static/images/project-logos/enwiki-2x.png)" ; final Markwon markwon = Markwon . builder ( this ) . usePlugin ( ImagesPlugin . create ( this ) ) . usePlugin ( new AbstractMarkwonPlugin ( ) { @ Override public void configureImages ( @ NonNull AsyncDrawableLoader . Builder builder ) { // we can have a custom SchemeHandler
// here we will just use networkSchemeHandler to redirect call
builder . addSchemeHandler ( "myownscheme" , new SchemeHandler ( ) { final NetworkSchemeHandler networkSchemeHandler = NetworkSchemeHandler . create ( ) ; @ Nullable @ Override public ImageItem handle ( @ NonNull String raw , @ NonNull Uri uri ) { raw = raw . replace ( "myownscheme" , "https" ) ; return networkSchemeHandler . handle ( raw , Uri . parse ( raw ) ) ; } } ) ; } } ) . build ( ) ; markwon . setMarkdown ( textView , markdown ) ;


signature:
public class MarkwonAdapter { /** * Factory method to obtain { @ link Builder } instance .
 * @ see Builder */
@ NonNull public static Builder builder ( @ LayoutRes int defaultEntryLayoutResId , @ IdRes int defaultEntryTextViewResId ) { } }

implementation: return builder ( SimpleEntry . create ( defaultEntryLayoutResId , defaultEntryTextViewResId ) ) ;


signature:
public class MarkwonAdapter { /** * Factory method to create a { @ link MarkwonAdapter } for evaluation purposes . Resulting
 * adapter will use default layout for all blocks . Default layout has no styling and should
 * be specified explicitly .
 * @ see # create ( Entry )
 * @ see # builder ( int , int )
 * @ see SimpleEntry */
@ NonNull public static MarkwonAdapter create ( @ LayoutRes int defaultEntryLayoutResId , @ IdRes int defaultEntryTextViewResId ) { } }

implementation: return builder ( defaultEntryLayoutResId , defaultEntryTextViewResId ) . build ( ) ;


signature:
public class MarkwonAdapter { /** * Factory method to create a { @ link MarkwonAdapter } that uses supplied entry to render all
 * nodes .
 * @ param defaultEntry { @ link Entry } to be used for node rendering
 * @ see # builder ( Entry ) */
@ NonNull public static MarkwonAdapter create ( @ NonNull Entry < ? extends Node , ? extends Holder > defaultEntry ) { } }

implementation: return builder ( defaultEntry ) . build ( ) ;


signature:
public class PriorityProcessorImpl { /** * we need to count the number of steps to a root node ( which has no parents ) */
private static int eval ( @ NonNull Class < ? extends MarkwonPlugin > who , @ NonNull Class < ? extends MarkwonPlugin > plugin , @ NonNull Map < Class < ? extends MarkwonPlugin > , Set < Class < ? extends MarkwonPlugin > > > map ) { } }

implementation:
// exact match
Set < Class < ? extends MarkwonPlugin > > set = map . get ( plugin ) ; if ( set == null ) { // let ' s try to find inexact type ( overridden / subclassed )
for ( Map . Entry < Class < ? extends MarkwonPlugin > , Set < Class < ? extends MarkwonPlugin > > > entry : map . entrySet ( ) ) { if ( plugin . isAssignableFrom ( entry . getKey ( ) ) ) { set = entry . getValue ( ) ; break ; } } if ( set == null ) { // unsatisfied dependency
throw new IllegalStateException ( String . format ( "Markwon unsatisfied dependency found. " + "Plugin `%s` comes after `%s` but it is not added." , who . getName ( ) , plugin . getName ( ) ) ) ; } } if ( set . isEmpty ( ) ) { return 0 ; } int value = 1 ; for ( Class < ? extends MarkwonPlugin > dependency : set ) { // a case when a plugin defines ` Priority . after ( getClass ) ` or being
// referenced by own dependency ( even indirect )
if ( who . equals ( dependency ) ) { throw new IllegalStateException ( String . format ( "Markwon plugin `%s` defined self " + "as a dependency or being referenced by own dependency (cycle)" , who . getName ( ) ) ) ; } value += eval ( who , dependency , map ) ; } return value ;


signature:
public class AsyncDrawable { /** * yeah */
public void setCallback2 ( @ Nullable Callback callback ) { } }

implementation:
this . callback = callback ; super . setCallback ( callback ) ; // if not null - > means we are attached
if ( callback != null ) { // as we have a placeholder now , it ' s important to check it our placeholder
// has a proper callback at this point . This is not required in most cases ,
// as placeholder should be static , but if it ' s not - > it can operate as usual
if ( result != null && result . getCallback ( ) == null ) { result . setCallback ( callback ) ; } loader . load ( destination , this ) ; } else { if ( result != null ) { result . setCallback ( null ) ; // let ' s additionally stop if it Animatable
if ( result instanceof Animatable ) { ( ( Animatable ) result ) . stop ( ) ; } } loader . cancel ( destination ) ; }


signature:
public class AsyncDrawable { /** * Remove result from this drawable ( for example , in case of cancellation )
 * @ since 3.0.1 */
public void clearResult ( ) { } }

implementation:
final Drawable result = this . result ; if ( result != null ) { result . setCallback ( null ) ; this . result = null ; // clear bounds
setBounds ( 0 , 0 , 0 , 0 ) ; }


signature:
public class Markwon { /** * Factory method to create a < em > minimally < / em > functional { @ link Markwon } instance . This
 * instance will have < strong > only < / strong > { @ link CorePlugin } registered . If you wish
 * to configure this instance more consider using { @ link # builder ( Context ) } method .
 * @ return { @ link Markwon } instance with only CorePlugin registered
 * @ since 3.0.0 */
@ NonNull public static Markwon create ( @ NonNull Context context ) { } }

implementation: return builder ( context ) . usePlugin ( CorePlugin . create ( ) ) . build ( ) ;


signature:
public class CoreActivity { /** * Create a simple instance of Markwon with only Core plugin registered
 * this will handle all _ natively _ supported by commonmark - java nodes :
 * < ul >
 * < li > StrongEmphasis < / li >
 * < li > Emphasis < / li >
 * < li > BlockQuote < / li >
 * < li > Code < / li >
 * < li > FencedCodeBlock < / li >
 * < li > IndentedCodeBlock < / li >
 * < li > ListItem ( bullet - list and ordered list < / li >
 * < li > Heading < / li >
 * < li > Link < / li >
 * < li > ThematicBreak < / li >
 * < li > Paragraph ( please note that there is no default span for a paragraph registered ) < / li >
 * < / ul >
 * and basic core functionality :
 * < ul >
 * < li > Append text < / li >
 * < li > Insert new lines ( soft and hard breaks ) < / li >
 * < / ul > */
private void step_1 ( ) { } }

implementation:
// short call
final Markwon markwon = Markwon . create ( this ) ; // this is the same as calling
final Markwon markwon2 = Markwon . builder ( this ) . usePlugin ( CorePlugin . create ( ) ) . build ( ) ;


signature:
public class CoreActivity { /** * To simply apply raw ( non - parsed ) markdown call { @ link Markwon # setMarkdown ( TextView , String ) } */
private void step_2 ( ) { } }

implementation:
// this is raw markdown
final String markdown = "Hello **markdown**!" ; final Markwon markwon = Markwon . create ( this ) ; // this will parse raw markdown and set parsed content to specified TextView
markwon . setMarkdown ( textView , markdown ) ;


signature:
public class CoreActivity { /** * To apply markdown in a different context ( other than textView ) use { @ link Markwon # toMarkdown ( String ) }
 * Please note that some features won ' t work unless they are used in a TextView context . For example
 * there might be misplaced ordered lists ( ordered list must have TextPaint in order to properly measure
 * its number ) . But also images and tables ( they belong to independent modules now ) . Images and tables
 * are using some work - arounds in order to be displayed in relatively limited context without proper way
 * of invalidation . But if a Toast for example is created with a custom view
 * ( { @ code new Toast ( this ) . setView ( . . . ) } ) and has access to a TextView everything < em > should < / em > work . */
private void step_3 ( ) { } }

implementation: final String markdown = "*Toast* __here__!\n\n> And a quote!" ; final Markwon markwon = Markwon . create ( this ) ; final Spanned spanned = markwon . toMarkdown ( markdown ) ; Toast . makeText ( this , spanned , Toast . LENGTH_LONG ) . show ( ) ;


signature:
public class CoreActivity { /** * To apply already parsed markdown use { @ link Markwon # setParsedMarkdown ( TextView , Spanned ) } */
private void step_4 ( ) { } }

implementation:
final String markdown = "This **is** pre-parsed [markdown](#)" ; final Markwon markwon = Markwon . create ( this ) ; // parse markdown to obtain a Node
final Node node = markwon . parse ( markdown ) ; // create a spanned content from parsed node
final Spanned spanned = markwon . render ( node ) ; // apply parsed markdown
markwon . setParsedMarkdown ( textView , spanned ) ;


signature:
public class TableEntry { /** * we will use gravity instead of textAlignment because min sdk is 16 ( textAlignment starts at 17) */
@ SuppressWarnings ( "WeakerAccess" ) @ SuppressLint ( "RtlHardcoded" ) @ VisibleForTesting static int textGravity ( @ NonNull Table . Alignment alignment , boolean cellTextCenterVertical ) { } }

implementation:
final int gravity ; switch ( alignment ) { case LEFT : gravity = Gravity . LEFT ; break ; case CENTER : gravity = Gravity . CENTER_HORIZONTAL ; break ; case RIGHT : gravity = Gravity . RIGHT ; break ; default : throw new IllegalStateException ( "Unknown table alignment: " + alignment ) ; } if ( cellTextCenterVertical ) { return gravity | Gravity . CENTER_VERTICAL ; } // do not center vertically
return gravity ;


signature:
public class MarkwonTheme { /** * Factory method to obtain a { @ link Builder } instance initialized with default values taken
 * from current application theme .
 * @ param context Context to obtain default styling values ( colors , etc )
 * @ return { @ link Builder } instance
 * @ since 1.0.0 */
@ NonNull public static Builder builderWithDefaults ( @ NonNull Context context ) { } }

implementation: final Dip dip = Dip . create ( context ) ; return new Builder ( ) . codeBlockMargin ( dip . toPx ( 8 ) ) . blockMargin ( dip . toPx ( 24 ) ) . blockQuoteWidth ( dip . toPx ( 4 ) ) . bulletListItemStrokeWidth ( dip . toPx ( 1 ) ) . headingBreakHeight ( dip . toPx ( 1 ) ) . thematicBreakHeight ( dip . toPx ( 4 ) ) ;


signature: public class CharacterReader { private void bufferUp ( ) { } }

implementation: if ( bufPos < bufSplitPoint ) return ; try { reader . skip ( bufPos ) ; reader . mark ( maxBufferLen ) ; final int read = reader . read ( charBuf ) ; reader . reset ( ) ; if ( read != - 1 ) { bufLength = read ; readerPos += bufPos ; bufPos = 0 ; bufMark = 0 ; bufSplitPoint = bufLength > readAheadLimit ? readAheadLimit : bufLength ; } } catch ( IOException e ) { throw new UncheckedIOException ( e ) ; }


signature:
public class CharacterReader { /** * Read characters until the first of any delimiters is found .
 * @ param chars delimiters to scan for
 * @ return characters read up to the matched delimiter . */
public String consumeToAny ( final char ... chars ) { } }

implementation: 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 ) : "" ;


signature:
public class AsyncDrawableScheduler { /** * must be called when text manually changed in TextView */
public static void unschedule ( @ NonNull TextView view ) { } }

implementation: for ( AsyncDrawable drawable : extract ( view ) ) { drawable . setCallback2 ( null ) ; }


signature:
public class TablePlugin { /** * Factory method to create a { @ link TablePlugin } with default { @ link TableTheme } instance
 * ( obtained via { @ link TableTheme # create ( Context ) } method )
 * @ see # create ( TableTheme )
 * @ see # create ( ThemeConfigure ) */
@ NonNull public static TablePlugin create ( @ NonNull Context context ) { } }

implementation: return new TablePlugin ( TableTheme . create ( context ) ) ;


signature:
public class Validate { /** * 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 noNullElements ( Object [ ] objects , String msg ) { } }

implementation: for ( Object obj : objects ) if ( obj == null ) throw new IllegalArgumentException ( msg ) ;


signature:
public class Validate { /** * Validates that the string is not empty
 * @ param string the string to test
 * @ param msg message to output if validation fails */
public static void notEmpty ( String string , String msg ) { } }

implementation: if ( string == null || string . length ( ) == 0 ) throw new IllegalArgumentException ( msg ) ;


signature:
public class SpannableBuilder { /** * This method will return all { @ link Span } spans that < em > overlap < / em > specified range ,
 * so if for example a 1 . . 9 range is specified some spans might have 0 . . 6 or 0 . . 10 start / end ranges .
 * < < < < < HEAD : markwon - core / src / main / java / ru / noties / markwon / SpannableBuilder . java
 * NB spans are returned in reversed order ( not in order that we store them internally )
 * NB spans are returned in reversed order ( no in order that we store them internally )
 * > > > > > master : markwon / src / main / java / ru / noties / markwon / SpannableBuilder . java
 * @ since 2.0.1 */
@ NonNull public List < Span > getSpans ( int start , int end ) { } }

implementation:
final int length = length ( ) ; if ( ! isPositionValid ( length , start , end ) ) { // we might as well throw here
return Collections . emptyList ( ) ; } // all requested
if ( start == 0 && length == end ) { // but also copy ( do not allow external modification )
final List < Span > list = new ArrayList < > ( spans ) ; Collections . reverse ( list ) ; return Collections . unmodifiableList ( list ) ; } final List < Span > list = new ArrayList < > ( 0 ) ; final Iterator < Span > iterator = spans . descendingIterator ( ) ; Span span ; while ( iterator . hasNext ( ) ) { span = iterator . next ( ) ; // we must execute 2 checks : if overlap with specified range or fully include it
// if span . start is > = range . start - > check if it ' s before range . end
// if span . end is < = end - > check if it ' s after range . start
if ( ( span . start >= start && span . start < end ) || ( span . end <= end && span . end > start ) || ( span . start < start && span . end > end ) ) { list . add ( span ) ; } } return Collections . unmodifiableList ( list ) ;


signature:
public class SpannableBuilder { /** * Simple method to create a SpannableStringBuilder , which is created anyway . Unlike { @ link # text ( ) }
 * method which returns the same SpannableStringBuilder there is no need to cast the resulting
 * CharSequence and makes the thing more explicit
 * @ since 2.0.0 */
@ NonNull public SpannableStringBuilder spannableStringBuilder ( ) { } }

implementation:
// okay , in order to not allow external modification and keep our spans order
// we should not return our builder
// plus , if this method was called - > all spans would be applied , which potentially
// breaks the order that we intend to use
// so , we will defensively copy builder
// as we do not expose builder and do no apply spans to it , we are safe to NOT to convert to String
final SpannableStringBuilderReversed reversed = new SpannableStringBuilderReversed ( builder ) ; // NB , as e are using Deque - > iteration will be started with last element
// so , spans will be appearing in the for loop in reverse order
for ( Span span : spans ) { reversed . setSpan ( span . what , span . start , span . end , span . flags ) ; } return reversed ;


signature:
public class ParseUtil { /** * Some SVG unit conversions . This is approximate */
static final Float convertUnits ( String name , XmlPullParser atts , float dpi , float width , float height ) { } }

implementation: String value = getStringAttr ( name , atts ) ; if ( value == null ) { return null ; } else if ( value . endsWith ( "px" ) ) { return Float . parseFloat ( value . substring ( 0 , value . length ( ) - 2 ) ) ; } else if ( value . endsWith ( "pt" ) ) { return Float . valueOf ( value . substring ( 0 , value . length ( ) - 2 ) ) * dpi / 72 ; } else if ( value . endsWith ( "pc" ) ) { return Float . valueOf ( value . substring ( 0 , value . length ( ) - 2 ) ) * dpi / 6 ; } else if ( value . endsWith ( "cm" ) ) { return Float . valueOf ( value . substring ( 0 , value . length ( ) - 2 ) ) * dpi / 2.54f ; } else if ( value . endsWith ( "mm" ) ) { return Float . valueOf ( value . substring ( 0 , value . length ( ) - 2 ) ) * dpi / 254 ; } else if ( value . endsWith ( "in" ) ) { return Float . valueOf ( value . substring ( 0 , value . length ( ) - 2 ) ) * dpi ; } else if ( value . endsWith ( "%" ) ) { Float result = Float . valueOf ( value . substring ( 0 , value . length ( ) - 1 ) ) ; float mult ; if ( name . contains ( "x" ) || name . equals ( "width" ) ) { mult = width / 100f ; } else if ( name . contains ( "y" ) || name . equals ( "height" ) ) { mult = height / 100f ; } else { mult = ( height + width ) / 2f ; } return result * mult ; } else { return Float . valueOf ( value ) ; }


signature:
public class PathParser { /** * This is where the hard - to - parse paths are handled .
 * Uppercase rules are absolute positions , lowercase are relative .
 * Types of path rules :
 * < ol >
 * < li > M / m - ( x y ) + - Move to ( without drawing )
 * < li > Z / z - ( no params ) - Close path ( back to starting point )
 * < li > L / l - ( x y ) + - Line to
 * < li > H / h - x + - Horizontal ine to
 * < li > V / v - y + - Vertical line to
 * < li > C / c - ( x1 y1 x2 y2 x y ) + - Cubic bezier to
 * < li > S / s - ( x2 y2 x y ) + - Smooth cubic bezier to ( shorthand that assumes the x2 , y2 from previous C / S is the x1 , y1 of this bezier )
 * < li > Q / q - ( x1 y1 x y ) + - Quadratic bezier to
 * < li > T / t - ( x y ) + - Smooth quadratic bezier to ( assumes previous control point is " reflection " of last one w . r . t . to current point )
 * < / ol >
 * Numbers are separate by whitespace , comma or nothing at all ( ! ) if they are self - delimiting , ( ie . begin with a - sign ) */
public static Path doPath ( String s ) { } }

implementation:
int n = s . length ( ) ; ParserHelper ph = new ParserHelper ( s ) ; ph . skipWhitespace ( ) ; Path p = new Path ( ) ; float lastX = 0 ; float lastY = 0 ; float lastX1 = 0 ; float lastY1 = 0 ; float contourInitialX = 0 ; float contourInitialY = 0 ; RectF r = new RectF ( ) ; char cmd = 'x' ; while ( ph . pos < n ) { char next = s . charAt ( ph . pos ) ; if ( ! Character . isDigit ( next ) && ! ( next == '.' ) && ! ( next == '-' ) ) { cmd = next ; ph . advance ( ) ; } else if ( cmd == 'M' ) { // implied command
cmd = 'L' ; } else if ( cmd == 'm' ) { // implied command
cmd = 'l' ; } else { // implied command
// ignore
} p . computeBounds ( r , true ) ; // Log . d ( TAG , " " + cmd + " " + r ) ;
// Util . debug ( " * Commands remaining : ' " + path + " ' . " ) ;
boolean wasCurve = false ; switch ( cmd ) { case 'M' : case 'm' : { float x = ph . nextFloat ( ) ; float y = ph . nextFloat ( ) ; if ( cmd == 'm' ) { p . rMoveTo ( x , y ) ; lastX += x ; lastY += y ; } else { p . moveTo ( x , y ) ; lastX = x ; lastY = y ; } contourInitialX = lastX ; contourInitialY = lastY ; break ; } case 'Z' : case 'z' : { // / p . lineTo ( contourInitialX , contourInitialY ) ;
p . close ( ) ; lastX = contourInitialX ; lastY = contourInitialY ; break ; } case 'L' : case 'l' : { float x = ph . nextFloat ( ) ; float y = ph . nextFloat ( ) ; if ( cmd == 'l' ) { p . rLineTo ( x , y ) ; lastX += x ; lastY += y ; } else { p . lineTo ( x , y ) ; lastX = x ; lastY = y ; } break ; } case 'H' : case 'h' : { float x = ph . nextFloat ( ) ; if ( cmd == 'h' ) { p . rLineTo ( x , 0 ) ; lastX += x ; } else { p . lineTo ( x , lastY ) ; lastX = x ; } break ; } case 'V' : case 'v' : { float y = ph . nextFloat ( ) ; if ( cmd == 'v' ) { p . rLineTo ( 0 , y ) ; lastY += y ; } else { p . lineTo ( lastX , y ) ; lastY = y ; } break ; } case 'C' : case 'c' : { wasCurve = true ; float x1 = ph . nextFloat ( ) ; float y1 = ph . nextFloat ( ) ; float x2 = ph . nextFloat ( ) ; float y2 = ph . nextFloat ( ) ; float x = ph . nextFloat ( ) ; float y = ph . nextFloat ( ) ; if ( cmd == 'c' ) { x1 += lastX ; x2 += lastX ; x += lastX ; y1 += lastY ; y2 += lastY ; y += lastY ; } p . cubicTo ( x1 , y1 , x2 , y2 , x , y ) ; lastX1 = x2 ; lastY1 = y2 ; lastX = x ; lastY = y ; break ; } case 'S' : case 's' : { wasCurve = true ; float x2 = ph . nextFloat ( ) ; float y2 = ph . nextFloat ( ) ; float x = ph . nextFloat ( ) ; float y = ph . nextFloat ( ) ; if ( cmd == 's' ) { x2 += lastX ; x += lastX ; y2 += lastY ; y += lastY ; } float x1 = 2 * lastX - lastX1 ; float y1 = 2 * lastY - lastY1 ; p . cubicTo ( x1 , y1 , x2 , y2 , x , y ) ; lastX1 = x2 ; lastY1 = y2 ; lastX = x ; lastY = y ; break ; } case 'A' : case 'a' : { float rx = ph . nextFloat ( ) ; float ry = ph . nextFloat ( ) ; float theta = ph . nextFloat ( ) ; int largeArc = ( int ) ph . nextFloat ( ) ; int sweepArc = ( int ) ph . nextFloat ( ) ; float x = ph . nextFloat ( ) ; float y = ph . nextFloat ( ) ; if ( cmd == 'a' ) { x += lastX ; y += lastY ; } drawArc ( p , lastX , lastY , x , y , rx , ry , theta , largeArc == 1 , sweepArc == 1 ) ; lastX = x ; lastY = y ; break ; } case 'T' : case 't' : { wasCurve = true ; float x = ph . nextFloat ( ) ; float y = ph . nextFloat ( ) ; if ( cmd == 't' ) { x += lastX ; y += lastY ; } float x1 = 2 * lastX - lastX1 ; float y1 = 2 * lastY - lastY1 ; p . cubicTo ( lastX , lastY , x1 , y1 , x , y ) ; lastX = x ; lastY = y ; lastX1 = x1 ; lastY1 = y1 ; break ; } case 'Q' : case 'q' : { wasCurve = true ; float x1 = ph . nextFloat ( ) ; float y1 = ph . nextFloat ( ) ; float x = ph . nextFloat ( ) ; float y = ph . nextFloat ( ) ; if ( cmd == 'q' ) { x += lastX ; y += lastY ; x1 += lastX ; y1 += lastY ; } p . cubicTo ( lastX , lastY , x1 , y1 , x , y ) ; lastX1 = x1 ; lastY1 = y1 ; lastX = x ; lastY = y ; break ; } default : Log . w ( TAG , "Invalid path command: " + cmd ) ; ph . advance ( ) ; } if ( ! wasCurve ) { lastX1 = lastX ; lastY1 = lastY ; } ph . skipWhitespace ( ) ; } return p ;


signature:
public class PathParser { /** * Elliptical arc implementation based on the SVG specification notes
 * Adapted from the Batik library ( Apache - 2 license ) by SAU */
private static void drawArc ( Path path , double x0 , double y0 , double x , double y , double rx , double ry , double angle , boolean largeArcFlag , boolean sweepFlag ) { } }

implementation:
double dx2 = ( x0 - x ) / 2.0 ; double dy2 = ( y0 - y ) / 2.0 ; angle = Math . toRadians ( angle % 360.0 ) ; double cosAngle = Math . cos ( angle ) ; double sinAngle = Math . sin ( angle ) ; double x1 = ( cosAngle * dx2 + sinAngle * dy2 ) ; double y1 = ( - sinAngle * dx2 + cosAngle * dy2 ) ; rx = Math . abs ( rx ) ; ry = Math . abs ( ry ) ; double Prx = rx * rx ; double Pry = ry * ry ; double Px1 = x1 * x1 ; double Py1 = y1 * y1 ; // check that radii are large enough
double radiiCheck = Px1 / Prx + Py1 / Pry ; if ( radiiCheck > 1 ) { rx = Math . sqrt ( radiiCheck ) * rx ; ry = Math . sqrt ( radiiCheck ) * ry ; Prx = rx * rx ; Pry = ry * ry ; } // Step 2 : Compute ( cx1 , cy1)
double sign = ( largeArcFlag == sweepFlag ) ? - 1 : 1 ; double sq = ( ( Prx * Pry ) - ( Prx * Py1 ) - ( Pry * Px1 ) ) / ( ( Prx * Py1 ) + ( Pry * Px1 ) ) ; sq = ( sq < 0 ) ? 0 : sq ; double coef = ( sign * Math . sqrt ( sq ) ) ; double cx1 = coef * ( ( rx * y1 ) / ry ) ; double cy1 = coef * - ( ( ry * x1 ) / rx ) ; double sx2 = ( x0 + x ) / 2.0 ; double sy2 = ( y0 + y ) / 2.0 ; double cx = sx2 + ( cosAngle * cx1 - sinAngle * cy1 ) ; double cy = sy2 + ( sinAngle * cx1 + cosAngle * cy1 ) ; // Step 4 : Compute the angleStart ( angle1 ) and the angleExtent ( dangle )
double ux = ( x1 - cx1 ) / rx ; double uy = ( y1 - cy1 ) / ry ; double vx = ( - x1 - cx1 ) / rx ; double vy = ( - y1 - cy1 ) / ry ; double p , n ; // Compute the angle start
n = Math . sqrt ( ( ux * ux ) + ( uy * uy ) ) ; p = ux ; // (1 * ux ) + ( 0 * uy )
sign = ( uy < 0 ) ? - 1.0 : 1.0 ; double angleStart = Math . toDegrees ( sign * Math . acos ( p / n ) ) ; // Compute the angle extent
n = Math . sqrt ( ( ux * ux + uy * uy ) * ( vx * vx + vy * vy ) ) ; p = ux * vx + uy * vy ; sign = ( ux * vy - uy * vx < 0 ) ? - 1.0 : 1.0 ; double angleExtent = Math . toDegrees ( sign * Math . acos ( p / n ) ) ; if ( ! sweepFlag && angleExtent > 0 ) { angleExtent -= 360f ; } else if ( sweepFlag && angleExtent < 0 ) { angleExtent += 360f ; } angleExtent %= 360f ; angleStart %= 360f ; RectF oval = new RectF ( ( float ) ( cx - rx ) , ( float ) ( cy - ry ) , ( float ) ( cx + rx ) , ( float ) ( cy + ry ) ) ; path . addArc ( oval , ( float ) angleStart , ( float ) angleExtent ) ;


signature:
public class TransformParser { /** * delims are whitespace or , ' s */
static Matrix parseTransform ( String s ) { } }

implementation:
// 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 ;


signature:
public class LazyBSONCallback { /** * This is a factory method pattern to create appropriate objects for BSON type DBPointer ( 0x0c ) .
 * @ param ns the namespace of the reference
 * @ param id the identifier of the reference
 * @ return object to be used as reference representation */
public Object createDBRef ( final String ns , final ObjectId id ) { } }

implementation: return new BasicBSONObject ( "$ns" , ns ) . append ( "$id" , id ) ;


signature:
public class BsonValueCodecProvider { /** * Get the { @ code BsonValue } subclass associated with the given { @ code BsonType } .
 * @ param bsonType the BsonType
 * @ return the class associated with the given type */
@ SuppressWarnings ( "unchecked" ) public static Class < ? extends BsonValue > getClassForBsonType ( final BsonType bsonType ) { } }

implementation: return ( Class < ? extends BsonValue > ) DEFAULT_BSON_TYPE_CLASS_MAP . get ( bsonType ) ;


signature:
public class GridFS { /** * 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 */
public DBCursor getFileList ( final DBObject query , final DBObject sort ) { } }

implementation: return filesCollection . find ( query ) . sort ( sort ) ;


signature:
public class GridFS { /** * 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 */
public List < GridFSDBFile > find ( final String filename , final DBObject sort ) { } }

implementation: return find ( new BasicDBObject ( "filename" , filename ) , sort ) ;


signature:
public class GridFS { /** * 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 */
public List < GridFSDBFile > find ( final DBObject query , final DBObject sort ) { } }

implementation: 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 ) ;


signature:
public class GridFS { /** * 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 */
public void remove ( final ObjectId id ) { } }

implementation: 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 ) ) ;


signature:
public class GridFS { /** * Removes all files matching the given query .
 * @ param query filter to apply
 * @ throws com . mongodb . MongoException if the operation fails */
public void remove ( final DBObject query ) { } }

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


signature:
public class GridFS { /** * Creates a file entry . After calling this method , you have to call { @ link com . mongodb . gridfs . GridFSInputFile # save ( ) } .
 * @ param file the file object
 * @ return a GridFS input file
 * @ throws IOException if there are problems reading { @ code file } */
public GridFSInputFile createFile ( final File file ) throws IOException { } }

implementation: return createFile ( new FileInputStream ( file ) , file . getName ( ) , true ) ;


signature:
public class GridFS { /** * Creates a file entry . After calling this method , you have to call { @ link com . mongodb . gridfs . GridFSInputFile # save ( ) } .
 * @ param in an inputstream containing the file ' s data
 * @ param filename the file name as stored in the db
 * @ param closeStreamOnPersist indicate the passed in input stream should be closed once the data chunk persisted
 * @ return a gridfs input file */
public GridFSInputFile createFile ( final InputStream in , final String filename , final boolean closeStreamOnPersist ) { } }

implementation: return new GridFSInputFile ( this , in , filename , closeStreamOnPersist ) ;


signature:
public class MongoClients { /** * Creates a new client with the given client settings .
 * < p > Note : Intended for driver and library authors to associate extra driver metadata with the connections . < / p >
 * @ param settings the settings
 * @ param mongoDriverInformation any driver information to associate with the MongoClient
 * @ return the client */
public static MongoClient create ( final MongoClientSettings settings , @ Nullable final MongoDriverInformation mongoDriverInformation ) { } }

implementation: MongoDriverInformation . Builder builder = mongoDriverInformation == null ? MongoDriverInformation . builder ( ) : MongoDriverInformation . builder ( mongoDriverInformation ) ; return new MongoClientImpl ( settings , builder . driverName ( "sync" ) . build ( ) ) ;


signature:
public class BasicBSONList { /** * 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 } */
@ Override public Object put ( final String key , final Object v ) { } }

implementation: return put ( _getInt ( key ) , v ) ;


signature:
public class BasicBSONList { /** * Puts a value at an index . This will fill any unset indexes less than { @ code index } with { @ code null } .
 * @ param key the index at which to insert the value
 * @ param value the value to insert
 * @ return the value */
public Object put ( final int key , final Object value ) { } }

implementation: while ( key >= size ( ) ) { add ( null ) ; } set ( key , value ) ; return value ;


signature:
public class BasicBSONList { /** * 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 } */
public Object get ( final String key ) { } }

implementation: int i = _getInt ( key ) ; if ( i < 0 ) { return null ; } if ( i >= size ( ) ) { return null ; } return get ( i ) ;


signature:
public class TypeData { /** * Creates a new builder for ClassTypeData
 * @ param type the class for the type
 * @ param < T > the type
 * @ return the builder */
public static < T > Builder < T > builder ( final Class < T > type ) { } }

implementation: return new Builder < T > ( notNull ( "type" , type ) ) ;


signature:
public class QuickTourAdmin { /** * Run this main method to see the output of this quick example .
 * @ param args takes an optional single argument for the connection string */
public static void main ( final String [ ] args ) { } }

implementation:
MongoClient mongoClient ; if ( args . length == 0 ) { // connect to the local database server
mongoClient = MongoClients . create ( ) ; } else { mongoClient = MongoClients . create ( args [ 0 ] ) ; } // get handle to " mydb " database
MongoDatabase database = mongoClient . getDatabase ( "mydb" ) ; database . drop ( ) ; // get a handle to the " test " collection
MongoCollection < Document > collection = database . getCollection ( "test" ) ; // drop all the data in it
collection . drop ( ) ; // getting a list of databases
for ( String name : mongoClient . listDatabaseNames ( ) ) { System . out . println ( name ) ; } // drop a database
mongoClient . getDatabase ( "databaseToBeDropped" ) . drop ( ) ; // create a collection
database . createCollection ( "cappedCollection" , new CreateCollectionOptions ( ) . capped ( true ) . sizeInBytes ( 0x100000 ) ) ; for ( String name : database . listCollectionNames ( ) ) { System . out . println ( name ) ; } // drop a collection :
collection . drop ( ) ; // create an ascending index on the " i " field
collection . createIndex ( Indexes . ascending ( "i" ) ) ; // list the indexes on the collection
for ( final Document index : collection . listIndexes ( ) ) { System . out . println ( index . toJson ( ) ) ; } // create a text index on the " content " field
collection . createIndex ( Indexes . text ( "content" ) ) ; collection . insertOne ( new Document ( "_id" , 0 ) . append ( "content" , "textual content" ) ) ; collection . insertOne ( new Document ( "_id" , 1 ) . append ( "content" , "additional content" ) ) ; collection . insertOne ( new Document ( "_id" , 2 ) . append ( "content" , "irrelevant content" ) ) ; // Find using the text index
long matchCount = collection . countDocuments ( text ( "textual content -irrelevant" ) ) ; System . out . println ( "Text search matches: " + matchCount ) ; // Find using the $ language operator
Bson textSearch = text ( "textual content -irrelevant" , new TextSearchOptions ( ) . language ( "english" ) ) ; matchCount = collection . countDocuments ( textSearch ) ; System . out . println ( "Text search matches (english): " + matchCount ) ; // Find the highest scoring match
Document projection = new Document ( "score" , new Document ( "$meta" , "textScore" ) ) ; Document myDoc = collection . find ( textSearch ) . projection ( projection ) . first ( ) ; System . out . println ( "Highest scoring document: " + myDoc . toJson ( ) ) ; // Run a command
Document buildInfo = database . runCommand ( new Document ( "buildInfo" , 1 ) ) ; System . out . println ( buildInfo ) ; // release resources
database . drop ( ) ; mongoClient . close ( ) ;


signature:
public class UuidCodecHelper { /** * reverse elements in the subarray data [ start : start + length ] */
public static void reverseByteArray ( final byte [ ] data , final int start , final int length ) { } }

implementation:
for ( int left = start , right = start + length - 1 ; left < right ; left ++ , right -- ) { // swap the values at the left and right indices
byte temp = data [ left ] ; data [ left ] = data [ right ] ; data [ right ] = temp ; }


signature:
public class ListIndexesOperation { /** * 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 */
public long getMaxTime ( final TimeUnit timeUnit ) { } }

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


signature:
public class MongoCompressor { /** * Gets the property with the given key .
 * @ param key the key
 * @ param defaultValue the default value
 * @ param < T > the property value type
 * @ return the property value , or the default value if the property is not defined */
@ SuppressWarnings ( "unchecked" ) @ Nullable public < T > T getProperty ( final String key , final T defaultValue ) { } }

implementation: notNull ( "key" , key ) ; T value = ( T ) properties . get ( key . toLowerCase ( ) ) ; return ( value == null && ! properties . containsKey ( key ) ) ? defaultValue : value ;


signature:
public class MongoCompressor { /** * Gets the property with the given key .
 * @ param key the key
 * @ param defaultValue the default value
 * @ param < T > the property value type
 * @ return the property value , or the default value if the property is not defined
 * @ throws IllegalArgumentException if the value and default value are null
 * @ since 3.7 */
public < T > T getPropertyNonNull ( final String key , final T defaultValue ) { } }

implementation: T value = getProperty ( key , defaultValue ) ; if ( value == null ) { throw new IllegalArgumentException ( ) ; } return value ;


signature:
public class MongoCompressor { /** * 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 */
public < T > MongoCompressor withProperty ( final String key , final T value ) { } }

implementation: return new MongoCompressor ( this , key , value ) ;


signature:
public class ReplicaSetStatus { /** * Get the name of the replica set .
 * @ return the name of the replica set . */
@ SuppressWarnings ( "deprecation" ) @ Nullable public String getName ( ) { } }

implementation: List < ServerDescription > any = getClusterDescription ( ) . getAnyPrimaryOrSecondary ( ) ; return any . isEmpty ( ) ? null : any . get ( 0 ) . getSetName ( ) ;


signature:
public class ReplicaSetStatus { /** * 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 */
@ SuppressWarnings ( "deprecation" ) @ Nullable public ServerAddress getMaster ( ) { } }

implementation: List < ServerDescription > primaries = getClusterDescription ( ) . getPrimaries ( ) ; return primaries . isEmpty ( ) ? null : primaries . get ( 0 ) . getAddress ( ) ;


signature:
public class ReplicaSetStatus { /** * 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 */
public boolean isMaster ( final ServerAddress serverAddress ) { } }

implementation: ServerAddress masterServerAddress = getMaster ( ) ; return masterServerAddress != null && masterServerAddress . equals ( serverAddress ) ;


signature:
public class ReplicaSetStatus { /** * 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 */
@ SuppressWarnings ( "deprecation" ) public int getMaxBsonObjectSize ( ) { } }

implementation: List < ServerDescription > primaries = getClusterDescription ( ) . getPrimaries ( ) ; return primaries . isEmpty ( ) ? ServerDescription . getDefaultMaxDocumentSize ( ) : primaries . get ( 0 ) . getMaxDocumentSize ( ) ;


signature:
public class QueryBuilder { /** * 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 } */
public QueryBuilder put ( final String key ) { } }

implementation: _currentKey = key ; if ( _query . get ( key ) == null ) { _query . put ( _currentKey , new NullObject ( ) ) ; } return this ;


signature:
public class QueryBuilder { /** * Equivalent of the $ within operand , used for geospatial operation
 * @ param x x coordinate
 * @ param y y coordinate
 * @ param radius radius
 * @ return { @ code this } */
public QueryBuilder withinCenter ( final double x , final double y , final double radius ) { } }

implementation: addOperand ( QueryOperators . WITHIN , new BasicDBObject ( QueryOperators . CENTER , asList ( asList ( x , y ) , radius ) ) ) ; return this ;


signature:
public class QueryBuilder { /** * Equivalent of the $ near operand
 * @ param x x coordinate
 * @ param y y coordinate
 * @ return { @ code this } */
public QueryBuilder near ( final double x , final double y ) { } }

implementation: addOperand ( QueryOperators . NEAR , asList ( x , y ) ) ; return this ;


signature:
public class QueryBuilder { /** * Equivalent of the $ near operand
 * @ param x x coordinate
 * @ param y y coordinate
 * @ param maxDistance max distance
 * @ return { @ code this } */
public QueryBuilder near ( final double x , final double y , final double maxDistance ) { } }

implementation: addOperand ( QueryOperators . NEAR , asList ( x , y ) ) ; addOperand ( QueryOperators . MAX_DISTANCE , maxDistance ) ; return this ;


signature:
public class QueryBuilder { /** * Equivalent of the $ nearSphere operand
 * @ param longitude coordinate in decimal degrees
 * @ param latitude coordinate in decimal degrees
 * @ return { @ code this } */
public QueryBuilder nearSphere ( final double longitude , final double latitude ) { } }

implementation: addOperand ( QueryOperators . NEAR_SPHERE , asList ( longitude , latitude ) ) ; return this ;


signature:
public class QueryBuilder { /** * Equivalent of the $ nearSphere operand
 * @ param longitude coordinate in decimal degrees
 * @ param latitude coordinate in decimal degrees
 * @ param maxDistance max spherical distance
 * @ return { @ code this } */
public QueryBuilder nearSphere ( final double longitude , final double latitude , final double maxDistance ) { } }

implementation: addOperand ( QueryOperators . NEAR_SPHERE , asList ( longitude , latitude ) ) ; addOperand ( QueryOperators . MAX_DISTANCE , maxDistance ) ; return this ;


signature:
public class QueryBuilder { /** * Equivalent of the $ centerSphere operand mostly intended for queries up to a few hundred miles or km .
 * @ param longitude coordinate in decimal degrees
 * @ param latitude coordinate in decimal degrees
 * @ param maxDistance max spherical distance
 * @ return { @ code this } */
public QueryBuilder withinCenterSphere ( final double longitude , final double latitude , final double maxDistance ) { } }

implementation: addOperand ( QueryOperators . WITHIN , new BasicDBObject ( QueryOperators . CENTER_SPHERE , asList ( asList ( longitude , latitude ) , maxDistance ) ) ) ; return this ;


signature:
public class QueryBuilder { /** * Equivalent to a $ within operand , based on a bounding box using represented by two corners
 * @ param x the x coordinate of the first box corner .
 * @ param y the y coordinate of the first box corner .
 * @ param x2 the x coordinate of the second box corner .
 * @ param y2 the y coordinate of the second box corner .
 * @ return { @ code this } */
@ SuppressWarnings ( "unchecked" ) public QueryBuilder withinBox ( final double x , final double y , final double x2 , final double y2 ) { } }

implementation: addOperand ( QueryOperators . WITHIN , new BasicDBObject ( QueryOperators . BOX , new Object [ ] { new Double [ ] { x , y } , new Double [ ] { x2 , y2 } } ) ) ; return this ;


signature:
public class QueryBuilder { /** * Equivalent to a $ within operand , based on a bounding polygon represented by an array of points
 * @ param points an array of Double [ ] defining the vertices of the search area
 * @ return { @ code this } */
public QueryBuilder withinPolygon ( final List < Double [ ] > points ) { } }

implementation: notNull ( "points" , points ) ; if ( points . isEmpty ( ) || points . size ( ) < 3 ) { throw new IllegalArgumentException ( "Polygon insufficient number of vertices defined" ) ; } addOperand ( QueryOperators . WITHIN , new BasicDBObject ( QueryOperators . POLYGON , convertToListOfLists ( points ) ) ) ; return this ;


signature:
public class QueryBuilder { /** * Equivalent to a $ text operand .
 * @ param search the search terms to apply to the text index .
 * @ param language the language to use .
 * @ return { @ code this }
 * @ mongodb . server . release 2.6 */
public QueryBuilder text ( final String search , @ Nullable final String language ) { } }

implementation: if ( _currentKey != null ) { throw new QueryBuilderException ( "The text operand may only occur at the top-level of a query. It does" + " not apply to a specific element, but rather to a document as a whole." ) ; } put ( QueryOperators . TEXT ) ; addOperand ( QueryOperators . SEARCH , search ) ; if ( language != null ) { addOperand ( QueryOperators . LANGUAGE , language ) ; } return this ;


signature:
public class QueryBuilder { /** * Equivalent to an $ or operand
 * @ param ors the list of conditions to or together
 * @ return { @ code this } */
@ SuppressWarnings ( "unchecked" ) public QueryBuilder or ( final DBObject ... ors ) { } }

implementation: List l = ( List ) _query . get ( QueryOperators . OR ) ; if ( l == null ) { l = new ArrayList ( ) ; _query . put ( QueryOperators . OR , l ) ; } Collections . addAll ( l , ors ) ; return this ;


signature:
public class QueryBuilder { /** * Equivalent to an $ and operand
 * @ param ands the list of conditions to and together
 * @ return { @ code this } */
@ SuppressWarnings ( "unchecked" ) public QueryBuilder and ( final DBObject ... ands ) { } }

implementation: List l = ( List ) _query . get ( QueryOperators . AND ) ; if ( l == null ) { l = new ArrayList ( ) ; _query . put ( QueryOperators . AND , l ) ; } Collections . addAll ( l , ands ) ; return this ;


signature:
public class QueryBuilder { /** * Creates a { @ code DBObject } query to be used for the driver ' s find operations
 * @ return { @ code this }
 * @ throws RuntimeException if a key does not have a matching operand */
public DBObject get ( ) { } }

implementation: for ( final String key : _query . keySet ( ) ) { if ( _query . get ( key ) instanceof NullObject ) { throw new QueryBuilderException ( "No operand for key:" + key ) ; } } return _query ;


signature:
public class Loggers { /** * Gets a logger with the given suffix appended on to { @ code PREFIX } , separated by a ' . ' .
 * @ param suffix the suffix for the logger
 * @ return the logger
 * @ see Loggers # PREFIX */
public static Logger getLogger ( final String suffix ) { } }

implementation: notNull ( "suffix" , suffix ) ; if ( suffix . startsWith ( "." ) || suffix . endsWith ( "." ) ) { throw new IllegalArgumentException ( "The suffix can not start or end with a '.'" ) ; } String name = PREFIX + "." + suffix ; if ( USE_SLF4J ) { return new SLF4JLogger ( name ) ; } else { return new JULLogger ( name ) ; }


signature:
public class ClientSessionImpl { /** * Apply majority write concern if the commit is to be retried . */
private void applyMajorityWriteConcernToTransactionOptions ( ) { } }

implementation: 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 ( ) ; }


signature:
public class Decimal128QuickTour { /** * Run this main method to see the output of this quick example .
 * @ param args takes an optional single argument for the connection string */
public static void main ( final String [ ] args ) { } }

implementation:
MongoClient mongoClient ; if ( args . length == 0 ) { // connect to the local database server
mongoClient = MongoClients . create ( ) ; } else { mongoClient = MongoClients . create ( args [ 0 ] ) ; } // get handle to " mydb " database
MongoDatabase database = mongoClient . getDatabase ( "mydb" ) ; // get a handle to the " test " collection
MongoCollection < Document > collection = database . getCollection ( "test" ) ; // drop all the data in it
collection . drop ( ) ; // make a document and insert it
Document doc = new Document ( "name" , "MongoDB" ) . append ( "amount1" , Decimal128 . parse ( ".10" ) ) . append ( "amount2" , new Decimal128 ( 42L ) ) . append ( "amount3" , new Decimal128 ( new BigDecimal ( ".200" ) ) ) ; collection . insertOne ( doc ) ; Document first = collection . find ( ) . filter ( Filters . eq ( "amount1" , new Decimal128 ( new BigDecimal ( ".10" ) ) ) ) . first ( ) ; Decimal128 amount3 = ( Decimal128 ) first . get ( "amount3" ) ; BigDecimal amount2AsBigDecimal = amount3 . bigDecimalValue ( ) ; System . out . println ( amount3 . toString ( ) ) ; System . out . println ( amount2AsBigDecimal . toString ( ) ) ;


signature:
public class CommandResult { /** * Gets the " ok " field , which is whether this command executed correctly or not .
 * @ return true if the command executed without error . */
public boolean ok ( ) { } }

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


signature:
public class CommandResult { /** * Gets the error message associated with a failed command .
 * @ return The error message or null */
@ Nullable public String getErrorMessage ( ) { } }

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


signature:
public class PropertyModelBuilder { /** * Sets the read annotations , to be applied when serializing to BSON
 * @ param annotations the read annotations
 * @ return this */
public PropertyModelBuilder < T > readAnnotations ( final List < Annotation > annotations ) { } }

implementation: this . readAnnotations = unmodifiableList ( notNull ( "annotations" , annotations ) ) ; return this ;


signature:
public class PropertyModelBuilder { /** * Creates the { @ link PropertyModel } .
 * @ return the PropertyModel */
@ SuppressWarnings ( { } }

implementation: "rawtypes" , "unchecked" } ) public PropertyModel < T > build ( ) { if ( ! isReadable ( ) && ! isWritable ( ) ) { throw new IllegalStateException ( format ( "Invalid PropertyModel '%s', neither readable or writable," , name ) ) ; } return new PropertyModel ( stateNotNull ( "propertyName" , name ) , readName , writeName , stateNotNull ( "typeData" , typeData ) , codec , stateNotNull ( "propertySerialization" , propertySerialization ) , discriminatorEnabled , stateNotNull ( "propertyAccessor" , propertyAccessor ) ) ;


signature:
public class InstantCodec { /** * { @ inheritDoc }
 * @ throws CodecConfigurationException if the Instant cannot be converted to a valid Bson DateTime . */
@ Override public void encode ( final BsonWriter writer , final Instant value , final EncoderContext encoderContext ) { } }

implementation: try { writer . writeDateTime ( value . toEpochMilli ( ) ) ; } catch ( ArithmeticException e ) { throw new CodecConfigurationException ( format ( "Unsupported Instant value '%s' could not be converted to milliseconds: %s" , value , e . getMessage ( ) ) , e ) ; }


signature:
public class LocalDateCodec { /** * { @ inheritDoc }
 * < p > Converts the { @ code LocalDate } to { @ link ZoneOffset # UTC } via { @ link LocalDate # atStartOfDay ( ZoneId ) } . < / p >
 * @ throws CodecConfigurationException if the LocalDate cannot be converted to a valid Bson DateTime . */
@ Override public void encode ( final BsonWriter writer , final LocalDate value , final EncoderContext encoderContext ) { } }

implementation: try { writer . writeDateTime ( value . atStartOfDay ( ZoneOffset . UTC ) . toInstant ( ) . toEpochMilli ( ) ) ; } catch ( ArithmeticException e ) { throw new CodecConfigurationException ( format ( "Unsupported LocalDate '%s' could not be converted to milliseconds: %s" , value , e . getMessage ( ) ) , e ) ; }


signature:
public class IndexHelper { /** * 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 List < String > getIndexNames ( final List < IndexModel > indexes , final CodecRegistry codecRegistry ) { } }

implementation: 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 ;


signature:
public class IndexHelper { /** * Convenience method to generate an index name from the set of fields it is over .
 * @ return a string representation of this index ' s fields */
public static String generateIndexName ( final BsonDocument index ) { } }

implementation: 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 ( ) ;


signature:
public class GridFSFile { /** * 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 */
@ Deprecated public void validate ( ) { } }

implementation:
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 ) ;


signature:
public class BsonTypeCodecMap { /** * Gets the Codec mapped to the given bson type .
 * @ param bsonType the non - null BsonType
 * @ return the non - null Codec */
public Codec < ? > get ( final BsonType bsonType ) { } }

implementation: 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 ;


signature:
public class MongoIterableSubscription { /** * Returns the batchSize to be used with the cursor .
 * < p > 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 . < / p >
 * @ return the batchSize to use */
private int calculateBatchSize ( ) { } }

implementation: 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 ; }


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

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


signature:
public class UnsignedLongs { /** * Equivalent of Long . compareUnsigned in Java 8.
 * @ param first the first value
 * @ param second the second value
 * @ return 0 if the values are equal , a value greater than zero if first is greater than second ,
 * a value less than zero if first is less than second */
public static int compare ( final long first , final long second ) { } }

implementation: return compareLongs ( first + Long . MIN_VALUE , second + Long . MIN_VALUE ) ;


signature:
public class UnsignedLongs { /** * Equivalent to Long . parseUnsignedLong in Java 8.
 * @ param string the string representation of an unsigned long
 * @ return the unsigned long */
public static long parse ( final String string ) { } }

implementation: 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 ;


signature:
public class UnsignedLongs { /** * number . */
private static boolean overflowInParse ( final long current , final int digit , final int radix ) { } }

implementation:
if ( current >= 0 ) { if ( current < MAX_VALUE_DIVS [ radix ] ) { return false ; } if ( current > MAX_VALUE_DIVS [ radix ] ) { return true ; } // current = = maxValueDivs [ radix ]
return ( digit > MAX_VALUE_MODS [ radix ] ) ; } // current < 0 : high bit is set
return true ;


signature:
public class UnsignedLongs { /** * Returns dividend / divisor , where the dividend and divisor are treated as unsigned 64 - bit quantities . */
private static long divide ( final long dividend , final long divisor ) { } }

implementation:
if ( divisor < 0 ) { // i . e . , divisor > = 2 ^ 63:
if ( compare ( dividend , divisor ) < 0 ) { return 0 ; // dividend < divisor
} else { return 1 ; // dividend > = divisor
} } // Optimization - use signed division if dividend < 2 ^ 63
if ( dividend >= 0 ) { return dividend / divisor ; } // Otherwise , approximate the quotient , check , and correct if necessary . Our approximation is
// guaranteed to be either exact or one less than the correct value . This follows from fact that
// floor ( floor ( x ) / i ) = = floor ( x / i ) for any real x and integer i ! = 0 . The proof is not quite
// trivial .
long quotient = ( ( dividend >>> 1 ) / divisor ) << 1 ; long rem = dividend - quotient * divisor ; return quotient + ( compare ( rem , divisor ) >= 0 ? 1 : 0 ) ;


signature:
public class UnsignedLongs { /** * Returns dividend % divisor , where the dividend and divisor are treated as unsigned 64 - bit * quantities . */
private static long remainder ( final long dividend , final long divisor ) { } }

implementation:
if ( divisor < 0 ) { // i . e . , divisor > = 2 ^ 63:
if ( compare ( dividend , divisor ) < 0 ) { return dividend ; // dividend < divisor
} else { return dividend - divisor ; // dividend > = divisor
} } // Optimization - use signed modulus if dividend < 2 ^ 63
if ( dividend >= 0 ) { return dividend % divisor ; } // Otherwise , approximate the quotient , check , and correct if necessary . Our approximation is
// guaranteed to be either exact or one less than the correct value . This follows from the fact
// that floor ( floor ( x ) / i ) = = floor ( x / i ) for any real x and integer i ! = 0 . The proof is not
// quite trivial .
long quotient = ( ( dividend >>> 1 ) / divisor ) << 1 ; long rem = dividend - quotient * divisor ; return rem - ( compare ( rem , divisor ) >= 0 ? divisor : 0 ) ;


signature:
public class DecoderContext { /** * 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 */
public < T > T decodeWithChildContext ( final Decoder < T > decoder , final BsonReader reader ) { } }

implementation: return decoder . decode ( reader , DEFAULT_CONTEXT ) ;


signature:
public class AggregateToCollectionOperation { /** * Sets the maximum execution time on the server for this operation .
 * @ param maxTime the max time
 * @ param timeUnit the time unit , which may not be null
 * @ return this
 * @ mongodb . driver . manual reference / method / cursor . maxTimeMS / # cursor . maxTimeMS Max Time */
public AggregateToCollectionOperation maxTime ( final long maxTime , final TimeUnit timeUnit ) { } }


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

implementation: return new AggregateExplainOperation ( namespace , pipeline ) . allowDiskUse ( allowDiskUse ) . maxTime ( maxTimeMS , TimeUnit . MILLISECONDS ) . hint ( hint ) ;


signature:
public class AbstractBsonWriter { /** * Returns the next valid state for this writer . For example , transitions from { @ link State # VALUE } to { @ link State # NAME } once a value
 * is written .
 * @ return the next { @ code State } */
protected State getNextState ( ) { } }

implementation: if ( getContext ( ) . getContextType ( ) == BsonContextType . ARRAY ) { return State . VALUE ; } else { return State . NAME ; }


signature:
public class AbstractBsonWriter { /** * 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 . */
protected boolean checkState ( final State [ ] validStates ) { } }

implementation: for ( final State cur : validStates ) { if ( cur == getState ( ) ) { return true ; } } return false ;


signature:
public class AbstractBsonWriter { /** * Checks the writer is in the correct state . If the writer ' s current state is in the list of given states , this method will complete
 * without exception . Throws an { @ link java . lang . IllegalStateException } if the writer is closed . Throws BsonInvalidOperationException
 * if the method is trying to do something that is not permitted in the current state .
 * @ param methodName the name of the method being performed that checks are being performed for
 * @ param validStates the list of valid states for this operation
 * @ see # throwInvalidState ( String , org . bson . AbstractBsonWriter . State . . . ) */
protected void checkPreconditions ( final String methodName , final State ... validStates ) { } }

implementation: if ( isClosed ( ) ) { throw new IllegalStateException ( "BsonWriter is closed" ) ; } if ( ! checkState ( validStates ) ) { throwInvalidState ( methodName , validStates ) ; }


signature:
public class AbstractBsonWriter { /** * Throws a { @ link BsonInvalidOperationException } when the method called is not valid for the current state .
 * @ param methodName The name of the method .
 * @ param validStates The valid states .
 * @ throws BsonInvalidOperationException when the method called is not valid for the current state . */
protected void throwInvalidState ( final String methodName , final State ... validStates ) { } }

implementation:
if ( state == State . INITIAL || state == State . SCOPE_DOCUMENT || state == State . DONE ) { if ( ! methodName . startsWith ( "end" ) && ! methodName . equals ( "writeName" ) ) { // NOPMD
// NOPMD collapsing these if statements will not aid readability
String typeName = methodName . substring ( 5 ) ; if ( typeName . startsWith ( "start" ) ) { typeName = typeName . substring ( 5 ) ; } String article = "A" ; if ( Arrays . asList ( 'A' , 'E' , 'I' , 'O' , 'U' ) . contains ( typeName . charAt ( 0 ) ) ) { article = "An" ; } throw new BsonInvalidOperationException ( format ( "%s %s value cannot be written to the root level of a BSON document." , article , typeName ) ) ; } } String validStatesString = StringUtils . join ( " or " , Arrays . asList ( validStates ) ) ; throw new BsonInvalidOperationException ( format ( "%s can only be called when State is %s, not when State is %s" , methodName , validStatesString , state ) ) ;


signature:
public class AbstractBsonWriter { /** * 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 */
public void pipe ( final BsonReader reader , final List < BsonElement > extraElements ) { } }

implementation: notNull ( "reader" , reader ) ; notNull ( "extraElements" , extraElements ) ; pipeDocument ( reader , extraElements ) ;


signature:
public class AbstractBsonWriter { /** * Pipe a list of extra element to this writer
 * @ param extraElements the extra elements */
protected void pipeExtraElements ( final List < BsonElement > extraElements ) { } }

implementation: notNull ( "extraElements" , extraElements ) ; for ( BsonElement cur : extraElements ) { writeName ( cur . getName ( ) ) ; pipeValue ( cur . getValue ( ) ) ; }


signature:
public class HexUtils { /** * Converts the given byte buffer to a hexadecimal string using { @ link java . lang . Integer # toHexString ( int ) } .
 * @ param bytes the bytes to convert to hex
 * @ return a String containing the hex representation of the given bytes . */
public static String toHex ( final byte [ ] bytes ) { } }

implementation: StringBuilder sb = new StringBuilder ( ) ; for ( final byte b : bytes ) { String s = Integer . toHexString ( 0xff & b ) ; if ( s . length ( ) < 2 ) { sb . append ( "0" ) ; } sb . append ( s ) ; } return sb . toString ( ) ;


signature:
public class HexUtils { /** * Produce hex representation of the MD5 digest of a byte array .
 * @ param data bytes to digest
 * @ return hex string of the MD5 digest */
public static String hexMD5 ( final byte [ ] data ) { } }

implementation: try { MessageDigest md5 = MessageDigest . getInstance ( "MD5" ) ; md5 . reset ( ) ; md5 . update ( data ) ; byte [ ] digest = md5 . digest ( ) ; return toHex ( digest ) ; } catch ( NoSuchAlgorithmException e ) { throw new RuntimeException ( "Error - this implementation of Java doesn't support MD5." ) ; }


signature:
public class HexUtils { /** * Produce hex representation of the MD5 digest of a byte array .
 * @ param buf byte buffer containing the bytes to digest
 * @ param offset the position to start reading bytes from
 * @ param len the number of bytes to read from the buffer
 * @ return hex string of the MD5 digest */
public static String hexMD5 ( final ByteBuffer buf , final int offset , final int len ) { } }

implementation: byte [ ] b = new byte [ len ] ; for ( int i = 0 ; i < len ; i ++ ) { b [ i ] = buf . get ( offset + i ) ; } return hexMD5 ( b ) ;


signature:
public class ObjectId { /** * Checks if a string could be an { @ code ObjectId } .
 * @ param hexString a potential ObjectId as a String .
 * @ return whether the string could be an object id
 * @ throws IllegalArgumentException if hexString is null */
public static boolean isValid ( final String hexString ) { } }

implementation: if ( hexString == null ) { throw new IllegalArgumentException ( ) ; } int len = hexString . length ( ) ; if ( len != 24 ) { return false ; } for ( int i = 0 ; i < len ; i ++ ) { char c = hexString . charAt ( i ) ; if ( c >= '0' && c <= '9' ) { continue ; } if ( c >= 'a' && c <= 'f' ) { continue ; } if ( c >= 'A' && c <= 'F' ) { continue ; } return false ; } return true ;


signature:
public class ObjectId { /** * Convert to a byte array . Note that the numbers are stored in big - endian order .
 * @ return the byte array */
public byte [ ] toByteArray ( ) { } }

implementation: ByteBuffer buffer = ByteBuffer . allocate ( OBJECT_ID_LENGTH ) ; putToByteBuffer ( buffer ) ; return buffer . array ( ) ; // using . allocate ensures there is a backing array that can be returned


signature:
public class ObjectId { /** * 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 */
public void putToByteBuffer ( final ByteBuffer buffer ) { } }

implementation: 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 ) ) ;


signature:
public class ObjectId { /** * Converts this instance into a 24 - byte hexadecimal string representation .
 * @ return a string representation of the ObjectId in hexadecimal format */
public String toHexString ( ) { } }

implementation: 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 ) ;


signature:
public class ObjectId { /** * < p > Creates an ObjectId using time , machine and inc values . The Java driver used to create all ObjectIds this way , but it does not
 * match the < a href = " http : / / docs . mongodb . org / manual / reference / object - id / " > ObjectId specification < / a > , which requires four values , not
 * three . This major release of the Java driver conforms to the specification , but still supports clients that are relying on the
 * behavior of the previous major release by providing this explicit factory method that takes three parameters instead of four . < / p >
 * < p > Ordinary users of the driver will not need this method . It ' s only for those that have written there own BSON decoders . < / p >
 * < p > NOTE : This will not break any application that use ObjectIds . The 12 - byte representation will be round - trippable from old to new
 * driver releases . < / p >
 * @ param time time in seconds
 * @ param machine machine ID
 * @ param inc incremental value
 * @ return a new { @ code ObjectId } created from the given values
 * @ since 2.12.0
 * @ deprecated Use { @ link # ObjectId ( int , int ) } instead */
@ Deprecated public static ObjectId createFromLegacyFormat ( final int time , final int machine , final int inc ) { } }

implementation: return new ObjectId ( time , machine , inc ) ;


signature:
public class BsonDocumentCodec { /** * This method may be overridden to change the behavior of reading the current value from the given { @ code BsonReader } . It is required
 * that the value be fully consumed before returning .
 * @ param reader the read to read the value from
 * @ param decoderContext the context
 * @ return the non - null value read from the reader */
protected BsonValue readValue ( final BsonReader reader , final DecoderContext decoderContext ) { } }

implementation: return ( BsonValue ) bsonTypeCodecMap . get ( reader . getCurrentBsonType ( ) ) . decode ( reader , decoderContext ) ;


signature:
public class ServerDescription { /** * Returns true if the server has the given tags . A server of either type { @ code ServerType . STANDALONE } or { @ code
 * ServerType . SHARD _ ROUTER } is considered to have all tags , so this method will always return true for instances of either of those
 * types .
 * @ param desiredTags the tags
 * @ return true if this server has the given tags */
public boolean hasTags ( final TagSet desiredTags ) { } }

implementation: if ( ! ok ) { return false ; } if ( type == STANDALONE || type == SHARD_ROUTER ) { return true ; } return tagSet . containsAll ( desiredTags ) ;


signature:
public class ServerDescription { /** * Returns a short , pretty description for this ServerDescription .
 * @ return a String containing the most pertinent information about this ServerDescription */
public String getShortDescription ( ) { } }

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


signature:
public class BasicDBObjectBuilder { /** * Creates a builder initialized with the given key / value .
 * @ param key The field name
 * @ param val The value
 * @ return the new builder */
public static BasicDBObjectBuilder start ( final String key , final Object val ) { } }

implementation: return ( new BasicDBObjectBuilder ( ) ) . add ( key , val ) ;


signature:
public class BasicDBObjectBuilder { /** * Creates an object builder from an existing map of key value pairs .
 * @ param documentAsMap a document in Map form .
 * @ return the new builder */
@ SuppressWarnings ( "unchecked" ) public static BasicDBObjectBuilder start ( final Map documentAsMap ) { } }

implementation: 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 ;


signature:
public class BasicDBObjectBuilder { /** * Appends the key / value to the active object
 * @ param key the field name
 * @ param val the value of the field
 * @ return { @ code this } so calls can be chained */
public BasicDBObjectBuilder append ( final String key , final Object val ) { } }

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


signature:
public class BasicDBObjectBuilder { /** * 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 */
public BasicDBObjectBuilder push ( final String key ) { } }

implementation: BasicDBObject o = new BasicDBObject ( ) ; _cur ( ) . put ( key , o ) ; _stack . addLast ( o ) ; return this ;


signature:
public class BulkWriteBatchCombiner { /** * Add a result
 * @ param result the result
 * @ param indexMap the index map */
public void addResult ( final BulkWriteResult result , final IndexMap indexMap ) { } }

implementation: insertedCount += result . getInsertedCount ( ) ; matchedCount += result . getMatchedCount ( ) ; deletedCount += result . getDeletedCount ( ) ; modifiedCount += result . getModifiedCount ( ) ; mergeUpserts ( result . getUpserts ( ) , indexMap ) ;


signature:
public class BulkWriteBatchCombiner { /** * Add an error result
 * @ param exception the exception
 * @ param indexMap the index map */
public void addErrorResult ( final MongoBulkWriteException exception , final IndexMap indexMap ) { } }

implementation: addResult ( exception . getWriteResult ( ) , indexMap ) ; mergeWriteErrors ( exception . getWriteErrors ( ) , indexMap ) ; mergeWriteConcernError ( exception . getWriteConcernError ( ) ) ;


signature:
public class BulkWriteBatchCombiner { /** * Add a write error result
 * @ param writeError the write error
 * @ param indexMap the index map */
public void addWriteErrorResult ( final BulkWriteError writeError , final IndexMap indexMap ) { } }

implementation: notNull ( "writeError" , writeError ) ; mergeWriteErrors ( asList ( writeError ) , indexMap ) ;


signature:
public class BulkWriteBatchCombiner { /** * 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 void addErrorResult ( final List < BulkWriteError > writeErrors , final WriteConcernError writeConcernError , final IndexMap indexMap ) { } }

implementation: mergeWriteErrors ( writeErrors , indexMap ) ; mergeWriteConcernError ( writeConcernError ) ;


signature:
public class BulkWriteBatchCombiner { /** * Gets the combined errors as an exception
 * @ return the bulk write exception , or null if there were no errors */
public MongoBulkWriteException getError ( ) { } }

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


signature:
public class Node { /** * compareAndSet next link */
private boolean casNext ( Node < E > cmp , Node < E > val ) { } }

implementation: return compareAndSet ( cmp , val ) ;


signature:
public class Node { /** * Returns next node , ignoring deletion marker . */
private Node < E > nextNonmarker ( ) { } }

implementation: Node < E > f = getNext ( ) ; return ( f == null || ! f . isMarker ( ) ) ? f : f . getNext ( ) ;


signature:
public class Node { /** * 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 */
Node < E > successor ( ) { } }

implementation:
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 ; }


signature:
public class Node { /** * Returns the apparent predecessor of target by searching
 * forward for it , starting at this node , patching up pointers
 * while traversing . Used by predecessor ( ) .
 * @ return target ' s predecessor , or null if not found */
private Node < E > findPredecessorOf ( Node < E > target ) { } }

implementation: Node < E > n = this ; for ( ; ; ) { Node < E > f = n . successor ( ) ; if ( f == target ) return n ; if ( f == null ) return null ; n = f ; }


signature:
public class Node { /** * 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 */
Node < E > predecessor ( ) { } }

implementation: 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 ; }


signature:
public class Node { /** * Returns the next node containing a nondeleted user element .
 * Use for forward list traversal .
 * @ return successor , or null if no such */
Node < E > forward ( ) { } }

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


signature:
public class Node { /** * 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 */
Node < E > back ( ) { } }

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


signature:
public class Node { /** * 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 */
Node < E > append ( E element ) { } }

implementation:
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 ; } }


signature:
public class Node { /** * 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 */
Node < E > prepend ( E element ) { } }

implementation:
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 ; } }


signature:
public class Node { /** * Tries to mark this node as deleted , failing if already
 * deleted or if this node is header or trailer .
 * @ return true if successful */
boolean delete ( ) { } }

implementation: 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 ;


signature:
public class Node { /** * 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 */
Node < E > replace ( E newElement ) { } }

implementation:
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 ; } }