idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
158,600
private static void selectJsonRow ( CqlSession session ) { // Reading the whole row as a JSON object Statement stmt = selectFrom ( "examples" , "json_jsr353_row" ) . json ( ) . all ( ) . whereColumn ( "id" ) . in ( literal ( 1 ) , literal ( 2 ) ) . build ( ) ; ResultSet rows = session . execute ( stmt ) ; for ( Row row : rows ) { // SELECT JSON returns only one column for each row, of type VARCHAR, // containing the row as a JSON payload. // Note that the codec requires that the type passed to the get() method // be always JsonStructure, and not a subclass of it, such as JsonObject, // hence the need to downcast to JsonObject manually JsonObject user = ( JsonObject ) row . get ( 0 , JsonStructure . class ) ; System . out . printf ( "Retrieved user: %s%n" , user ) ; } }
Retrieving User instances from table rows using SELECT JSON
219
10
158,601
private static ByteBuffer readAll ( File file ) throws IOException { try ( FileInputStream inputStream = new FileInputStream ( file ) ) { FileChannel channel = inputStream . getChannel ( ) ; ByteBuffer buffer = ByteBuffer . allocate ( ( int ) channel . size ( ) ) ; channel . read ( buffer ) ; buffer . flip ( ) ; return buffer ; } }
probably not insert it into Cassandra either ; )
80
9
158,602
public static int minimumRequestSize ( Request request ) { // Header and payload are common inside a Frame at the protocol level // Frame header has a fixed size of 9 for protocol version >= V3, which includes Frame flags // size int size = FrameCodec . headerEncodedSize ( ) ; if ( ! request . getCustomPayload ( ) . isEmpty ( ) ) { // Custom payload is not supported in v3, but assume user won't have a custom payload set if // they use this version size += PrimitiveSizes . sizeOfBytesMap ( request . getCustomPayload ( ) ) ; } return size ; }
Returns a common size for all kinds of Request implementations .
131
11
158,603
public static int sizeOfSimpleStatementValues ( SimpleStatement simpleStatement , ProtocolVersion protocolVersion , CodecRegistry codecRegistry ) { int size = 0 ; if ( ! simpleStatement . getPositionalValues ( ) . isEmpty ( ) ) { List < ByteBuffer > positionalValues = new ArrayList <> ( simpleStatement . getPositionalValues ( ) . size ( ) ) ; for ( Object value : simpleStatement . getPositionalValues ( ) ) { positionalValues . add ( Conversions . encode ( value , codecRegistry , protocolVersion ) ) ; } size += Values . sizeOfPositionalValues ( positionalValues ) ; } else if ( ! simpleStatement . getNamedValues ( ) . isEmpty ( ) ) { Map < String , ByteBuffer > namedValues = new HashMap <> ( simpleStatement . getNamedValues ( ) . size ( ) ) ; for ( Map . Entry < CqlIdentifier , Object > value : simpleStatement . getNamedValues ( ) . entrySet ( ) ) { namedValues . put ( value . getKey ( ) . asInternal ( ) , Conversions . encode ( value . getValue ( ) , codecRegistry , protocolVersion ) ) ; } size += Values . sizeOfNamedValues ( namedValues ) ; } return size ; }
Returns the size in bytes of a simple statement s values depending on whether the values are named or positional .
273
21
158,604
public static Integer sizeOfInnerBatchStatementInBytes ( BatchableStatement statement , ProtocolVersion protocolVersion , CodecRegistry codecRegistry ) { int size = 0 ; size += PrimitiveSizes . BYTE ; // for each inner statement, there is one byte for the "kind": prepared or string if ( statement instanceof SimpleStatement ) { size += PrimitiveSizes . sizeOfLongString ( ( ( SimpleStatement ) statement ) . getQuery ( ) ) ; size += sizeOfSimpleStatementValues ( ( ( SimpleStatement ) statement ) , protocolVersion , codecRegistry ) ; } else if ( statement instanceof BoundStatement ) { size += PrimitiveSizes . sizeOfShortBytes ( ( ( BoundStatement ) statement ) . getPreparedStatement ( ) . getId ( ) . array ( ) ) ; size += sizeOfBoundStatementValues ( ( ( BoundStatement ) statement ) ) ; } return size ; }
The size of a statement inside a batch query is different from the size of a complete Statement . The inner batch statements only include the query or prepared ID and the values of the statement .
194
37
158,605
public List < VertexT > topologicalSort ( ) { Preconditions . checkState ( ! wasSorted ) ; wasSorted = true ; Queue < VertexT > queue = new ArrayDeque <> ( ) ; for ( Map . Entry < VertexT , Integer > entry : vertices . entrySet ( ) ) { if ( entry . getValue ( ) == 0 ) { queue . add ( entry . getKey ( ) ) ; } } List < VertexT > result = Lists . newArrayList ( ) ; while ( ! queue . isEmpty ( ) ) { VertexT vertex = queue . remove ( ) ; result . add ( vertex ) ; for ( VertexT successor : adjacencyList . get ( vertex ) ) { if ( decrementAndGetCount ( successor ) == 0 ) { queue . add ( successor ) ; } } } if ( result . size ( ) != vertices . size ( ) ) { throw new IllegalArgumentException ( "failed to perform topological sort, graph has a cycle" ) ; } return result ; }
one - time use only calling this multiple times on the same graph won t work
229
16
158,606
public void cancel ( ResponseCallback responseCallback ) { // To avoid creating an extra message, we adopt the convention that writing the callback // directly means cancellation writeCoalescer . writeAndFlush ( channel , responseCallback ) . addListener ( UncaughtExceptions :: log ) ; }
Cancels a callback indicating that the client that wrote it is no longer interested in the answer .
58
20
158,607
private void computeEvents ( KeyspaceMetadata oldKeyspace , KeyspaceMetadata newKeyspace , ImmutableList . Builder < Object > events ) { if ( oldKeyspace == null ) { events . add ( KeyspaceChangeEvent . created ( newKeyspace ) ) ; } else { if ( ! shallowEquals ( oldKeyspace , newKeyspace ) ) { events . add ( KeyspaceChangeEvent . updated ( oldKeyspace , newKeyspace ) ) ; } computeChildEvents ( oldKeyspace , newKeyspace , events ) ; } }
Computes the exact set of events to emit when a keyspace has changed .
117
16
158,608
public void receive ( IncomingT element ) { assert adminExecutor . inEventLoop ( ) ; if ( stopped ) { return ; } if ( window . isZero ( ) || maxEvents == 1 ) { LOG . debug ( "Received {}, flushing immediately (window = {}, maxEvents = {})" , element , window , maxEvents ) ; onFlush . accept ( coalescer . apply ( ImmutableList . of ( element ) ) ) ; } else { currentBatch . add ( element ) ; if ( currentBatch . size ( ) == maxEvents ) { LOG . debug ( "Received {}, flushing immediately (because {} accumulated events)" , element , maxEvents ) ; flushNow ( ) ; } else { LOG . debug ( "Received {}, scheduling next flush in {}" , element , window ) ; scheduleFlush ( ) ; } } }
This must be called on eventExecutor too .
186
10
158,609
@ NonNull public CompletionStage < SessionT > buildAsync ( ) { CompletionStage < CqlSession > buildStage = buildDefaultSessionAsync ( ) ; CompletionStage < SessionT > wrapStage = buildStage . thenApply ( this :: wrap ) ; // thenApply does not propagate cancellation (!) CompletableFutures . propagateCancellation ( wrapStage , buildStage ) ; return wrapStage ; }
Creates the session with the options set by this builder .
89
12
158,610
private boolean getRow ( ) { try { rowCache . clear ( ) ; while ( rowCache . size ( ) < rowCacheSize && parser . hasNext ( ) ) { handleEvent ( parser . nextEvent ( ) ) ; } rowCacheIterator = rowCache . iterator ( ) ; return rowCacheIterator . hasNext ( ) ; } catch ( XMLStreamException e ) { throw new ParseException ( "Error reading XML stream" , e ) ; } }
Read through a number of rows equal to the rowCacheSize field or until there is no more data to read
97
22
158,611
void setFormatString ( StartElement startElement , StreamingCell cell ) { Attribute cellStyle = startElement . getAttributeByName ( new QName ( "s" ) ) ; String cellStyleString = ( cellStyle != null ) ? cellStyle . getValue ( ) : null ; XSSFCellStyle style = null ; if ( cellStyleString != null ) { style = stylesTable . getStyleAt ( Integer . parseInt ( cellStyleString ) ) ; } else if ( stylesTable . getNumCellStyles ( ) > 0 ) { style = stylesTable . getStyleAt ( 0 ) ; } if ( style != null ) { cell . setNumericFormatIndex ( style . getDataFormat ( ) ) ; String formatString = style . getDataFormatString ( ) ; if ( formatString != null ) { cell . setNumericFormat ( formatString ) ; } else { cell . setNumericFormat ( BuiltinFormats . getBuiltinFormat ( cell . getNumericFormatIndex ( ) ) ) ; } } else { cell . setNumericFormatIndex ( null ) ; cell . setNumericFormat ( null ) ; } }
Read the numeric format string out of the styles table for this cell . Stores the result in the Cell .
244
21
158,612
private Supplier getFormatterForType ( String type ) { switch ( type ) { case "s" : //string stored in shared table if ( ! lastContents . isEmpty ( ) ) { int idx = Integer . parseInt ( lastContents ) ; return new StringSupplier ( new XSSFRichTextString ( sst . getEntryAt ( idx ) ) . toString ( ) ) ; } return new StringSupplier ( lastContents ) ; case "inlineStr" : //inline string (not in sst) case "str" : return new StringSupplier ( new XSSFRichTextString ( lastContents ) . toString ( ) ) ; case "e" : //error type return new StringSupplier ( "ERROR: " + lastContents ) ; case "n" : //numeric type if ( currentCell . getNumericFormat ( ) != null && lastContents . length ( ) > 0 ) { // the formatRawCellContents operation incurs a significant overhead on large sheets, // and we want to defer the execution of this method until the value is actually needed. // it is not needed in all cases.. final String currentLastContents = lastContents ; final int currentNumericFormatIndex = currentCell . getNumericFormatIndex ( ) ; final String currentNumericFormat = currentCell . getNumericFormat ( ) ; return new Supplier ( ) { String cachedContent ; @ Override public Object getContent ( ) { if ( cachedContent == null ) { cachedContent = dataFormatter . formatRawCellContents ( Double . parseDouble ( currentLastContents ) , currentNumericFormatIndex , currentNumericFormat ) ; } return cachedContent ; } } ; } else { return new StringSupplier ( lastContents ) ; } default : return new StringSupplier ( lastContents ) ; } }
Tries to format the contents of the last contents appropriately based on the provided type and the discovered numeric format .
384
22
158,613
String unformattedContents ( ) { switch ( currentCell . getType ( ) ) { case "s" : //string stored in shared table if ( ! lastContents . isEmpty ( ) ) { int idx = Integer . parseInt ( lastContents ) ; return new XSSFRichTextString ( sst . getEntryAt ( idx ) ) . toString ( ) ; } return lastContents ; case "inlineStr" : //inline string (not in sst) return new XSSFRichTextString ( lastContents ) . toString ( ) ; default : return lastContents ; } }
Returns the contents of the cell with no formatting applied
127
10
158,614
@ Override public CellType getCellType ( ) { if ( formulaType ) { return CellType . FORMULA ; } else if ( contentsSupplier . getContent ( ) == null || type == null ) { return CellType . BLANK ; } else if ( "n" . equals ( type ) ) { return CellType . NUMERIC ; } else if ( "s" . equals ( type ) || "inlineStr" . equals ( type ) || "str" . equals ( type ) ) { return CellType . STRING ; } else if ( "str" . equals ( type ) ) { return CellType . FORMULA ; } else if ( "b" . equals ( type ) ) { return CellType . BOOLEAN ; } else if ( "e" . equals ( type ) ) { return CellType . ERROR ; } else { throw new UnsupportedOperationException ( "Unsupported cell type '" + type + "'" ) ; } }
Return the cell type .
206
5
158,615
@ Override public String getStringCellValue ( ) { Object c = contentsSupplier . getContent ( ) ; return c == null ? "" : c . toString ( ) ; }
Get the value of the cell as a string . For blank cells we return an empty string .
39
19
158,616
@ Override public Date getDateCellValue ( ) { if ( getCellType ( ) == CellType . STRING ) { throw new IllegalStateException ( "Cell type cannot be CELL_TYPE_STRING" ) ; } return rawContents == null ? null : HSSFDateUtil . getJavaDate ( getNumericCellValue ( ) , use1904Dates ) ; }
Get the value of the cell as a date . For strings we throw an exception . For blank cells we return a null .
84
25
158,617
@ Override public boolean getBooleanCellValue ( ) { CellType cellType = getCellType ( ) ; switch ( cellType ) { case BLANK : return false ; case BOOLEAN : return rawContents != null && TRUE_AS_STRING . equals ( rawContents ) ; case FORMULA : throw new NotSupportedException ( ) ; default : throw typeMismatch ( CellType . BOOLEAN , cellType , false ) ; } }
Get the value of the cell as a boolean . For strings we throw an exception . For blank cells we return a false .
99
25
158,618
private static String getCellTypeName ( CellType cellType ) { switch ( cellType ) { case BLANK : return "blank" ; case STRING : return "text" ; case BOOLEAN : return "boolean" ; case ERROR : return "error" ; case NUMERIC : return "numeric" ; case FORMULA : return "formula" ; } return "#unknown cell type (" + cellType + ")#" ; }
Used to help format error messages
97
6
158,619
@ Override public CellType getCachedFormulaResultType ( ) { if ( formulaType ) { if ( contentsSupplier . getContent ( ) == null || type == null ) { return CellType . BLANK ; } else if ( "n" . equals ( type ) ) { return CellType . NUMERIC ; } else if ( "s" . equals ( type ) || "inlineStr" . equals ( type ) || "str" . equals ( type ) ) { return CellType . STRING ; } else if ( "b" . equals ( type ) ) { return CellType . BOOLEAN ; } else if ( "e" . equals ( type ) ) { return CellType . ERROR ; } else { throw new UnsupportedOperationException ( "Unsupported cell type '" + type + "'" ) ; } } else { throw new IllegalStateException ( "Only formula cells have cached results" ) ; } }
Only valid for formula cells
198
5
158,620
@ Override public void close ( ) throws IOException { try { workbook . close ( ) ; } finally { if ( tmp != null ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Deleting tmp file [" + tmp . getAbsolutePath ( ) + "]" ) ; } tmp . delete ( ) ; } } }
Closes the streaming resource attempting to clean up any temporary files created .
77
14
158,621
public boolean containsThumbnail ( int userPage , int page , float width , float height , RectF pageRelativeBounds ) { PagePart fakePart = new PagePart ( userPage , page , null , width , height , pageRelativeBounds , true , 0 ) ; for ( PagePart part : thumbnails ) { if ( part . equals ( fakePart ) ) { return true ; } } return false ; }
Return true if already contains the described PagePart
88
9
158,622
private float distance ( MotionEvent event ) { if ( event . getPointerCount ( ) < 2 ) { return 0 ; } return PointF . length ( event . getX ( POINTER1 ) - event . getX ( POINTER2 ) , // event . getY ( POINTER1 ) - event . getY ( POINTER2 ) ) ; }
Calculates the distance between the 2 current pointers
76
10
158,623
private boolean isClick ( MotionEvent upEvent , float xDown , float yDown , float xUp , float yUp ) { if ( upEvent == null ) return false ; long time = upEvent . getEventTime ( ) - upEvent . getDownTime ( ) ; float distance = PointF . length ( // xDown - xUp , // yDown - yUp ) ; return time < MAX_CLICK_TIME && distance < MAX_CLICK_DISTANCE ; }
Test if a MotionEvent with the given start and end offsets can be considered as a click .
103
19
158,624
private void drawPart ( Canvas canvas , PagePart part ) { // Can seem strange, but avoid lot of calls RectF pageRelativeBounds = part . getPageRelativeBounds ( ) ; Bitmap renderedBitmap = part . getRenderedBitmap ( ) ; // Move to the target page float localTranslationX = 0 ; float localTranslationY = 0 ; if ( swipeVertical ) localTranslationY = toCurrentScale ( part . getUserPage ( ) * optimalPageHeight ) ; else localTranslationX = toCurrentScale ( part . getUserPage ( ) * optimalPageWidth ) ; canvas . translate ( localTranslationX , localTranslationY ) ; Rect srcRect = new Rect ( 0 , 0 , renderedBitmap . getWidth ( ) , // renderedBitmap . getHeight ( ) ) ; float offsetX = toCurrentScale ( pageRelativeBounds . left * optimalPageWidth ) ; float offsetY = toCurrentScale ( pageRelativeBounds . top * optimalPageHeight ) ; float width = toCurrentScale ( pageRelativeBounds . width ( ) * optimalPageWidth ) ; float height = toCurrentScale ( pageRelativeBounds . height ( ) * optimalPageHeight ) ; // If we use float values for this rectangle, there will be // a possible gap between page parts, especially when // the zoom level is high. RectF dstRect = new RectF ( ( int ) offsetX , ( int ) offsetY , // ( int ) ( offsetX + width ) , // ( int ) ( offsetY + height ) ) ; // Check if bitmap is in the screen float translationX = currentXOffset + localTranslationX ; float translationY = currentYOffset + localTranslationY ; if ( translationX + dstRect . left >= getWidth ( ) || translationX + dstRect . right <= 0 || translationY + dstRect . top >= getHeight ( ) || translationY + dstRect . bottom <= 0 ) { canvas . translate ( - localTranslationX , - localTranslationY ) ; return ; } canvas . drawBitmap ( renderedBitmap , srcRect , dstRect , paint ) ; if ( Constants . DEBUG_MODE ) { debugPaint . setColor ( part . getUserPage ( ) % 2 == 0 ? Color . RED : Color . BLUE ) ; canvas . drawRect ( dstRect , debugPaint ) ; } // Restore the canvas position canvas . translate ( - localTranslationX , - localTranslationY ) ; }
Draw a given PagePart on the canvas
525
8
158,625
public void loadPages ( ) { if ( optimalPageWidth == 0 || optimalPageHeight == 0 ) { return ; } // Cancel all current tasks renderingAsyncTask . removeAllTasks ( ) ; cacheManager . makeANewSet ( ) ; // Find current index in filtered user pages int index = currentPage ; if ( filteredUserPageIndexes != null ) { index = filteredUserPageIndexes [ currentPage ] ; } // Loop through the pages like [...][4][2][0][1][3][...] // loading as many parts as it can. int parts = 0 ; for ( int i = 0 ; i <= Constants . LOADED_SIZE / 2 && parts < CACHE_SIZE ; i ++ ) { parts += loadPage ( index + i , CACHE_SIZE - parts ) ; if ( i != 0 && parts < CACHE_SIZE ) { parts += loadPage ( index - i , CACHE_SIZE - parts ) ; } } invalidate ( ) ; }
Load all the parts around the center of the screen taking into account X and Y offsets zoom level and the current page displayed
214
24
158,626
public void loadComplete ( DecodeService decodeService ) { this . decodeService = decodeService ; this . documentPageCount = decodeService . getPageCount ( ) ; // We assume all the pages are the same size this . pageWidth = decodeService . getPageWidth ( 0 ) ; this . pageHeight = decodeService . getPageHeight ( 0 ) ; state = State . LOADED ; calculateOptimalWidthAndHeight ( ) ; // Notify the listener jumpTo ( defaultPage ) ; if ( onLoadCompleteListener != null ) { onLoadCompleteListener . loadComplete ( documentPageCount ) ; } }
Called when the PDF is loaded
129
7
158,627
public void onBitmapRendered ( PagePart part ) { if ( part . isThumbnail ( ) ) { cacheManager . cacheThumbnail ( part ) ; } else { cacheManager . cachePart ( part ) ; } invalidate ( ) ; }
Called when a rendering task is over and a PagePart has been freshly created .
51
17
158,628
private int determineValidPageNumberFrom ( int userPage ) { if ( userPage <= 0 ) { return 0 ; } if ( originalUserPages != null ) { if ( userPage >= originalUserPages . length ) { return originalUserPages . length - 1 ; } } else { if ( userPage >= documentPageCount ) { return documentPageCount - 1 ; } } return userPage ; }
Given the UserPage number this method restrict it to be sure it s an existing page . It takes care of using the user defined pages if any .
83
30
158,629
private void calculateOptimalWidthAndHeight ( ) { if ( state == State . DEFAULT || getWidth ( ) == 0 ) { return ; } float maxWidth = getWidth ( ) , maxHeight = getHeight ( ) ; float w = pageWidth , h = pageHeight ; float ratio = w / h ; w = maxWidth ; h = ( float ) Math . floor ( maxWidth / ratio ) ; if ( h > maxHeight ) { h = maxHeight ; w = ( float ) Math . floor ( maxHeight * ratio ) ; } optimalPageWidth = w ; optimalPageHeight = h ; calculateMasksBounds ( ) ; calculateMinimapBounds ( ) ; }
Calculate the optimal width and height of a page considering the area width and height
145
17
158,630
private void calculateMinimapBounds ( ) { float ratioX = Constants . MINIMAP_MAX_SIZE / optimalPageWidth ; float ratioY = Constants . MINIMAP_MAX_SIZE / optimalPageHeight ; float ratio = Math . min ( ratioX , ratioY ) ; float minimapWidth = optimalPageWidth * ratio ; float minimapHeight = optimalPageHeight * ratio ; minimapBounds = new RectF ( getWidth ( ) - 5 - minimapWidth , 5 , getWidth ( ) - 5 , 5 + minimapHeight ) ; calculateMinimapAreaBounds ( ) ; }
Place the minimap background considering the optimal width and height and the MINIMAP_MAX_SIZE .
132
21
158,631
private void calculateMasksBounds ( ) { leftMask = new RectF ( 0 , 0 , getWidth ( ) / 2 - toCurrentScale ( optimalPageWidth ) / 2 , getHeight ( ) ) ; rightMask = new RectF ( getWidth ( ) / 2 + toCurrentScale ( optimalPageWidth ) / 2 , 0 , getWidth ( ) , getHeight ( ) ) ; }
Place the left and right masks around the current page .
84
11
158,632
public void moveTo ( float offsetX , float offsetY ) { if ( swipeVertical ) { // Check X offset if ( toCurrentScale ( optimalPageWidth ) < getWidth ( ) ) { offsetX = getWidth ( ) / 2 - toCurrentScale ( optimalPageWidth ) / 2 ; } else { if ( offsetX > 0 ) { offsetX = 0 ; } else if ( offsetX + toCurrentScale ( optimalPageWidth ) < getWidth ( ) ) { offsetX = getWidth ( ) - toCurrentScale ( optimalPageWidth ) ; } } // Check Y offset if ( isZooming ( ) ) { if ( toCurrentScale ( optimalPageHeight ) < getHeight ( ) ) { miniMapRequired = false ; offsetY = getHeight ( ) / 2 - toCurrentScale ( ( currentFilteredPage + 0.5f ) * optimalPageHeight ) ; } else { miniMapRequired = true ; if ( offsetY + toCurrentScale ( currentFilteredPage * optimalPageHeight ) > 0 ) { offsetY = - toCurrentScale ( currentFilteredPage * optimalPageHeight ) ; } else if ( offsetY + toCurrentScale ( ( currentFilteredPage + 1 ) * optimalPageHeight ) < getHeight ( ) ) { offsetY = getHeight ( ) - toCurrentScale ( ( currentFilteredPage + 1 ) * optimalPageHeight ) ; } } } else { float maxY = calculateCenterOffsetForPage ( currentFilteredPage + 1 ) ; float minY = calculateCenterOffsetForPage ( currentFilteredPage - 1 ) ; if ( offsetY < maxY ) { offsetY = maxY ; } else if ( offsetY > minY ) { offsetY = minY ; } } } else { // Check Y offset if ( toCurrentScale ( optimalPageHeight ) < getHeight ( ) ) { offsetY = getHeight ( ) / 2 - toCurrentScale ( optimalPageHeight ) / 2 ; } else { if ( offsetY > 0 ) { offsetY = 0 ; } else if ( offsetY + toCurrentScale ( optimalPageHeight ) < getHeight ( ) ) { offsetY = getHeight ( ) - toCurrentScale ( optimalPageHeight ) ; } } // Check X offset if ( isZooming ( ) ) { if ( toCurrentScale ( optimalPageWidth ) < getWidth ( ) ) { miniMapRequired = false ; offsetX = getWidth ( ) / 2 - toCurrentScale ( ( currentFilteredPage + 0.5f ) * optimalPageWidth ) ; } else { miniMapRequired = true ; if ( offsetX + toCurrentScale ( currentFilteredPage * optimalPageWidth ) > 0 ) { offsetX = - toCurrentScale ( currentFilteredPage * optimalPageWidth ) ; } else if ( offsetX + toCurrentScale ( ( currentFilteredPage + 1 ) * optimalPageWidth ) < getWidth ( ) ) { offsetX = getWidth ( ) - toCurrentScale ( ( currentFilteredPage + 1 ) * optimalPageWidth ) ; } } } else { float maxX = calculateCenterOffsetForPage ( currentFilteredPage + 1 ) ; float minX = calculateCenterOffsetForPage ( currentFilteredPage - 1 ) ; if ( offsetX < maxX ) { offsetX = maxX ; } else if ( offsetX > minX ) { offsetX = minX ; } } } currentXOffset = offsetX ; currentYOffset = offsetY ; calculateMinimapAreaBounds ( ) ; invalidate ( ) ; }
Move to the given X and Y offsets but check them ahead of time to be sure not to go outside the the big strip .
749
26
158,633
public Configurator fromAsset ( String assetName ) { try { File pdfFile = FileUtils . fileFromAsset ( getContext ( ) , assetName ) ; return fromFile ( pdfFile ) ; } catch ( IOException e ) { throw new FileNotFoundException ( assetName + " does not exist." , e ) ; } }
Use an asset file as the pdf source
72
8
158,634
public Configurator fromFile ( File file ) { if ( ! file . exists ( ) ) throw new FileNotFoundException ( file . getAbsolutePath ( ) + "does not exist." ) ; return new Configurator ( Uri . fromFile ( file ) ) ; }
Use a file as the pdf source
59
7
158,635
@ Benchmark @ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Span putAttribute ( Data data ) { Span span = data . attributeSpan ; for ( int i = 0 ; i < data . size ; i ++ ) { span . putAttribute ( data . attributeKeys [ i ] , data . attributeValues [ i ] ) ; } return span ; }
Add attributes individually .
90
4
158,636
@ Benchmark @ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Span putAttributes ( Data data ) { Span span = data . attributeSpan ; span . putAttributes ( data . attributeMap ) ; return span ; }
Add attributes as a map .
61
6
158,637
@ Benchmark @ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Span addAnnotationEmpty ( Data data ) { Span span = data . annotationSpanEmpty ; span . addAnnotation ( ANNOTATION_DESCRIPTION ) ; return span ; }
Add an annotation as description only .
67
7
158,638
@ Benchmark @ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Span addAnnotationWithAttributes ( Data data ) { Span span = data . annotationSpanAttributes ; span . addAnnotation ( ANNOTATION_DESCRIPTION , data . attributeMap ) ; return span ; }
Add an annotation with attributes .
73
6
158,639
@ Benchmark @ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Span addAnnotationWithAnnotation ( Data data ) { Span span = data . annotationSpanAnnotation ; Annotation annotation = Annotation . fromDescriptionAndAttributes ( ANNOTATION_DESCRIPTION , data . attributeMap ) ; span . addAnnotation ( annotation ) ; return span ; }
Add an annotation with an annotation .
90
7
158,640
@ Benchmark @ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Span addMessageEvent ( Data data ) { Span span = data . messageEventSpan ; for ( int i = 0 ; i < data . size ; i ++ ) { span . addMessageEvent ( data . messageEvents [ i ] ) ; } return span ; }
Add message events .
85
4
158,641
@ Benchmark @ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Span addLink ( Data data ) { Span span = data . linkSpan ; for ( int i = 0 ; i < data . size ; i ++ ) { span . addLink ( data . links [ i ] ) ; } return span ; }
Add links .
81
3
158,642
@ Override public < V > Callable < V > wrap ( Callable < V > callable ) { if ( isTracing ( ) ) { return new SpanContinuingTraceCallable < V > ( this , this . traceKeys , this . spanNamer , callable ) ; } return callable ; }
Wrap the callable in a TraceCallable if tracing .
68
13
158,643
@ Override public Runnable wrap ( Runnable runnable ) { if ( isTracing ( ) ) { return new SpanContinuingTraceRunnable ( this , this . traceKeys , this . spanNamer , runnable ) ; } return runnable ; }
Wrap the runnable in a TraceRunnable if tracing .
62
15
158,644
public static void premain ( String agentArgs , Instrumentation instrumentation ) throws Exception { checkNotNull ( instrumentation , "instrumentation" ) ; logger . fine ( "Initializing." ) ; // The classes in bootstrap.jar, such as ContextManger and ContextStrategy, will be referenced // from classes loaded by the bootstrap classloader. Thus, these classes have to be loaded by // the bootstrap classloader, too. instrumentation . appendToBootstrapClassLoaderSearch ( new JarFile ( Resources . getResourceAsTempFile ( "bootstrap.jar" ) ) ) ; checkLoadedByBootstrapClassloader ( ContextTrampoline . class ) ; checkLoadedByBootstrapClassloader ( ContextStrategy . class ) ; Settings settings = Settings . load ( ) ; AgentBuilder agentBuilder = new AgentBuilder . Default ( ) . disableClassFormatChanges ( ) . with ( AgentBuilder . RedefinitionStrategy . RETRANSFORMATION ) . with ( new AgentBuilderListener ( ) ) . ignore ( none ( ) ) ; for ( Instrumenter instrumenter : ServiceLoader . load ( Instrumenter . class ) ) { agentBuilder = instrumenter . instrument ( agentBuilder , settings ) ; } agentBuilder . installOn ( instrumentation ) ; logger . fine ( "Initialized." ) ; }
Initializes the OpenCensus Agent for Java .
276
10
158,645
private static TraceServiceGrpc . TraceServiceStub getTraceServiceStub ( String endPoint , Boolean useInsecure , SslContext sslContext ) { ManagedChannelBuilder < ? > channelBuilder ; if ( useInsecure ) { channelBuilder = ManagedChannelBuilder . forTarget ( endPoint ) . usePlaintext ( ) ; } else { channelBuilder = NettyChannelBuilder . forTarget ( endPoint ) . negotiationType ( NegotiationType . TLS ) . sslContext ( sslContext ) ; } ManagedChannel channel = channelBuilder . build ( ) ; return TraceServiceGrpc . newStub ( channel ) ; }
One stub can be used for both Export RPC and Config RPC .
138
13
158,646
@ Benchmark @ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public MeasureMap recordBatchedDoubleCount ( Data data ) { MeasureMap map = data . recorder . newMeasureMap ( ) ; for ( int i = 0 ; i < data . numValues ; i ++ ) { map . put ( StatsBenchmarksUtil . DOUBLE_COUNT_MEASURES [ i ] , ( double ) i ) ; } map . record ( data . tags ) ; return map ; }
Record batched double count measures .
117
7
158,647
static File getResourceAsTempFile ( String resourceName ) throws IOException { checkArgument ( ! Strings . isNullOrEmpty ( resourceName ) , "resourceName" ) ; File file = File . createTempFile ( resourceName , ".tmp" ) ; OutputStream os = new FileOutputStream ( file ) ; try { getResourceAsTempFile ( resourceName , file , os ) ; return file ; } finally { os . close ( ) ; } }
Returns a resource of the given name as a temporary file .
98
12
158,648
public static void createAndRegister ( DatadogTraceConfiguration configuration ) throws MalformedURLException { synchronized ( monitor ) { checkState ( handler == null , "Datadog exporter is already registered." ) ; String agentEndpoint = configuration . getAgentEndpoint ( ) ; String service = configuration . getService ( ) ; String type = configuration . getType ( ) ; final DatadogExporterHandler exporterHandler = new DatadogExporterHandler ( agentEndpoint , service , type ) ; handler = exporterHandler ; Tracing . getExportComponent ( ) . getSpanExporter ( ) . registerHandler ( REGISTER_NAME , exporterHandler ) ; } }
Creates and registers the Datadog Trace exporter to the OpenCensus library . Only one Datadog exporter can be registered at any point .
147
32
158,649
@ Deprecated public static void createAndRegisterWithCredentialsAndProjectId ( Credentials credentials , String projectId , Duration exportInterval ) throws IOException { checkNotNull ( credentials , "credentials" ) ; checkNotNull ( projectId , "projectId" ) ; checkNotNull ( exportInterval , "exportInterval" ) ; createInternal ( credentials , projectId , exportInterval , DEFAULT_RESOURCE , null , DEFAULT_CONSTANT_LABELS ) ; }
Creates a StackdriverStatsExporter for an explicit project ID and using explicit credentials with default Monitored Resource .
108
23
158,650
@ Deprecated public static void createAndRegisterWithProjectId ( String projectId , Duration exportInterval ) throws IOException { checkNotNull ( projectId , "projectId" ) ; checkNotNull ( exportInterval , "exportInterval" ) ; createInternal ( null , projectId , exportInterval , DEFAULT_RESOURCE , null , DEFAULT_CONSTANT_LABELS ) ; }
Creates a Stackdriver Stats exporter for an explicit project ID with default Monitored Resource .
86
19
158,651
@ Deprecated public static void createAndRegister ( Duration exportInterval ) throws IOException { checkNotNull ( exportInterval , "exportInterval" ) ; checkArgument ( ! DEFAULT_PROJECT_ID . isEmpty ( ) , "Cannot find a project ID from application default." ) ; createInternal ( null , DEFAULT_PROJECT_ID , exportInterval , DEFAULT_RESOURCE , null , DEFAULT_CONSTANT_LABELS ) ; }
Creates a Stackdriver Stats exporter with default Monitored Resource .
102
14
158,652
@ Deprecated public static void createAndRegisterWithProjectIdAndMonitoredResource ( String projectId , Duration exportInterval , MonitoredResource monitoredResource ) throws IOException { checkNotNull ( projectId , "projectId" ) ; checkNotNull ( exportInterval , "exportInterval" ) ; checkNotNull ( monitoredResource , "monitoredResource" ) ; createInternal ( null , projectId , exportInterval , monitoredResource , null , DEFAULT_CONSTANT_LABELS ) ; }
Creates a Stackdriver Stats exporter with an explicit project ID and a custom Monitored Resource .
107
20
158,653
@ Deprecated public static void createAndRegisterWithMonitoredResource ( Duration exportInterval , MonitoredResource monitoredResource ) throws IOException { checkNotNull ( exportInterval , "exportInterval" ) ; checkNotNull ( monitoredResource , "monitoredResource" ) ; checkArgument ( ! DEFAULT_PROJECT_ID . isEmpty ( ) , "Cannot find a project ID from application default." ) ; createInternal ( null , DEFAULT_PROJECT_ID , exportInterval , monitoredResource , null , DEFAULT_CONSTANT_LABELS ) ; }
Creates a Stackdriver Stats exporter with a custom Monitored Resource .
123
15
158,654
@ VisibleForTesting static void unsafeResetExporter ( ) { synchronized ( monitor ) { if ( instance != null ) { instance . intervalMetricReader . stop ( ) ; } instance = null ; } }
Resets exporter to null . Used only for unit tests .
45
13
158,655
private void export ( ) { if ( exportRpcHandler == null || exportRpcHandler . isCompleted ( ) ) { return ; } ArrayList < Metric > metricsList = Lists . newArrayList ( ) ; for ( MetricProducer metricProducer : metricProducerManager . getAllMetricProducer ( ) ) { metricsList . addAll ( metricProducer . getMetrics ( ) ) ; } List < io . opencensus . proto . metrics . v1 . Metric > metricProtos = Lists . newArrayList ( ) ; for ( Metric metric : metricsList ) { // TODO(songya): determine if we should make the optimization on not sending already-existed // MetricDescriptors. // boolean registered = true; // if (!registeredDescriptors.contains(metric.getMetricDescriptor())) { // registered = false; // registeredDescriptors.add(metric.getMetricDescriptor()); // } metricProtos . add ( MetricsProtoUtils . toMetricProto ( metric , null ) ) ; } exportRpcHandler . onExport ( // For now don't include Resource in the following messages, i.e don't allow Resource to // mutate after the initial message. ExportMetricsServiceRequest . newBuilder ( ) . addAllMetrics ( metricProtos ) . build ( ) ) ; }
converts them to proto then exports them to OC - Agent .
300
13
158,656
public static void setTraceStrategy ( TraceStrategy traceStrategy ) { if ( TraceTrampoline . traceStrategy != null ) { throw new IllegalStateException ( "traceStrategy was already set" ) ; } if ( traceStrategy == null ) { throw new NullPointerException ( "traceStrategy" ) ; } TraceTrampoline . traceStrategy = traceStrategy ; }
Sets the concrete strategy for creating and manipulating trace spans .
86
12
158,657
public static < T > T createInstance ( Class < ? > rawClass , Class < T > superclass ) { try { return rawClass . asSubclass ( superclass ) . getConstructor ( ) . newInstance ( ) ; } catch ( Exception e ) { throw new ServiceConfigurationError ( "Provider " + rawClass . getName ( ) + " could not be instantiated." , e ) ; } }
Tries to create an instance of the given rawClass as a subclass of the given superclass .
87
20
158,658
private static final TagKey createTagKey ( String name ) throws TagContextDeserializationException { try { return TagKey . create ( name ) ; } catch ( IllegalArgumentException e ) { throw new TagContextDeserializationException ( "Invalid tag key: " + name , e ) ; } }
IllegalArgumentException here .
64
7
158,659
private static final TagValue createTagValue ( TagKey key , String value ) throws TagContextDeserializationException { try { return TagValue . create ( value ) ; } catch ( IllegalArgumentException e ) { throw new TagContextDeserializationException ( "Invalid tag value for key " + key + ": " + value , e ) ; } }
an IllegalArgumentException here .
75
7
158,660
private boolean registerMetricDescriptor ( io . opencensus . metrics . export . MetricDescriptor metricDescriptor ) { String metricName = metricDescriptor . getName ( ) ; io . opencensus . metrics . export . MetricDescriptor existingMetricDescriptor = registeredMetricDescriptors . get ( metricName ) ; if ( existingMetricDescriptor != null ) { if ( existingMetricDescriptor . equals ( metricDescriptor ) ) { // Ignore metricDescriptor that are already registered. return true ; } else { logger . log ( Level . WARNING , "A different metric with the same name is already registered: " + existingMetricDescriptor ) ; return false ; } } registeredMetricDescriptors . put ( metricName , metricDescriptor ) ; if ( isBuiltInMetric ( metricName ) ) { return true ; // skip creating metric descriptor for stackdriver built-in metrics. } Span span = tracer . getCurrentSpan ( ) ; span . addAnnotation ( "Create Stackdriver Metric." ) ; MetricDescriptor stackDriverMetricDescriptor = StackdriverExportUtils . createMetricDescriptor ( metricDescriptor , projectId , domain , displayNamePrefix , constantLabels ) ; CreateMetricDescriptorRequest request = CreateMetricDescriptorRequest . newBuilder ( ) . setName ( projectName . toString ( ) ) . setMetricDescriptor ( stackDriverMetricDescriptor ) . build ( ) ; try { metricServiceClient . createMetricDescriptor ( request ) ; span . addAnnotation ( "Finish creating MetricDescriptor." ) ; return true ; } catch ( ApiException e ) { logger . log ( Level . WARNING , "ApiException thrown when creating MetricDescriptor." , e ) ; span . setStatus ( Status . CanonicalCode . valueOf ( e . getStatusCode ( ) . getCode ( ) . name ( ) ) . toStatus ( ) . withDescription ( "ApiException thrown when creating MetricDescriptor: " + StackdriverExportUtils . exceptionMessage ( e ) ) ) ; return false ; } catch ( Throwable e ) { logger . log ( Level . WARNING , "Exception thrown when creating MetricDescriptor." , e ) ; span . setStatus ( Status . UNKNOWN . withDescription ( "Exception thrown when creating MetricDescriptor: " + StackdriverExportUtils . exceptionMessage ( e ) ) ) ; return false ; } }
exact same metric has already been registered . Returns false otherwise .
555
13
158,661
static String generateFullMetricName ( String name , String type ) { return SOURCE + DELIMITER + name + DELIMITER + type ; }
Returns the metric name .
34
5
158,662
static String generateFullMetricDescription ( String metricName , Metric metric ) { return "Collected from " + SOURCE + " (metric=" + metricName + ", type=" + metric . getClass ( ) . getName ( ) + ")" ; }
Returns the metric description .
56
5
158,663
public static void setContextStrategy ( ContextStrategy contextStrategy ) { if ( ContextTrampoline . contextStrategy != null ) { throw new IllegalStateException ( "contextStrategy was already set" ) ; } if ( contextStrategy == null ) { throw new NullPointerException ( "contextStrategy" ) ; } ContextTrampoline . contextStrategy = contextStrategy ; }
Sets the concrete strategy for accessing and manipulating the context .
85
12
158,664
private static Attributes toAttributesProto ( io . opencensus . trace . export . SpanData . Attributes attributes , Map < String , AttributeValue > resourceLabels , Map < String , AttributeValue > fixedAttributes ) { Attributes . Builder attributesBuilder = toAttributesBuilderProto ( attributes . getAttributeMap ( ) , attributes . getDroppedAttributesCount ( ) ) ; attributesBuilder . putAttributeMap ( AGENT_LABEL_KEY , AGENT_LABEL_VALUE ) ; for ( Entry < String , AttributeValue > entry : resourceLabels . entrySet ( ) ) { attributesBuilder . putAttributeMap ( entry . getKey ( ) , entry . getValue ( ) ) ; } for ( Entry < String , AttributeValue > entry : fixedAttributes . entrySet ( ) ) { attributesBuilder . putAttributeMap ( entry . getKey ( ) , entry . getValue ( ) ) ; } return attributesBuilder . build ( ) ; }
These are the attributes of the Span where usually we may add more attributes like the agent .
201
18
158,665
public static void createAndRegister ( String agentEndpoint ) throws MalformedURLException { synchronized ( monitor ) { checkState ( handler == null , "Instana exporter is already registered." ) ; Handler newHandler = new InstanaExporterHandler ( new URL ( agentEndpoint ) ) ; handler = newHandler ; register ( Tracing . getExportComponent ( ) . getSpanExporter ( ) , newHandler ) ; } }
Creates and registers the Instana Trace exporter to the OpenCensus library . Only one Instana exporter can be registered at any point .
93
30
158,666
public synchronized Collection < T > getAll ( ) { List < T > all = new ArrayList < T > ( size ) ; for ( T e = head ; e != null ; e = e . getNext ( ) ) { all . add ( e ) ; } return all ; }
Returns all the elements from this list .
60
8
158,667
public final void handleMessageSent ( HttpRequestContext context , long bytes ) { checkNotNull ( context , "context" ) ; context . sentMessageSize . addAndGet ( bytes ) ; if ( context . span . getOptions ( ) . contains ( Options . RECORD_EVENTS ) ) { // record compressed size recordMessageEvent ( context . span , context . sentSeqId . addAndGet ( 1L ) , Type . SENT , bytes , 0L ) ; } }
Instrument an HTTP span after a message is sent . Typically called for every chunk of request or response is sent .
104
23
158,668
public final void handleMessageReceived ( HttpRequestContext context , long bytes ) { checkNotNull ( context , "context" ) ; context . receiveMessageSize . addAndGet ( bytes ) ; if ( context . span . getOptions ( ) . contains ( Options . RECORD_EVENTS ) ) { // record compressed size recordMessageEvent ( context . span , context . receviedSeqId . addAndGet ( 1L ) , Type . RECEIVED , bytes , 0L ) ; } }
Instrument an HTTP span after a message is received . Typically called for every chunk of request or response is received .
109
23
158,669
@ GuardedBy ( "monitor" ) private /*@Nullable*/ TreeNode findNode ( /*@Nullable*/ String path ) { if ( Strings . isNullOrEmpty ( path ) || "/" . equals ( path ) ) { // Go back to the root directory. return root ; } else { List < String > dirs = PATH_SPLITTER . splitToList ( path ) ; TreeNode node = root ; for ( int i = 0 ; i < dirs . size ( ) ; i ++ ) { String dir = dirs . get ( i ) ; if ( "" . equals ( dir ) && i == 0 ) { continue ; // Skip the first "", the path of root node. } if ( ! node . children . containsKey ( dir ) ) { return null ; } else { node = node . children . get ( dir ) ; } } return node ; } }
Returns null if such a TreeNode doesn t exist .
190
11
158,670
void record ( List < /*@Nullable*/ TagValue > tagValues , double value , Map < String , AttachmentValue > attachments , Timestamp timestamp ) { if ( ! tagValueAggregationMap . containsKey ( tagValues ) ) { tagValueAggregationMap . put ( tagValues , RecordUtils . createMutableAggregation ( aggregation , measure ) ) ; } tagValueAggregationMap . get ( tagValues ) . add ( value , attachments , timestamp ) ; }
Puts a new value into the internal MutableAggregations based on the TagValues .
101
19
158,671
static MetricDescriptor createMetricDescriptor ( io . opencensus . metrics . export . MetricDescriptor metricDescriptor , String projectId , String domain , String displayNamePrefix , Map < LabelKey , LabelValue > constantLabels ) { MetricDescriptor . Builder builder = MetricDescriptor . newBuilder ( ) ; String type = generateType ( metricDescriptor . getName ( ) , domain ) ; // Name format refers to // cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.metricDescriptors/create builder . setName ( "projects/" + projectId + "/metricDescriptors/" + type ) ; builder . setType ( type ) ; builder . setDescription ( metricDescriptor . getDescription ( ) ) ; builder . setDisplayName ( createDisplayName ( metricDescriptor . getName ( ) , displayNamePrefix ) ) ; for ( LabelKey labelKey : metricDescriptor . getLabelKeys ( ) ) { builder . addLabels ( createLabelDescriptor ( labelKey ) ) ; } for ( LabelKey labelKey : constantLabels . keySet ( ) ) { builder . addLabels ( createLabelDescriptor ( labelKey ) ) ; } builder . setUnit ( metricDescriptor . getUnit ( ) ) ; builder . setMetricKind ( createMetricKind ( metricDescriptor . getType ( ) ) ) ; builder . setValueType ( createValueType ( metricDescriptor . getType ( ) ) ) ; return builder . build ( ) ; }
Convert a OpenCensus MetricDescriptor to a StackDriver MetricDescriptor
350
20
158,672
@ VisibleForTesting static LabelDescriptor createLabelDescriptor ( LabelKey labelKey ) { LabelDescriptor . Builder builder = LabelDescriptor . newBuilder ( ) ; builder . setKey ( labelKey . getKey ( ) ) ; builder . setDescription ( labelKey . getDescription ( ) ) ; // Now we only support String tags builder . setValueType ( ValueType . STRING ) ; return builder . build ( ) ; }
Construct a LabelDescriptor from a LabelKey
96
10
158,673
@ VisibleForTesting static MetricKind createMetricKind ( Type type ) { if ( type == Type . GAUGE_INT64 || type == Type . GAUGE_DOUBLE ) { return MetricKind . GAUGE ; } else if ( type == Type . CUMULATIVE_INT64 || type == Type . CUMULATIVE_DOUBLE || type == Type . CUMULATIVE_DISTRIBUTION ) { return MetricKind . CUMULATIVE ; } return MetricKind . UNRECOGNIZED ; }
Convert a OpenCensus Type to a StackDriver MetricKind
118
14
158,674
@ VisibleForTesting static MetricDescriptor . ValueType createValueType ( Type type ) { if ( type == Type . CUMULATIVE_DOUBLE || type == Type . GAUGE_DOUBLE ) { return MetricDescriptor . ValueType . DOUBLE ; } else if ( type == Type . GAUGE_INT64 || type == Type . CUMULATIVE_INT64 ) { return MetricDescriptor . ValueType . INT64 ; } else if ( type == Type . GAUGE_DISTRIBUTION || type == Type . CUMULATIVE_DISTRIBUTION ) { return MetricDescriptor . ValueType . DISTRIBUTION ; } return MetricDescriptor . ValueType . UNRECOGNIZED ; }
Convert a OpenCensus Type to a StackDriver ValueType
167
13
158,675
@ VisibleForTesting static Metric createMetric ( io . opencensus . metrics . export . MetricDescriptor metricDescriptor , List < LabelValue > labelValues , String domain , Map < LabelKey , LabelValue > constantLabels ) { Metric . Builder builder = Metric . newBuilder ( ) ; builder . setType ( generateType ( metricDescriptor . getName ( ) , domain ) ) ; Map < String , String > stringTagMap = Maps . newHashMap ( ) ; List < LabelKey > labelKeys = metricDescriptor . getLabelKeys ( ) ; for ( int i = 0 ; i < labelValues . size ( ) ; i ++ ) { String value = labelValues . get ( i ) . getValue ( ) ; if ( value == null ) { continue ; } stringTagMap . put ( labelKeys . get ( i ) . getKey ( ) , value ) ; } for ( Map . Entry < LabelKey , LabelValue > constantLabel : constantLabels . entrySet ( ) ) { String constantLabelKey = constantLabel . getKey ( ) . getKey ( ) ; String constantLabelValue = constantLabel . getValue ( ) . getValue ( ) ; constantLabelValue = constantLabelValue == null ? "" : constantLabelValue ; stringTagMap . put ( constantLabelKey , constantLabelValue ) ; } builder . putAllLabels ( stringTagMap ) ; return builder . build ( ) ; }
Create a Metric using the LabelKeys and LabelValues .
311
12
158,676
@ VisibleForTesting static TypedValue createTypedValue ( Value value ) { return value . match ( typedValueDoubleFunction , typedValueLongFunction , typedValueDistributionFunction , typedValueSummaryFunction , Functions . < TypedValue > throwIllegalArgumentException ( ) ) ; }
Note TypedValue is A single strongly - typed value i . e only one field should be set .
62
21
158,677
@ VisibleForTesting static Distribution createDistribution ( io . opencensus . metrics . export . Distribution distribution ) { Distribution . Builder builder = Distribution . newBuilder ( ) . setBucketOptions ( createBucketOptions ( distribution . getBucketOptions ( ) ) ) . setCount ( distribution . getCount ( ) ) . setMean ( distribution . getCount ( ) == 0 ? 0 : distribution . getSum ( ) / distribution . getCount ( ) ) . setSumOfSquaredDeviation ( distribution . getSumOfSquaredDeviations ( ) ) ; setBucketCountsAndExemplars ( distribution . getBuckets ( ) , builder ) ; return builder . build ( ) ; }
Convert a OpenCensus Distribution to a StackDriver Distribution
150
12
158,678
@ VisibleForTesting static Timestamp convertTimestamp ( io . opencensus . common . Timestamp censusTimestamp ) { if ( censusTimestamp . getSeconds ( ) < 0 ) { // StackDriver doesn't handle negative timestamps. return Timestamp . newBuilder ( ) . build ( ) ; } return Timestamp . newBuilder ( ) . setSeconds ( censusTimestamp . getSeconds ( ) ) . setNanos ( censusTimestamp . getNanos ( ) ) . build ( ) ; }
Convert a OpenCensus Timestamp to a StackDriver Timestamp
111
14
158,679
@ Benchmark @ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public TagContext tagContextCreation ( Data data ) { return TagsBenchmarksUtil . createTagContext ( data . tagger . emptyBuilder ( ) , data . numTags ) ; }
Create a tag context .
68
5
158,680
@ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Scope scopeTagContext ( Data data ) { Scope scope = data . tagger . withTagContext ( data . tagContext ) ; scope . close ( ) ; return scope ; }
Open and close a tag context scope .
63
8
158,681
@ Benchmark @ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public TagContext getCurrentTagContext ( Data data ) { return data . tagger . getCurrentTagContext ( ) ; }
Get the current tag context .
54
6
158,682
@ Benchmark @ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public byte [ ] serializeTagContext ( Data data ) throws Exception { return data . serializer . toByteArray ( data . tagContext ) ; }
Serialize a tag context .
60
6
158,683
@ Benchmark @ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public TagContext deserializeTagContext ( Data data ) throws Exception { return data . serializer . fromByteArray ( data . serializedTagContext ) ; }
Deserialize a tag context .
62
7
158,684
private static ViewData createInternal ( View view , Map < List < /*@Nullable*/ TagValue > , AggregationData > aggregationMap , AggregationWindowData window , Timestamp start , Timestamp end ) { @ SuppressWarnings ( "nullness" ) Map < List < TagValue > , AggregationData > map = aggregationMap ; return new AutoValue_ViewData ( view , map , window , start , end ) ; }
constructor does not have the
94
6
158,685
static Endpoint produceLocalEndpoint ( String serviceName ) { Endpoint . Builder builder = Endpoint . newBuilder ( ) . serviceName ( serviceName ) ; try { Enumeration < NetworkInterface > nics = NetworkInterface . getNetworkInterfaces ( ) ; if ( nics == null ) { return builder . build ( ) ; } while ( nics . hasMoreElements ( ) ) { NetworkInterface nic = nics . nextElement ( ) ; Enumeration < InetAddress > addresses = nic . getInetAddresses ( ) ; while ( addresses . hasMoreElements ( ) ) { InetAddress address = addresses . nextElement ( ) ; if ( address . isSiteLocalAddress ( ) ) { builder . ip ( address ) ; break ; } } } } catch ( Exception e ) { // don't crash the caller if there was a problem reading nics. if ( logger . isLoggable ( Level . FINE ) ) { logger . log ( Level . FINE , "error reading nics" , e ) ; } } return builder . build ( ) ; }
Logic borrowed from brave . internal . Platform . produceLocalEndpoint
232
14
158,686
@ Benchmark @ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public AttributeValue [ ] createAttributeValues ( Data data ) { return getAttributeValues ( data . size , data . attributeType ) ; }
Create attribute values .
58
4
158,687
@ Benchmark @ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Map < String , AttributeValue > createAttributeMap ( Data data ) { Map < String , AttributeValue > attributeMap = new HashMap <> ( data . size ) ; for ( int i = 0 ; i < data . size ; i ++ ) { attributeMap . put ( data . attributeKeys [ i ] , data . attributeValues [ i ] ) ; } return attributeMap ; }
Create an AttributeMap .
112
6
158,688
@ Benchmark @ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Annotation createAnnotation ( Data data ) { return Annotation . fromDescriptionAndAttributes ( ANNOTATION_DESCRIPTION , data . attributeMap ) ; }
Create an Annotation .
62
5
158,689
static MetricFamilySamples createMetricFamilySamples ( Metric metric , String namespace ) { MetricDescriptor metricDescriptor = metric . getMetricDescriptor ( ) ; String name = getNamespacedName ( metricDescriptor . getName ( ) , namespace ) ; Type type = getType ( metricDescriptor . getType ( ) ) ; List < String > labelNames = convertToLabelNames ( metricDescriptor . getLabelKeys ( ) ) ; List < Sample > samples = Lists . newArrayList ( ) ; for ( io . opencensus . metrics . export . TimeSeries timeSeries : metric . getTimeSeriesList ( ) ) { for ( io . opencensus . metrics . export . Point point : timeSeries . getPoints ( ) ) { samples . addAll ( getSamples ( name , labelNames , timeSeries . getLabelValues ( ) , point . getValue ( ) ) ) ; } } return new MetricFamilySamples ( name , type , metricDescriptor . getDescription ( ) , samples ) ; }
Converts a Metric to a Prometheus MetricFamilySamples .
229
14
158,690
static MetricFamilySamples createDescribableMetricFamilySamples ( MetricDescriptor metricDescriptor , String namespace ) { String name = getNamespacedName ( metricDescriptor . getName ( ) , namespace ) ; Type type = getType ( metricDescriptor . getType ( ) ) ; List < String > labelNames = convertToLabelNames ( metricDescriptor . getLabelKeys ( ) ) ; if ( containsDisallowedLeLabelForHistogram ( labelNames , type ) ) { throw new IllegalStateException ( "Prometheus Histogram cannot have a label named 'le', " + "because it is a reserved label for bucket boundaries. " + "Please remove this key from your view." ) ; } if ( containsDisallowedQuantileLabelForSummary ( labelNames , type ) ) { throw new IllegalStateException ( "Prometheus Summary cannot have a label named 'quantile', " + "because it is a reserved label. Please remove this key from your view." ) ; } return new MetricFamilySamples ( name , type , metricDescriptor . getDescription ( ) , Collections . < Sample > emptyList ( ) ) ; }
Used only for Prometheus metric registry should not contain any actual samples .
248
13
158,691
@ VisibleForTesting static List < String > convertToLabelNames ( List < LabelKey > labelKeys ) { final List < String > labelNames = new ArrayList < String > ( labelKeys . size ( ) ) ; for ( LabelKey labelKey : labelKeys ) { labelNames . add ( Collector . sanitizeMetricName ( labelKey . getKey ( ) ) ) ; } return labelNames ; }
Converts the list of label keys to a list of string label names . Also sanitizes the label keys .
88
23
158,692
static TraceConfig getCurrentTraceConfig ( io . opencensus . trace . config . TraceConfig traceConfig ) { TraceParams traceParams = traceConfig . getActiveTraceParams ( ) ; return toTraceConfigProto ( traceParams ) ; }
Creates a TraceConfig proto message with current TraceParams .
58
13
158,693
static TraceParams getUpdatedTraceParams ( UpdatedLibraryConfig config , io . opencensus . trace . config . TraceConfig traceConfig ) { TraceParams currentParams = traceConfig . getActiveTraceParams ( ) ; TraceConfig traceConfigProto = config . getConfig ( ) ; return fromTraceConfigProto ( traceConfigProto , currentParams ) ; }
TraceParams then applies the updated TraceParams .
84
12
158,694
@ SuppressWarnings ( "nullness" ) public static void createAndRegister ( ElasticsearchTraceConfiguration elasticsearchTraceConfiguration ) throws MalformedURLException { synchronized ( monitor ) { Preconditions . checkState ( handler == null , "Elasticsearch exporter already registered." ) ; Preconditions . checkArgument ( elasticsearchTraceConfiguration != null , "Elasticsearch " + "configuration not set." ) ; Preconditions . checkArgument ( elasticsearchTraceConfiguration . getElasticsearchIndex ( ) != null , "Elasticsearch index not specified" ) ; Preconditions . checkArgument ( elasticsearchTraceConfiguration . getElasticsearchType ( ) != null , "Elasticsearch type not specified" ) ; Preconditions . checkArgument ( elasticsearchTraceConfiguration . getElasticsearchUrl ( ) != null , "Elasticsearch URL not specified" ) ; handler = new ElasticsearchTraceHandler ( elasticsearchTraceConfiguration ) ; register ( Tracing . getExportComponent ( ) . getSpanExporter ( ) , handler ) ; } }
Creates and registers the ElasticsearchTraceExporter to the OpenCensus .
237
17
158,695
public boolean isEnabled ( String featurePath ) { checkArgument ( ! Strings . isNullOrEmpty ( featurePath ) ) ; return config . getConfig ( featurePath ) . getBoolean ( "enabled" ) ; }
Checks whether a feature is enabled in the effective configuration .
47
12
158,696
synchronized void sendInitialMessage ( Node node ) { io . opencensus . proto . trace . v1 . TraceConfig currentTraceConfigProto = TraceProtoUtils . getCurrentTraceConfig ( traceConfig ) ; // First config must have Node set. CurrentLibraryConfig firstConfig = CurrentLibraryConfig . newBuilder ( ) . setNode ( node ) . setConfig ( currentTraceConfigProto ) . build ( ) ; sendCurrentConfig ( firstConfig ) ; }
subsequent updated library configs unless the stream is interrupted .
103
12
158,697
private synchronized void sendCurrentConfig ( ) { // Bouncing back CurrentLibraryConfig to Agent. io . opencensus . proto . trace . v1 . TraceConfig currentTraceConfigProto = TraceProtoUtils . getCurrentTraceConfig ( traceConfig ) ; CurrentLibraryConfig currentLibraryConfig = CurrentLibraryConfig . newBuilder ( ) . setConfig ( currentTraceConfigProto ) . build ( ) ; sendCurrentConfig ( currentLibraryConfig ) ; }
Follow up after applying the updated library config .
98
9
158,698
private synchronized void sendCurrentConfig ( CurrentLibraryConfig currentLibraryConfig ) { if ( isCompleted ( ) || currentConfigObserver == null ) { return ; } try { currentConfigObserver . onNext ( currentLibraryConfig ) ; } catch ( Exception e ) { // Catch client side exceptions. onComplete ( e ) ; } }
Sends current config to Agent if the stream is still connected otherwise do nothing .
69
16
158,699
public static void main ( String [ ] args ) throws IOException , InterruptedException { // Register the view. It is imperative that this step exists, // otherwise recorded metrics will be dropped and never exported. View view = View . create ( Name . create ( "task_latency_distribution" ) , "The distribution of the task latencies." , LATENCY_MS , Aggregation . Distribution . create ( LATENCY_BOUNDARIES ) , Collections . < TagKey > emptyList ( ) ) ; // Create the view manager ViewManager viewManager = Stats . getViewManager ( ) ; // Then finally register the views viewManager . registerView ( view ) ; // [START setup_exporter] // Enable OpenCensus exporters to export metrics to Stackdriver Monitoring. // Exporters use Application Default Credentials to authenticate. // See https://developers.google.com/identity/protocols/application-default-credentials // for more details. StackdriverStatsExporter . createAndRegister ( ) ; // [END setup_exporter] // Record 100 fake latency values between 0 and 5 seconds. Random rand = new Random ( ) ; for ( int i = 0 ; i < 100 ; i ++ ) { long ms = ( long ) ( TimeUnit . MILLISECONDS . convert ( 5 , TimeUnit . SECONDS ) * rand . nextDouble ( ) ) ; System . out . println ( String . format ( "Latency %d: %d" , i , ms ) ) ; STATS_RECORDER . newMeasureMap ( ) . put ( LATENCY_MS , ms ) . record ( ) ; } // The default export interval is 60 seconds. The thread with the StackdriverStatsExporter must // live for at least the interval past any metrics that must be collected, or some risk being // lost if they are recorded after the last export. System . out . println ( String . format ( "Sleeping %d seconds before shutdown to ensure all records are flushed." , EXPORT_INTERVAL ) ) ; Thread . sleep ( TimeUnit . MILLISECONDS . convert ( EXPORT_INTERVAL , TimeUnit . SECONDS ) ) ; }
Main launcher for the Stackdriver example .
467
8