idx
int64 0
41.2k
| question
stringlengths 83
4.15k
| target
stringlengths 5
715
|
|---|---|---|
35,200
|
public static boolean needsDoubleQuotes ( String s ) { assert s != null && ! s . isEmpty ( ) ; char c = s . charAt ( 0 ) ; if ( ! ( c >= 97 && c <= 122 ) ) return true ; for ( int i = 1 ; i < s . length ( ) ; i ++ ) { c = s . charAt ( i ) ; if ( ! ( ( c >= 48 && c <= 57 ) || ( c == 95 ) || ( c >= 97 && c <= 122 ) ) ) { return true ; } } return isReservedCqlKeyword ( s ) ; }
|
Whether a string needs double quotes to be a valid CQL identifier .
|
35,201
|
public static boolean isLongLiteral ( String str ) { if ( str == null || str . isEmpty ( ) ) return false ; char [ ] chars = str . toCharArray ( ) ; for ( int i = 0 ; i < chars . length ; i ++ ) { char c = chars [ i ] ; if ( ( c < '0' && ( i != 0 || c != '-' ) ) || c > '9' ) return false ; } return true ; }
|
Check whether the given string corresponds to a valid CQL long literal . Long literals are composed solely by digits but can have an optional leading minus sign .
|
35,202
|
public String asCql ( boolean pretty ) { if ( pretty ) { return Strings . needsDoubleQuotes ( internal ) ? Strings . doubleQuote ( internal ) : internal ; } else { return Strings . doubleQuote ( internal ) ; } }
|
Returns the identifier in a format appropriate for concatenation in a CQL query .
|
35,203
|
public Map < String , String > build ( ) { NullAllowingImmutableMap . Builder < String , String > builder = NullAllowingImmutableMap . builder ( 3 ) ; String compressionAlgorithm = context . getCompressor ( ) . algorithm ( ) ; if ( compressionAlgorithm != null && ! compressionAlgorithm . trim ( ) . isEmpty ( ) ) { builder . put ( Startup . COMPRESSION_KEY , compressionAlgorithm . trim ( ) ) ; } return builder . put ( DRIVER_NAME_KEY , getDriverName ( ) ) . put ( DRIVER_VERSION_KEY , getDriverVersion ( ) ) . build ( ) ; }
|
Builds a map of options to send in a Startup message .
|
35,204
|
private void connect ( ) { session = CqlSession . builder ( ) . build ( ) ; System . out . printf ( "Connected to session: %s%n" , session . getName ( ) ) ; }
|
Initiates a connection to the session specified by the application . conf .
|
35,205
|
private void write ( ConsistencyLevel cl , int retryCount ) { System . out . printf ( "Writing at %s (retry count: %d)%n" , cl , retryCount ) ; BatchStatement batch = BatchStatement . newInstance ( UNLOGGED ) . add ( SimpleStatement . newInstance ( "INSERT INTO downgrading.sensor_data " + "(sensor_id, date, timestamp, value) " + "VALUES (" + "756716f7-2e54-4715-9f00-91dcbea6cf50," + "'2018-02-26'," + "'2018-02-26T13:53:46.345+01:00'," + "2.34)" ) ) . add ( SimpleStatement . newInstance ( "INSERT INTO downgrading.sensor_data " + "(sensor_id, date, timestamp, value) " + "VALUES (" + "756716f7-2e54-4715-9f00-91dcbea6cf50," + "'2018-02-26'," + "'2018-02-26T13:54:27.488+01:00'," + "2.47)" ) ) . add ( SimpleStatement . newInstance ( "INSERT INTO downgrading.sensor_data " + "(sensor_id, date, timestamp, value) " + "VALUES (" + "756716f7-2e54-4715-9f00-91dcbea6cf50," + "'2018-02-26'," + "'2018-02-26T13:56:33.739+01:00'," + "2.52)" ) ) . setConsistencyLevel ( cl ) ; try { session . execute ( batch ) ; System . out . println ( "Write succeeded at " + cl ) ; } catch ( DriverException e ) { if ( retryCount == maxRetries ) { throw e ; } e = unwrapAllNodesFailedException ( e ) ; System . out . println ( "Write failed: " + e ) ; if ( e instanceof UnavailableException ) { int aliveReplicas = ( ( UnavailableException ) e ) . getAlive ( ) ; ConsistencyLevel downgraded = downgrade ( cl , aliveReplicas , e ) ; write ( downgraded , retryCount + 1 ) ; } else if ( e instanceof WriteTimeoutException ) { DefaultWriteType writeType = ( DefaultWriteType ) ( ( WriteTimeoutException ) e ) . getWriteType ( ) ; int acknowledgements = ( ( WriteTimeoutException ) e ) . getReceived ( ) ; switch ( writeType ) { case SIMPLE : case BATCH : if ( acknowledgements == 0 ) { throw e ; } break ; case UNLOGGED_BATCH : ConsistencyLevel downgraded = downgrade ( cl , acknowledgements , e ) ; write ( downgraded , retryCount + 1 ) ; break ; case BATCH_LOG : write ( cl , retryCount + 1 ) ; break ; default : throw e ; } } else { write ( cl , retryCount + 1 ) ; } } }
|
Inserts data retrying if necessary with a downgraded CL .
|
35,206
|
private ResultSet read ( ConsistencyLevel cl , int retryCount ) { System . out . printf ( "Reading at %s (retry count: %d)%n" , cl , retryCount ) ; Statement stmt = SimpleStatement . newInstance ( "SELECT sensor_id, date, timestamp, value " + "FROM downgrading.sensor_data " + "WHERE " + "sensor_id = 756716f7-2e54-4715-9f00-91dcbea6cf50 AND " + "date = '2018-02-26' AND " + "timestamp > '2018-02-26+01:00'" ) . setConsistencyLevel ( cl ) ; try { ResultSet rows = session . execute ( stmt ) ; System . out . println ( "Read succeeded at " + cl ) ; return rows ; } catch ( DriverException e ) { if ( retryCount == maxRetries ) { throw e ; } e = unwrapAllNodesFailedException ( e ) ; System . out . println ( "Read failed: " + e ) ; if ( e instanceof UnavailableException ) { int aliveReplicas = ( ( UnavailableException ) e ) . getAlive ( ) ; ConsistencyLevel downgraded = downgrade ( cl , aliveReplicas , e ) ; return read ( downgraded , retryCount + 1 ) ; } else if ( e instanceof ReadTimeoutException ) { ReadTimeoutException readTimeout = ( ReadTimeoutException ) e ; int received = readTimeout . getReceived ( ) ; int required = readTimeout . getBlockFor ( ) ; if ( received < required ) { ConsistencyLevel downgraded = downgrade ( cl , received , e ) ; return read ( downgraded , retryCount + 1 ) ; } if ( ! readTimeout . wasDataPresent ( ) ) { return read ( cl , retryCount + 1 ) ; } throw e ; } else { return read ( cl , retryCount + 1 ) ; } } }
|
Queries data retrying if necessary with a downgraded CL .
|
35,207
|
private void display ( ResultSet rows ) { final int width1 = 38 ; final int width2 = 12 ; final int width3 = 30 ; final int width4 = 21 ; String format = "%-" + width1 + "s%-" + width2 + "s%-" + width3 + "s%-" + width4 + "s%n" ; System . out . printf ( format , "sensor_id" , "date" , "timestamp" , "value" ) ; drawLine ( width1 , width2 , width3 , width4 ) ; for ( Row row : rows ) { System . out . printf ( format , row . getUuid ( "sensor_id" ) , row . getLocalDate ( "date" ) , row . getInstant ( "timestamp" ) , row . getDouble ( "value" ) ) ; } }
|
Displays the results on the console .
|
35,208
|
private static ConsistencyLevel downgrade ( ConsistencyLevel current , int acknowledgements , DriverException original ) { if ( acknowledgements >= 3 ) { return DefaultConsistencyLevel . THREE ; } if ( acknowledgements == 2 ) { return DefaultConsistencyLevel . TWO ; } if ( acknowledgements == 1 ) { return DefaultConsistencyLevel . ONE ; } if ( current == DefaultConsistencyLevel . EACH_QUORUM ) { return DefaultConsistencyLevel . ONE ; } throw original ; }
|
Downgrades the current consistency level to the highest level that is likely to succeed given the number of acknowledgements received . Rethrows the original exception if the current consistency level cannot be downgraded any further .
|
35,209
|
private static void drawLine ( int ... widths ) { for ( int width : widths ) { for ( int i = 1 ; i < width ; i ++ ) { System . out . print ( '-' ) ; } System . out . print ( '+' ) ; } System . out . println ( ) ; }
|
Draws a line to isolate headings from rows .
|
35,210
|
public void querySchema ( ) { ResultSet results = session . execute ( "SELECT * FROM simplex.playlists " + "WHERE id = 2cc9ccb7-6221-4ccb-8387-f22b6a1b354d;" ) ; System . out . printf ( "%-30s\t%-20s\t%-20s%n" , "title" , "album" , "artist" ) ; System . out . println ( "-------------------------------+-----------------------+--------------------" ) ; for ( Row row : results ) { System . out . printf ( "%-30s\t%-20s\t%-20s%n" , row . getString ( "title" ) , row . getString ( "album" ) , row . getString ( "artist" ) ) ; } }
|
Queries and displays data .
|
35,211
|
public static Class < ? > loadClass ( ClassLoader classLoader , String className ) { try { ClassLoader cl = classLoader != null ? classLoader : Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( cl != null ) { return Class . forName ( className , true , cl ) ; } else { return Class . forName ( className ) ; } } catch ( ClassNotFoundException e ) { return null ; } }
|
Loads a class by name .
|
35,212
|
public static < ComponentT > Optional < ComponentT > buildFromConfig ( InternalDriverContext context , DriverOption classNameOption , Class < ComponentT > expectedSuperType , String ... defaultPackages ) { return buildFromConfig ( context , null , classNameOption , expectedSuperType , defaultPackages ) ; }
|
Tries to create an instance of a class given an option defined in the driver configuration .
|
35,213
|
public static < ComponentT > Map < String , ComponentT > buildFromConfigProfiles ( InternalDriverContext context , DriverOption rootOption , Class < ComponentT > expectedSuperType , String ... defaultPackages ) { ListMultimap < Object , String > profilesByConfig = MultimapBuilder . hashKeys ( ) . arrayListValues ( ) . build ( ) ; for ( DriverExecutionProfile profile : context . getConfig ( ) . getProfiles ( ) . values ( ) ) { profilesByConfig . put ( profile . getComparisonKey ( rootOption ) , profile . getName ( ) ) ; } ImmutableMap . Builder < String , ComponentT > result = ImmutableMap . builder ( ) ; for ( Collection < String > profiles : profilesByConfig . asMap ( ) . values ( ) ) { String profileName = profiles . iterator ( ) . next ( ) ; ComponentT policy = buildFromConfig ( context , profileName , classOption ( rootOption ) , expectedSuperType , defaultPackages ) . orElseThrow ( ( ) -> new IllegalArgumentException ( String . format ( "Missing configuration for %s in profile %s" , rootOption . getPath ( ) , profileName ) ) ) ; for ( String profile : profiles ) { result . put ( profile , policy ) ; } } return result . build ( ) ; }
|
Tries to create multiple instances of a class given options defined in the driver configuration and possibly overridden in profiles .
|
35,214
|
public Map < CqlIdentifier , UserDefinedType > parse ( Collection < AdminRow > typeRows , CqlIdentifier keyspaceId ) { if ( typeRows . isEmpty ( ) ) { return Collections . emptyMap ( ) ; } else { Map < CqlIdentifier , UserDefinedType > types = new LinkedHashMap < > ( ) ; for ( AdminRow row : topologicalSort ( typeRows , keyspaceId ) ) { UserDefinedType type = parseType ( row , keyspaceId , types ) ; types . put ( type . getName ( ) , type ) ; } return ImmutableMap . copyOf ( types ) ; } }
|
Contrary to other element parsers this one processes all the types of a keyspace in one go . UDTs can depend on each other but the system table returns them in alphabetical order . In order to properly build the definitions we need to do a topological sort of the rows first so that each type is parsed after its dependencies .
|
35,215
|
public CompletionStage < Void > init ( boolean listenToClusterEvents , boolean reconnectOnFailure , boolean useInitialReconnectionSchedule ) { RunOrSchedule . on ( adminExecutor , ( ) -> singleThreaded . init ( listenToClusterEvents , reconnectOnFailure , useInitialReconnectionSchedule ) ) ; return singleThreaded . initFuture ; }
|
Initializes the control connection . If it is already initialized this is a no - op and all parameters are ignored .
|
35,216
|
public CompletionStage < Void > setKeyspace ( CqlIdentifier newKeyspaceName ) { return RunOrSchedule . on ( adminExecutor , ( ) -> singleThreaded . setKeyspace ( newKeyspaceName ) ) ; }
|
Changes the keyspace name on all the channels in this pool .
|
35,217
|
public List < String > getPreReleaseLabels ( ) { return preReleases == null ? null : Collections . unmodifiableList ( Arrays . asList ( preReleases ) ) ; }
|
The pre - release labels if relevant i . e . label1 and label2 in X . Y . Z - label1 - lable2 .
|
35,218
|
private void processNodeStateEvent ( NodeStateEvent event ) { switch ( stateRef . get ( ) ) { case BEFORE_INIT : case DURING_INIT : throw new AssertionError ( "Filter should not be marked ready until LBP init" ) ; case CLOSING : return ; case RUNNING : for ( LoadBalancingPolicy policy : policies ) { if ( event . newState == NodeState . UP ) { policy . onUp ( event . node ) ; } else if ( event . newState == NodeState . DOWN || event . newState == NodeState . FORCED_DOWN ) { policy . onDown ( event . node ) ; } else if ( event . newState == NodeState . UNKNOWN ) { policy . onAdd ( event . node ) ; } else if ( event . newState == null ) { policy . onRemove ( event . node ) ; } else { LOG . warn ( "[{}] Unsupported event: {}" , logPrefix , event ) ; } } break ; } }
|
once it has gone through the filter
|
35,219
|
static String reverse ( InetAddress address ) { byte [ ] bytes = address . getAddress ( ) ; if ( bytes . length == 4 ) return reverseIpv4 ( bytes ) ; else return reverseIpv6 ( bytes ) ; }
|
Builds the reversed domain name in the ARPA domain to perform the reverse lookup
|
35,220
|
public int firstIndexOf ( CqlIdentifier id ) { Integer index = byId . get ( id ) ; return ( index == null ) ? - 1 : index ; }
|
Returns the first occurrence of a given identifier or - 1 if it s not in the list .
|
35,221
|
private static void insertWithCoreApi ( CqlSession session ) { session . execute ( SimpleStatement . newInstance ( "INSERT INTO examples.querybuilder_json JSON ?" , "{ \"id\": 1, \"name\": \"Mouse\", \"specs\": { \"color\": \"silver\" } }" ) ) ; PreparedStatement pst = session . prepare ( "INSERT INTO examples.querybuilder_json JSON :payload" ) ; session . execute ( pst . bind ( ) . setString ( "payload" , "{ \"id\": 2, \"name\": \"Keyboard\", \"specs\": { \"layout\": \"qwerty\" } }" ) ) ; session . execute ( SimpleStatement . newInstance ( "INSERT INTO examples.querybuilder_json " + "(id, name, specs) VALUES (?, ?, fromJson(?))" , 3 , "Screen" , "{ \"size\": \"24-inch\" }" ) ) ; }
|
Demonstrates data insertion with the core API i . e . providing the full query strings .
|
35,222
|
private static void selectWithCoreApi ( CqlSession session ) { Row row = session . execute ( SimpleStatement . newInstance ( "SELECT JSON * FROM examples.querybuilder_json WHERE id = ?" , 1 ) ) . one ( ) ; assert row != null ; System . out . printf ( "Entry #1 as JSON: %s%n" , row . getString ( "[json]" ) ) ; row = session . execute ( SimpleStatement . newInstance ( "SELECT id, toJson(specs) AS json_specs FROM examples.querybuilder_json WHERE id = ?" , 2 ) ) . one ( ) ; assert row != null ; System . out . printf ( "Entry #%d's specs as JSON: %s%n" , row . getInt ( "id" ) , row . getString ( "json_specs" ) ) ; }
|
Demonstrates data retrieval with the core API i . e . providing the full query strings .
|
35,223
|
public UserDefinedTypeBuilder withField ( CqlIdentifier name , DataType type ) { fieldNames . add ( name ) ; fieldTypes . add ( type ) ; return this ; }
|
Adds a new field . The fields in the resulting type will be in the order of the calls to this method .
|
35,224
|
public DefaultMetadata withNodes ( Map < UUID , Node > newNodes , boolean tokenMapEnabled , boolean tokensChanged , TokenFactory tokenFactory , InternalDriverContext context ) { boolean forceFullRebuild = tokensChanged || ! newNodes . equals ( nodes ) ; return new DefaultMetadata ( ImmutableMap . copyOf ( newNodes ) , this . keyspaces , rebuildTokenMap ( newNodes , keyspaces , tokenMapEnabled , forceFullRebuild , tokenFactory , context ) ) ; }
|
Refreshes the current metadata with the given list of nodes .
|
35,225
|
private void sendRequest ( Node retriedNode , Queue < Node > queryPlan , int currentExecutionIndex , int retryCount , boolean scheduleNextExecution ) { if ( result . isDone ( ) ) { return ; } Node node = retriedNode ; DriverChannel channel = null ; if ( node == null || ( channel = session . getChannel ( node , logPrefix ) ) == null ) { while ( ! result . isDone ( ) && ( node = queryPlan . poll ( ) ) != null ) { channel = session . getChannel ( node , logPrefix ) ; if ( channel != null ) { break ; } } } if ( channel == null ) { if ( ! result . isDone ( ) && activeExecutionsCount . decrementAndGet ( ) == 0 ) { setFinalError ( AllNodesFailedException . fromErrors ( this . errors ) , null , - 1 ) ; } } else { NodeResponseCallback nodeResponseCallback = new NodeResponseCallback ( node , queryPlan , channel , currentExecutionIndex , retryCount , scheduleNextExecution , logPrefix ) ; channel . write ( message , statement . isTracing ( ) , statement . getCustomPayload ( ) , nodeResponseCallback ) . addListener ( nodeResponseCallback ) ; } }
|
Sends the request to the next available node .
|
35,226
|
private static void selectJsonRow ( CqlSession session ) { 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 ) { 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
|
35,227
|
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 ; )
|
35,228
|
public static int minimumRequestSize ( Request request ) { int size = FrameCodec . headerEncodedSize ( ) ; if ( ! request . getCustomPayload ( ) . isEmpty ( ) ) { size += PrimitiveSizes . sizeOfBytesMap ( request . getCustomPayload ( ) ) ; } return size ; }
|
Returns a common size for all kinds of Request implementations .
|
35,229
|
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 .
|
35,230
|
public static Integer sizeOfInnerBatchStatementInBytes ( BatchableStatement statement , ProtocolVersion protocolVersion , CodecRegistry codecRegistry ) { int size = 0 ; size += PrimitiveSizes . BYTE ; 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 .
|
35,231
|
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
|
35,232
|
public void cancel ( ResponseCallback responseCallback ) { writeCoalescer . writeAndFlush ( channel , responseCallback ) . addListener ( UncaughtExceptions :: log ) ; }
|
Cancels a callback indicating that the client that wrote it is no longer interested in the answer .
|
35,233
|
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 .
|
35,234
|
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 .
|
35,235
|
public CompletionStage < SessionT > buildAsync ( ) { CompletionStage < CqlSession > buildStage = buildDefaultSessionAsync ( ) ; CompletionStage < SessionT > wrapStage = buildStage . thenApply ( this :: wrap ) ; CompletableFutures . propagateCancellation ( wrapStage , buildStage ) ; return wrapStage ; }
|
Creates the session with the options set by this builder .
|
35,236
|
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
|
35,237
|
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 .
|
35,238
|
private Supplier getFormatterForType ( String type ) { switch ( type ) { case "s" : if ( ! lastContents . isEmpty ( ) ) { int idx = Integer . parseInt ( lastContents ) ; return new StringSupplier ( new XSSFRichTextString ( sst . getEntryAt ( idx ) ) . toString ( ) ) ; } return new StringSupplier ( lastContents ) ; case "inlineStr" : case "str" : return new StringSupplier ( new XSSFRichTextString ( lastContents ) . toString ( ) ) ; case "e" : return new StringSupplier ( "ERROR: " + lastContents ) ; case "n" : if ( currentCell . getNumericFormat ( ) != null && lastContents . length ( ) > 0 ) { final String currentLastContents = lastContents ; final int currentNumericFormatIndex = currentCell . getNumericFormatIndex ( ) ; final String currentNumericFormat = currentCell . getNumericFormat ( ) ; return new Supplier ( ) { String cachedContent ; 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 .
|
35,239
|
String unformattedContents ( ) { switch ( currentCell . getType ( ) ) { case "s" : if ( ! lastContents . isEmpty ( ) ) { int idx = Integer . parseInt ( lastContents ) ; return new XSSFRichTextString ( sst . getEntryAt ( idx ) ) . toString ( ) ; } return lastContents ; case "inlineStr" : return new XSSFRichTextString ( lastContents ) . toString ( ) ; default : return lastContents ; } }
|
Returns the contents of the cell with no formatting applied
|
35,240
|
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 .
|
35,241
|
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 .
|
35,242
|
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 .
|
35,243
|
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 .
|
35,244
|
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
|
35,245
|
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
|
35,246
|
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 .
|
35,247
|
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
|
35,248
|
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
|
35,249
|
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 .
|
35,250
|
private void drawPart ( Canvas canvas , PagePart part ) { RectF pageRelativeBounds = part . getPageRelativeBounds ( ) ; Bitmap renderedBitmap = part . getRenderedBitmap ( ) ; 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 ) ; RectF dstRect = new RectF ( ( int ) offsetX , ( int ) offsetY , ( int ) ( offsetX + width ) , ( int ) ( offsetY + height ) ) ; 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 ) ; } canvas . translate ( - localTranslationX , - localTranslationY ) ; }
|
Draw a given PagePart on the canvas
|
35,251
|
public void loadPages ( ) { if ( optimalPageWidth == 0 || optimalPageHeight == 0 ) { return ; } renderingAsyncTask . removeAllTasks ( ) ; cacheManager . makeANewSet ( ) ; int index = currentPage ; if ( filteredUserPageIndexes != null ) { index = filteredUserPageIndexes [ currentPage ] ; } 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
|
35,252
|
public void loadComplete ( DecodeService decodeService ) { this . decodeService = decodeService ; this . documentPageCount = decodeService . getPageCount ( ) ; this . pageWidth = decodeService . getPageWidth ( 0 ) ; this . pageHeight = decodeService . getPageHeight ( 0 ) ; state = State . LOADED ; calculateOptimalWidthAndHeight ( ) ; jumpTo ( defaultPage ) ; if ( onLoadCompleteListener != null ) { onLoadCompleteListener . loadComplete ( documentPageCount ) ; } }
|
Called when the PDF is loaded
|
35,253
|
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 .
|
35,254
|
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 .
|
35,255
|
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
|
35,256
|
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 .
|
35,257
|
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 .
|
35,258
|
public void moveTo ( float offsetX , float offsetY ) { if ( swipeVertical ) { 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 ) ; } } 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 { 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 ) ; } } 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 .
|
35,259
|
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
|
35,260
|
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
|
35,261
|
@ 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 .
|
35,262
|
@ 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 .
|
35,263
|
@ 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 .
|
35,264
|
@ 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 .
|
35,265
|
@ 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 .
|
35,266
|
@ 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 .
|
35,267
|
@ 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 .
|
35,268
|
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 .
|
35,269
|
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 .
|
35,270
|
public static void premain ( String agentArgs , Instrumentation instrumentation ) throws Exception { checkNotNull ( instrumentation , "instrumentation" ) ; logger . fine ( "Initializing." ) ; 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 .
|
35,271
|
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 .
|
35,272
|
@ 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 .
|
35,273
|
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 .
|
35,274
|
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 .
|
35,275
|
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 .
|
35,276
|
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 .
|
35,277
|
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 .
|
35,278
|
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 .
|
35,279
|
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 .
|
35,280
|
static void unsafeResetExporter ( ) { synchronized ( monitor ) { if ( instance != null ) { instance . intervalMetricReader . stop ( ) ; } instance = null ; } }
|
Resets exporter to null . Used only for unit tests .
|
35,281
|
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 ) { metricProtos . add ( MetricsProtoUtils . toMetricProto ( metric , null ) ) ; } exportRpcHandler . onExport ( ExportMetricsServiceRequest . newBuilder ( ) . addAllMetrics ( metricProtos ) . build ( ) ) ; }
|
converts them to proto then exports them to OC - Agent .
|
35,282
|
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 .
|
35,283
|
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 .
|
35,284
|
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 .
|
35,285
|
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 .
|
35,286
|
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 ) ) { 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 ; } 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 .
|
35,287
|
static String generateFullMetricName ( String name , String type ) { return SOURCE + DELIMITER + name + DELIMITER + type ; }
|
Returns the metric name .
|
35,288
|
static String generateFullMetricDescription ( String metricName , Metric metric ) { return "Collected from " + SOURCE + " (metric=" + metricName + ", type=" + metric . getClass ( ) . getName ( ) + ")" ; }
|
Returns the metric description .
|
35,289
|
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 .
|
35,290
|
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 .
|
35,291
|
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 .
|
35,292
|
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 .
|
35,293
|
public final void handleMessageSent ( HttpRequestContext context , long bytes ) { checkNotNull ( context , "context" ) ; context . sentMessageSize . addAndGet ( bytes ) ; if ( context . span . getOptions ( ) . contains ( Options . RECORD_EVENTS ) ) { 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 .
|
35,294
|
public final void handleMessageReceived ( HttpRequestContext context , long bytes ) { checkNotNull ( context , "context" ) ; context . receiveMessageSize . addAndGet ( bytes ) ; if ( context . span . getOptions ( ) . contains ( Options . RECORD_EVENTS ) ) { 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 .
|
35,295
|
@ GuardedBy ( "monitor" ) private TreeNode findNode ( String path ) { if ( Strings . isNullOrEmpty ( path ) || "/" . equals ( path ) ) { 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 ; } if ( ! node . children . containsKey ( dir ) ) { return null ; } else { node = node . children . get ( dir ) ; } } return node ; } }
|
Returns null if such a TreeNode doesn t exist .
|
35,296
|
void record ( List < 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 .
|
35,297
|
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 ) ; 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
|
35,298
|
static LabelDescriptor createLabelDescriptor ( LabelKey labelKey ) { LabelDescriptor . Builder builder = LabelDescriptor . newBuilder ( ) ; builder . setKey ( labelKey . getKey ( ) ) ; builder . setDescription ( labelKey . getDescription ( ) ) ; builder . setValueType ( ValueType . STRING ) ; return builder . build ( ) ; }
|
Construct a LabelDescriptor from a LabelKey
|
35,299
|
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.