idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
158,700
synchronized void onExport ( ExportTraceServiceRequest request ) { if ( isCompleted ( ) || exportRequestObserver == null ) { return ; } try { exportRequestObserver . onNext ( request ) ; } catch ( Exception e ) { // Catch client side exceptions. onComplete ( e ) ; } }
Sends the export request to Agent if the stream is still connected otherwise do nothing .
67
17
158,701
public static Duration create ( long seconds , int nanos ) { if ( seconds < - MAX_SECONDS ) { throw new IllegalArgumentException ( "'seconds' is less than minimum (" + - MAX_SECONDS + "): " + seconds ) ; } if ( seconds > MAX_SECONDS ) { throw new IllegalArgumentException ( "'seconds' is greater than maximum (" + MAX_SECONDS + "): " + seconds ) ; } if ( nanos < - MAX_NANOS ) { throw new IllegalArgumentException ( "'nanos' is less than minimum (" + - MAX_NANOS + "): " + nanos ) ; } if ( nanos > MAX_NANOS ) { throw new IllegalArgumentException ( "'nanos' is greater than maximum (" + MAX_NANOS + "): " + nanos ) ; } if ( ( seconds < 0 && nanos > 0 ) || ( seconds > 0 && nanos < 0 ) ) { throw new IllegalArgumentException ( "'seconds' and 'nanos' have inconsistent sign: seconds=" + seconds + ", nanos=" + nanos ) ; } return new AutoValue_Duration ( seconds , nanos ) ; }
Creates a new time duration from given seconds and nanoseconds .
260
15
158,702
static Node getNodeInfo ( String serviceName ) { String jvmName = ManagementFactory . getRuntimeMXBean ( ) . getName ( ) ; Timestamp censusTimestamp = Timestamp . fromMillis ( System . currentTimeMillis ( ) ) ; return Node . newBuilder ( ) . setIdentifier ( getProcessIdentifier ( jvmName , censusTimestamp ) ) . setLibraryInfo ( getLibraryInfo ( OpenCensusLibraryInformation . VERSION ) ) . setServiceInfo ( getServiceInfo ( serviceName ) ) . build ( ) ; }
Creates a Node with information from the OpenCensus library and environment variables .
119
16
158,703
@ VisibleForTesting static LibraryInfo getLibraryInfo ( String currentOcJavaVersion ) { return LibraryInfo . newBuilder ( ) . setLanguage ( Language . JAVA ) . setCoreLibraryVersion ( currentOcJavaVersion ) . setExporterVersion ( OC_AGENT_EXPORTER_VERSION ) . build ( ) ; }
Creates library info with the given OpenCensus Java version .
73
13
158,704
@ VisibleForTesting static ServiceInfo getServiceInfo ( String serviceName ) { return ServiceInfo . newBuilder ( ) . setName ( serviceName ) . build ( ) ; }
Creates service info with the given service name .
38
10
158,705
public HttpRequestContext handleStart ( C carrier , Q request ) { checkNotNull ( carrier , "carrier" ) ; checkNotNull ( request , "request" ) ; SpanBuilder spanBuilder = null ; String spanName = getSpanName ( request , extractor ) ; // de-serialize the context SpanContext spanContext = null ; try { spanContext = textFormat . extract ( carrier , getter ) ; } catch ( SpanContextParseException e ) { // TODO: Currently we cannot distinguish between context parse error and missing context. // Logging would be annoying so we just ignore this error and do not even log a message. } if ( spanContext == null || publicEndpoint ) { spanBuilder = tracer . spanBuilder ( spanName ) ; } else { spanBuilder = tracer . spanBuilderWithRemoteParent ( spanName , spanContext ) ; } Span span = spanBuilder . setSpanKind ( Kind . SERVER ) . startSpan ( ) ; if ( publicEndpoint && spanContext != null ) { span . addLink ( Link . fromSpanContext ( spanContext , Type . PARENT_LINKED_SPAN ) ) ; } if ( span . getOptions ( ) . contains ( Options . RECORD_EVENTS ) ) { addSpanRequestAttributes ( span , request , extractor ) ; } return getNewContext ( span , tagger . getCurrentTagContext ( ) ) ; }
Instrument an incoming request before it is handled .
306
10
158,706
private Map < String , StatsSnapshot > getStatsSnapshots ( boolean isReceived ) { SortedMap < String , StatsSnapshot > map = Maps . newTreeMap ( ) ; // Sorted by method name. if ( isReceived ) { getStatsSnapshots ( map , SERVER_RPC_CUMULATIVE_VIEWS ) ; getStatsSnapshots ( map , SERVER_RPC_MINUTE_VIEWS ) ; getStatsSnapshots ( map , SERVER_RPC_HOUR_VIEWS ) ; } else { getStatsSnapshots ( map , CLIENT_RPC_CUMULATIVE_VIEWS ) ; getStatsSnapshots ( map , CLIENT_RPC_MINUTE_VIEWS ) ; getStatsSnapshots ( map , CLIENT_RPC_HOUR_VIEWS ) ; } return map ; }
Gets stats snapshot for each method .
183
8
158,707
private static double getDurationInSecs ( ViewData . AggregationWindowData . CumulativeData cumulativeData ) { return toDoubleSeconds ( cumulativeData . getEnd ( ) . subtractTimestamp ( cumulativeData . getStart ( ) ) ) ; }
Calculates the duration of the given CumulativeData in seconds .
53
14
158,708
public static void main ( String [ ] args ) throws InterruptedException { TagContextBuilder tagContextBuilder = tagger . currentBuilder ( ) . put ( FRONTEND_KEY , TagValue . create ( "mobile-ios9.3.5" ) ) ; SpanBuilder spanBuilder = tracer . spanBuilder ( "my.org/ProcessVideo" ) . setRecordEvents ( true ) . setSampler ( Samplers . alwaysSample ( ) ) ; viewManager . registerView ( VIDEO_SIZE_VIEW ) ; LoggingTraceExporter . register ( ) ; // Process video. // Record the processed video size. try ( Scope scopedTags = tagContextBuilder . buildScoped ( ) ; Scope scopedSpan = spanBuilder . startScopedSpan ( ) ) { tracer . getCurrentSpan ( ) . addAnnotation ( "Start processing video." ) ; // Sleep for [0,10] milliseconds to fake work. Thread . sleep ( new Random ( ) . nextInt ( 10 ) + 1 ) ; statsRecorder . newMeasureMap ( ) . put ( VIDEO_SIZE , 25 * MiB ) . record ( ) ; tracer . getCurrentSpan ( ) . addAnnotation ( "Finished processing video." ) ; } catch ( Exception e ) { tracer . getCurrentSpan ( ) . addAnnotation ( "Exception thrown when processing video." ) ; tracer . getCurrentSpan ( ) . setStatus ( Status . UNKNOWN ) ; logger . severe ( e . getMessage ( ) ) ; } logger . info ( "Wait longer than the reporting duration..." ) ; // Wait for a duration longer than reporting duration (5s) to ensure spans are exported. // TODO(songya): remove the gap once we add a shutdown hook for exporting unflushed spans. Thread . sleep ( 5100 ) ; ViewData viewData = viewManager . getView ( VIDEO_SIZE_VIEW_NAME ) ; logger . info ( String . format ( "Recorded stats for %s:\n %s" , VIDEO_SIZE_VIEW_NAME . asString ( ) , viewData ) ) ; }
Main launcher for the QuickStart example .
453
8
158,709
@ VisibleForTesting public static TagKey [ ] createTagKeys ( int size , String name ) { TagKey [ ] keys = new TagKey [ size ] ; for ( int i = 0 ; i < size ; i ++ ) { keys [ i ] = TagKey . create ( name + i ) ; } return keys ; }
Creates an array of TagKeys of size with name prefix .
70
13
158,710
@ VisibleForTesting public static TagValue [ ] createTagValues ( int size , String name ) { TagValue [ ] values = new TagValue [ size ] ; for ( int i = 0 ; i < size ; i ++ ) { values [ i ] = TagValue . create ( name + i ) ; } return values ; }
Creates an array of TagValues of size with name prefix .
70
13
158,711
@ VisibleForTesting public static TagContext createTagContext ( TagContextBuilder tagsBuilder , int numTags ) { for ( int i = 0 ; i < numTags ; i ++ ) { tagsBuilder . put ( TAG_KEYS . get ( i ) , TAG_VALUES . get ( i ) , UNLIMITED_PROPAGATION ) ; } return tagsBuilder . build ( ) ; }
Adds numTags tags to tagsBuilder and returns the associated tag context .
86
14
158,712
private static DisruptorEventQueue create ( ) { // Create new Disruptor for processing. Note that Disruptor creates a single thread per // consumer (see https://github.com/LMAX-Exchange/disruptor/issues/121 for details); // this ensures that the event handler can take unsynchronized actions whenever possible. Disruptor < DisruptorEvent > disruptor = new Disruptor <> ( DisruptorEventFactory . INSTANCE , DISRUPTOR_BUFFER_SIZE , new DaemonThreadFactory ( "OpenCensus.Disruptor" ) , ProducerType . MULTI , new SleepingWaitStrategy ( 0 , 1000 * 1000 ) ) ; disruptor . handleEventsWith ( new DisruptorEventHandler [ ] { DisruptorEventHandler . INSTANCE } ) ; disruptor . start ( ) ; final RingBuffer < DisruptorEvent > ringBuffer = disruptor . getRingBuffer ( ) ; DisruptorEnqueuer enqueuer = new DisruptorEnqueuer ( ) { @ Override public void enqueue ( Entry entry ) { long sequence = ringBuffer . next ( ) ; try { DisruptorEvent event = ringBuffer . get ( sequence ) ; event . setEntry ( entry ) ; } finally { ringBuffer . publish ( sequence ) ; } } } ; return new DisruptorEventQueue ( disruptor , enqueuer ) ; }
Creates a new EventQueue . Private to prevent creation of non - singleton instance .
302
18
158,713
@ Override public void shutdown ( ) { enqueuer = new DisruptorEnqueuer ( ) { final AtomicBoolean logged = new AtomicBoolean ( false ) ; @ Override public void enqueue ( Entry entry ) { if ( ! logged . getAndSet ( true ) ) { logger . log ( Level . INFO , "Attempted to enqueue entry after Disruptor shutdown." ) ; } } } ; disruptor . shutdown ( ) ; }
Shuts down the underlying disruptor .
97
8
158,714
public final Span getCurrentSpan ( ) { Span currentSpan = CurrentSpanUtils . getCurrentSpan ( ) ; return currentSpan != null ? currentSpan : BlankSpan . INSTANCE ; }
Gets the current Span from the current Context .
47
10
158,715
public static void unregister ( ) { synchronized ( monitor ) { checkState ( handler != null , "Zipkin exporter is not registered." ) ; unregister ( Tracing . getExportComponent ( ) . getSpanExporter ( ) ) ; handler = null ; } }
Unregisters the Zipkin Trace exporter from the OpenCensus library .
58
16
158,716
@ javax . annotation . Nullable static Span getCurrentSpan ( ) { SpanContext currentSpanContext = CURRENT_SPAN . get ( ) ; return currentSpanContext != null ? currentSpanContext . span : null ; }
Get the current span out of the thread context .
53
10
158,717
static void setCurrentSpan ( Span span ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "Setting current span " + span ) ; } push ( span , /* autoClose= */ false ) ; }
Set the current span in the thread context
50
8
158,718
static void close ( SpanFunction spanFunction ) { SpanContext current = CURRENT_SPAN . get ( ) ; while ( current != null ) { spanFunction . apply ( current . span ) ; current = removeCurrentSpanInternal ( current . parent ) ; if ( current == null || ! current . autoClose ) { return ; } } }
will be applied on the closed Span .
72
8
158,719
static void push ( Span span , boolean autoClose ) { if ( isCurrent ( span ) ) { return ; } setSpanContextInternal ( new SpanContext ( span , autoClose ) ) ; }
Push a span into the thread context with the option to have it auto close if any child spans are themselves closed . Use autoClose = true if you start a new span with a parent that wasn t already in thread context .
42
45
158,720
public static void main ( String ... args ) { // Step 1. Enable OpenCensus Metrics. try { setupOpenCensusAndPrometheusExporter ( ) ; } catch ( IOException e ) { System . err . println ( "Failed to create and register OpenCensus Prometheus Stats exporter " + e ) ; return ; } BufferedReader stdin = new BufferedReader ( new InputStreamReader ( System . in ) ) ; while ( true ) { try { readEvaluateProcessLine ( stdin ) ; } catch ( IOException e ) { System . err . println ( "EOF bye " + e ) ; return ; } catch ( Exception e ) { recordTaggedStat ( KEY_METHOD , "repl" , M_ERRORS , new Long ( 1 ) ) ; return ; } } }
Main launcher for the Repl example .
173
7
158,721
@ javax . annotation . Nullable public String get ( String key ) { for ( Entry entry : getEntries ( ) ) { if ( entry . getKey ( ) . equals ( key ) ) { return entry . getValue ( ) ; } } return null ; }
Returns the value to which the specified key is mapped or null if this map contains no mapping for the key .
58
22
158,722
private static boolean validateValue ( String value ) { if ( value . length ( ) > VALUE_MAX_SIZE || value . charAt ( value . length ( ) - 1 ) == ' ' /* '\u0020' */ ) { return false ; } for ( int i = 0 ; i < value . length ( ) ; i ++ ) { char c = value . charAt ( i ) ; if ( c == ' ' || c == ' ' || c < ' ' /* '\u0020' */ || c > ' ' /* '\u007E' */ ) { return false ; } } return true ; }
0x20 to 0x7E ) except comma and = .
133
14
158,723
@ Benchmark @ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public TagContext timeNestedTagContext ( Data data ) { return TagsBenchmarksUtil . createTagContext ( data . tagger . toBuilder ( data . baseTagContext ) , data . numTags ) ; }
Build nested tag context .
74
5
158,724
public static void createAndRegister ( final String thriftEndpoint , final String serviceName ) { synchronized ( monitor ) { checkState ( handler == null , "Jaeger exporter is already registered." ) ; final SpanExporter . Handler newHandler = newHandler ( thriftEndpoint , serviceName ) ; JaegerTraceExporter . handler = newHandler ; register ( Tracing . getExportComponent ( ) . getSpanExporter ( ) , newHandler ) ; } }
Creates and registers the Jaeger Trace exporter to the OpenCensus library . Only one Jaeger exporter can be registered at any point .
102
30
158,725
public static void createWithSender ( final ThriftSender sender , final String serviceName ) { synchronized ( monitor ) { checkState ( handler == null , "Jaeger exporter is already registered." ) ; final SpanExporter . Handler newHandler = newHandlerWithSender ( sender , serviceName ) ; JaegerTraceExporter . handler = newHandler ; register ( Tracing . getExportComponent ( ) . getSpanExporter ( ) , newHandler ) ; } }
Creates and registers the Jaeger Trace exporter to the OpenCensus library using the provided HttpSender . Only one Jaeger exporter can be registered at any point .
103
37
158,726
private static void performWork ( Span parent ) { SpanBuilder spanBuilder = tracer . spanBuilderWithExplicitParent ( "internal_work" , parent ) . setRecordEvents ( true ) . setSampler ( Samplers . alwaysSample ( ) ) ; try ( Scope scope = spanBuilder . startScopedSpan ( ) ) { Span span = tracer . getCurrentSpan ( ) ; span . putAttribute ( "my_attribute" , AttributeValue . stringAttributeValue ( "blue" ) ) ; span . addAnnotation ( "Performing work." ) ; sleepFor ( 20 ) ; // Working hard here. span . addAnnotation ( "Done work." ) ; } }
A helper function that performs some work in its own Span .
148
12
158,727
@ SuppressWarnings ( "deprecation" ) private static void emitTraceParamsTable ( TraceParams params , PrintWriter out ) { out . write ( "<b class=\"title\">Active tracing parameters:</b><br>\n" + "<table class=\"small\" rules=\"all\">\n" + " <tr>\n" + " <td class=\"col_headR\">Name</td>\n" + " <td class=\"col_head\">Value</td>\n" + " </tr>\n" ) ; out . printf ( " <tr>%n <td>Sampler</td>%n <td>%s</td>%n </tr>%n" , params . getSampler ( ) . getDescription ( ) ) ; out . printf ( " <tr>%n <td>MaxNumberOfAttributes</td>%n <td>%d</td>%n </tr>%n" , params . getMaxNumberOfAttributes ( ) ) ; out . printf ( " <tr>%n <td>MaxNumberOfAnnotations</td>%n <td>%d</td>%n </tr>%n" , params . getMaxNumberOfAnnotations ( ) ) ; out . printf ( " <tr>%n <td>MaxNumberOfNetworkEvents</td>%n <td>%d</td>%n </tr>%n" , params . getMaxNumberOfNetworkEvents ( ) ) ; out . printf ( " <tr>%n <td>MaxNumberOfLinks</td>%n <td>%d</td>%n </tr>%n" , params . getMaxNumberOfLinks ( ) ) ; out . write ( "</table>\n" ) ; }
Prints a table to a PrintWriter that shows existing trace parameters .
391
14
158,728
@ Benchmark @ BenchmarkMode ( Mode . SampleTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Span putAttribute ( Data data ) { data . span . putAttribute ( ATTRIBUTE_KEY , AttributeValue . stringAttributeValue ( ATTRIBUTE_VALUE ) ) ; return data . span ; }
This benchmark attempts to measure performance of adding an attribute to the span .
74
14
158,729
@ Benchmark @ BenchmarkMode ( Mode . SampleTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Span addAnnotation ( Data data ) { data . span . addAnnotation ( ANNOTATION_DESCRIPTION ) ; return data . span ; }
This benchmark attempts to measure performance of adding an annotation to the span .
60
14
158,730
@ Benchmark @ BenchmarkMode ( Mode . SampleTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Span addMessageEvent ( Data data ) { data . span . addMessageEvent ( io . opencensus . trace . MessageEvent . builder ( Type . RECEIVED , 1 ) . setUncompressedMessageSize ( 3 ) . build ( ) ) ; return data . span ; }
This benchmark attempts to measure performance of adding a network event to the span .
90
15
158,731
@ Benchmark @ BenchmarkMode ( Mode . SampleTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Span addLink ( Data data ) { data . span . addLink ( Link . fromSpanContext ( data . linkedSpan . getContext ( ) , Link . Type . PARENT_LINKED_SPAN ) ) ; return data . span ; }
This benchmark attempts to measure performance of adding a link to the span .
84
14
158,732
static OcAgentMetricsServiceExportRpcHandler create ( MetricsServiceStub stub ) { OcAgentMetricsServiceExportRpcHandler exportRpcHandler = new OcAgentMetricsServiceExportRpcHandler ( ) ; ExportResponseObserver exportResponseObserver = new ExportResponseObserver ( exportRpcHandler ) ; try { StreamObserver < ExportMetricsServiceRequest > exportRequestObserver = stub . export ( exportResponseObserver ) ; exportRpcHandler . setExportRequestObserver ( exportRequestObserver ) ; } catch ( StatusRuntimeException e ) { exportRpcHandler . onComplete ( e ) ; } return exportRpcHandler ; }
given MetricsServiceStub .
143
7
158,733
public static Timestamp create ( long seconds , int nanos ) { if ( seconds < - MAX_SECONDS ) { throw new IllegalArgumentException ( "'seconds' is less than minimum (" + - MAX_SECONDS + "): " + seconds ) ; } if ( seconds > MAX_SECONDS ) { throw new IllegalArgumentException ( "'seconds' is greater than maximum (" + MAX_SECONDS + "): " + seconds ) ; } if ( nanos < 0 ) { throw new IllegalArgumentException ( "'nanos' is less than zero: " + nanos ) ; } if ( nanos > MAX_NANOS ) { throw new IllegalArgumentException ( "'nanos' is greater than maximum (" + MAX_NANOS + "): " + nanos ) ; } return new AutoValue_Timestamp ( seconds , nanos ) ; }
Creates a new timestamp from given seconds and nanoseconds .
188
14
158,734
public static Timestamp fromMillis ( long epochMilli ) { long secs = floorDiv ( epochMilli , MILLIS_PER_SECOND ) ; int mos = ( int ) floorMod ( epochMilli , MILLIS_PER_SECOND ) ; return create ( secs , ( int ) ( mos * NANOS_PER_MILLI ) ) ; // Safe int * NANOS_PER_MILLI }
Creates a new timestamp from the given milliseconds .
94
10
158,735
private Timestamp plus ( long secondsToAdd , long nanosToAdd ) { if ( ( secondsToAdd | nanosToAdd ) == 0 ) { return this ; } long epochSec = TimeUtils . checkedAdd ( getSeconds ( ) , secondsToAdd ) ; epochSec = TimeUtils . checkedAdd ( epochSec , nanosToAdd / NANOS_PER_SECOND ) ; nanosToAdd = nanosToAdd % NANOS_PER_SECOND ; long nanoAdjustment = getNanos ( ) + nanosToAdd ; // safe int + NANOS_PER_SECOND return ofEpochSecond ( epochSec , nanoAdjustment ) ; }
Returns a Timestamp with the specified duration added .
149
10
158,736
private static long floorDiv ( long x , long y ) { return BigDecimal . valueOf ( x ) . divide ( BigDecimal . valueOf ( y ) , 0 , RoundingMode . FLOOR ) . longValue ( ) ; }
Returns the result of dividing x by y rounded using floor .
53
12
158,737
private static Map < String , String > initializeAwsIdentityDocument ( ) { InputStream stream = null ; try { stream = openStream ( AWS_INSTANCE_IDENTITY_DOCUMENT_URI ) ; String awsIdentityDocument = slurp ( new InputStreamReader ( stream , Charset . forName ( "UTF-8" ) ) ) ; return parseAwsIdentityDocument ( awsIdentityDocument ) ; } catch ( IOException e ) { // Cannot connect to http://169.254.169.254/latest/dynamic/instance-identity/document. // Not on an AWS EC2 instance. } finally { if ( stream != null ) { try { stream . close ( ) ; } catch ( IOException e ) { // Do nothing. } } } return Collections . emptyMap ( ) ; }
This method should only be called once .
178
8
158,738
private static Set < View > filterExportedViews ( Collection < View > allViews ) { Set < View > views = Sets . newHashSet ( ) ; for ( View view : allViews ) { if ( view . getWindow ( ) instanceof View . AggregationWindow . Cumulative ) { views . add ( view ) ; } } return Collections . unmodifiableSet ( views ) ; }
Returns the subset of the given views that should be exported
86
11
158,739
synchronized void record ( TagContext tags , MeasureMapInternal stats , Timestamp timestamp ) { Iterator < Measurement > iterator = stats . iterator ( ) ; Map < String , AttachmentValue > attachments = stats . getAttachments ( ) ; while ( iterator . hasNext ( ) ) { Measurement measurement = iterator . next ( ) ; Measure measure = measurement . getMeasure ( ) ; if ( ! measure . equals ( registeredMeasures . get ( measure . getName ( ) ) ) ) { // unregistered measures will be ignored. continue ; } Collection < MutableViewData > viewDataCollection = mutableMap . get ( measure . getName ( ) ) ; for ( MutableViewData viewData : viewDataCollection ) { viewData . record ( tags , RecordUtils . getDoubleValueFromMeasurement ( measurement ) , timestamp , attachments ) ; } } }
Records stats with a set of tags .
184
9
158,740
synchronized void clearStats ( ) { for ( Entry < String , Collection < MutableViewData > > entry : mutableMap . asMap ( ) . entrySet ( ) ) { for ( MutableViewData mutableViewData : entry . getValue ( ) ) { mutableViewData . clearStats ( ) ; } } }
Clear stats for all the current MutableViewData
72
10
158,741
synchronized void resumeStatsCollection ( Timestamp now ) { for ( Entry < String , Collection < MutableViewData > > entry : mutableMap . asMap ( ) . entrySet ( ) ) { for ( MutableViewData mutableViewData : entry . getValue ( ) ) { mutableViewData . resumeStatsCollection ( now ) ; } } }
Resume stats collection for all MutableViewData .
78
11
158,742
@ VisibleForTesting static ProcessIdentifier getProcessIdentifier ( String jvmName , Timestamp censusTimestamp ) { String hostname ; int pid ; // jvmName should be something like '<pid>@<hostname>', at least in Oracle and OpenJdk JVMs int delimiterIndex = jvmName . indexOf ( ' ' ) ; if ( delimiterIndex < 1 ) { // Not the expected format, generate a random number. try { hostname = InetAddress . getLocalHost ( ) . getHostName ( ) ; } catch ( UnknownHostException e ) { hostname = "localhost" ; } // Generate a random number as the PID. pid = new SecureRandom ( ) . nextInt ( ) ; } else { hostname = jvmName . substring ( delimiterIndex + 1 , jvmName . length ( ) ) ; try { pid = Integer . parseInt ( jvmName . substring ( 0 , delimiterIndex ) ) ; } catch ( NumberFormatException e ) { // Generate a random number as the PID if format is unexpected. pid = new SecureRandom ( ) . nextInt ( ) ; } } return ProcessIdentifier . newBuilder ( ) . setHostName ( hostname ) . setPid ( pid ) . setStartTimestamp ( MetricsProtoUtils . toTimestampProto ( censusTimestamp ) ) . build ( ) ; }
Creates process identifier with the given JVM name and start time .
303
14
158,743
public static void main ( String [ ] args ) throws InterruptedException { configureAlwaysSample ( ) ; // Always sample for demo purpose. DO NOT use in production. registerAllViews ( ) ; LongGauge gauge = registerGauge ( ) ; String endPoint = getStringOrDefaultFromArgs ( args , 0 , DEFAULT_ENDPOINT ) ; registerAgentExporters ( endPoint ) ; try ( Scope scope = tracer . spanBuilder ( "root" ) . startScopedSpan ( ) ) { int iteration = 1 ; while ( true ) { doWork ( iteration , random . nextInt ( 10 ) , gauge ) ; iteration ++ ; Thread . sleep ( 5000 ) ; } } catch ( InterruptedException e ) { logger . info ( "Thread interrupted, exiting in 5 seconds." ) ; Thread . sleep ( 5000 ) ; // Wait 5s so that last batch will be exported. } }
Main launcher of the example .
195
6
158,744
public State get ( ) { InternalState internalState = currentInternalState . get ( ) ; while ( ! internalState . isRead ) { // Slow path, the state is first time read. Change the state only if no other changes // happened between the moment initialState is read and this moment. This ensures that this // method only changes the isRead part of the internal state. currentInternalState . compareAndSet ( internalState , internalState . state == State . ENABLED ? InternalState . ENABLED_READ : InternalState . DISABLED_READ ) ; internalState = currentInternalState . get ( ) ; } return internalState . state ; }
Returns the current state and updates the status as being read .
140
12
158,745
public boolean set ( State state ) { while ( true ) { InternalState internalState = currentInternalState . get ( ) ; checkState ( ! internalState . isRead , "State was already read, cannot set state." ) ; if ( state == internalState . state ) { return false ; } else { if ( ! currentInternalState . compareAndSet ( internalState , state == State . ENABLED ? InternalState . ENABLED_NOT_READ : InternalState . DISABLED_NOT_READ ) ) { // The state was changed between the moment the internalState was read and this point. // Some conditions may be not correct, reset at the beginning and recheck all conditions. continue ; } return true ; } } }
Sets current state to the given state . Returns true if the current state is changed false otherwise .
157
20
158,746
private static int encodeTag ( Tag tag , StringBuilder stringBuilder ) { String key = tag . getKey ( ) . getName ( ) ; String value = tag . getValue ( ) . asString ( ) ; int charsOfTag = key . length ( ) + value . length ( ) ; // This should never happen with our current constraints (<= 255 chars) on tags. checkArgument ( charsOfTag <= TAG_SERIALIZED_SIZE_LIMIT , "Serialized size of tag " + tag + " exceeds limit " + TAG_SERIALIZED_SIZE_LIMIT ) ; // TODO(songy23): do we want to encode TagMetadata? stringBuilder . append ( key ) . append ( TAG_KEY_VALUE_DELIMITER ) . append ( value ) ; return charsOfTag ; }
Encodes the tag to the given string builder and returns the length of encoded key - value pair .
180
20
158,747
private static void decodeTag ( String stringTag , Map < TagKey , TagValueWithMetadata > tags ) { String keyWithValue ; int firstPropertyIndex = stringTag . indexOf ( TAG_PROPERTIES_DELIMITER ) ; if ( firstPropertyIndex != - 1 ) { // Tag with properties. keyWithValue = stringTag . substring ( 0 , firstPropertyIndex ) ; // TODO(songya): support decoding tag properties. } else { // Tag without properties. keyWithValue = stringTag ; } List < String > keyValuePair = TAG_KEY_VALUE_SPLITTER . splitToList ( keyWithValue ) ; checkArgument ( keyValuePair . size ( ) == 2 , "Malformed tag " + stringTag ) ; TagKey key = TagKey . create ( keyValuePair . get ( 0 ) . trim ( ) ) ; TagValue value = TagValue . create ( keyValuePair . get ( 1 ) . trim ( ) ) ; TagValueWithMetadata valueWithMetadata = TagValueWithMetadata . create ( value , METADATA_UNLIMITED_PROPAGATION ) ; tags . put ( key , valueWithMetadata ) ; }
The format of encoded string tag is name1 = value1 ; properties1 = p1 ; properties2 = p2 .
264
25
158,748
private static void emitSpans ( PrintWriter out , Formatter formatter , Collection < SpanData > spans ) { out . write ( "<pre>\n" ) ; formatter . format ( "%-23s %18s%n" , "When" , "Elapsed(s)" ) ; out . write ( "-------------------------------------------\n" ) ; for ( SpanData span : spans ) { tracer . getCurrentSpan ( ) . addAnnotation ( "Render span." , ImmutableMap . < String , AttributeValue > builder ( ) . put ( "SpanId" , AttributeValue . stringAttributeValue ( BaseEncoding . base16 ( ) . lowerCase ( ) . encode ( span . getContext ( ) . getSpanId ( ) . getBytes ( ) ) ) ) . build ( ) ) ; emitSingleSpan ( formatter , span ) ; } out . write ( "</pre>\n" ) ; }
Emits the list of SampledRequets with a header .
204
13
158,749
public static int getVarInt ( byte [ ] src , int offset , int [ ] dst ) { int result = 0 ; int shift = 0 ; int b ; do { if ( shift >= 32 ) { // Out of range throw new IndexOutOfBoundsException ( "varint too long" ) ; } // Get 7 bits from next byte b = src [ offset ++ ] ; result |= ( b & 0x7F ) << shift ; shift += 7 ; } while ( ( b & 0x80 ) != 0 ) ; dst [ 0 ] = result ; return offset ; }
Reads a varint from src places its values into the first element of dst and returns the offset in to src of the first byte after the varint .
123
32
158,750
public static int getVarInt ( ByteBuffer src ) { int tmp ; if ( ( tmp = src . get ( ) ) >= 0 ) { return tmp ; } int result = tmp & 0x7f ; if ( ( tmp = src . get ( ) ) >= 0 ) { result |= tmp << 7 ; } else { result |= ( tmp & 0x7f ) << 7 ; if ( ( tmp = src . get ( ) ) >= 0 ) { result |= tmp << 14 ; } else { result |= ( tmp & 0x7f ) << 14 ; if ( ( tmp = src . get ( ) ) >= 0 ) { result |= tmp << 21 ; } else { result |= ( tmp & 0x7f ) << 21 ; result |= ( tmp = src . get ( ) ) << 28 ; while ( tmp < 0 ) { // We get into this loop only in the case of overflow. // By doing this, we can call getVarInt() instead of // getVarLong() when we only need an int. tmp = src . get ( ) ; } } } } return result ; }
Reads a varint from the current position of the given ByteBuffer and returns the decoded value as 32 bit integer .
238
25
158,751
public static void putVarInt ( int v , ByteBuffer sink ) { while ( true ) { int bits = v & 0x7f ; v >>>= 7 ; if ( v == 0 ) { sink . put ( ( byte ) bits ) ; return ; } sink . put ( ( byte ) ( bits | 0x80 ) ) ; } }
Encodes an integer in a variable - length encoding 7 bits per byte to a ByteBuffer sink .
73
20
158,752
public static int getVarInt ( InputStream inputStream ) throws IOException { int result = 0 ; int shift = 0 ; int b ; do { if ( shift >= 32 ) { // Out of range throw new IndexOutOfBoundsException ( "varint too long" ) ; } // Get 7 bits from next byte b = inputStream . read ( ) ; result |= ( b & 0x7F ) << shift ; shift += 7 ; } while ( ( b & 0x80 ) != 0 ) ; return result ; }
Reads a varint from the given InputStream and returns the decoded value as an int .
112
20
158,753
public static void putVarInt ( int v , OutputStream outputStream ) throws IOException { byte [ ] bytes = new byte [ varIntSize ( v ) ] ; putVarInt ( v , bytes , 0 ) ; outputStream . write ( bytes ) ; }
Encodes an integer in a variable - length encoding 7 bits per byte and writes it to the given OutputStream .
55
23
158,754
public static long getVarLong ( ByteBuffer src ) { long tmp ; if ( ( tmp = src . get ( ) ) >= 0 ) { return tmp ; } long result = tmp & 0x7f ; if ( ( tmp = src . get ( ) ) >= 0 ) { result |= tmp << 7 ; } else { result |= ( tmp & 0x7f ) << 7 ; if ( ( tmp = src . get ( ) ) >= 0 ) { result |= tmp << 14 ; } else { result |= ( tmp & 0x7f ) << 14 ; if ( ( tmp = src . get ( ) ) >= 0 ) { result |= tmp << 21 ; } else { result |= ( tmp & 0x7f ) << 21 ; if ( ( tmp = src . get ( ) ) >= 0 ) { result |= tmp << 28 ; } else { result |= ( tmp & 0x7f ) << 28 ; if ( ( tmp = src . get ( ) ) >= 0 ) { result |= tmp << 35 ; } else { result |= ( tmp & 0x7f ) << 35 ; if ( ( tmp = src . get ( ) ) >= 0 ) { result |= tmp << 42 ; } else { result |= ( tmp & 0x7f ) << 42 ; if ( ( tmp = src . get ( ) ) >= 0 ) { result |= tmp << 49 ; } else { result |= ( tmp & 0x7f ) << 49 ; if ( ( tmp = src . get ( ) ) >= 0 ) { result |= tmp << 56 ; } else { result |= ( tmp & 0x7f ) << 56 ; result |= ( ( long ) src . get ( ) ) << 63 ; } } } } } } } } return result ; }
Reads an up to 64 bit long varint from the current position of the given ByteBuffer and returns the decoded value as long .
384
28
158,755
public static void putVarLong ( long v , ByteBuffer sink ) { while ( true ) { int bits = ( ( int ) v ) & 0x7f ; v >>>= 7 ; if ( v == 0 ) { sink . put ( ( byte ) bits ) ; return ; } sink . put ( ( byte ) ( bits | 0x80 ) ) ; } }
Encodes a long integer in a variable - length encoding 7 bits per byte to a ByteBuffer sink .
78
21
158,756
@ Benchmark @ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Span createRootSpan ( Data data ) { Span span = data . tracer . spanBuilderWithExplicitParent ( "RootSpan" , null ) . setRecordEvents ( data . recorded ) . setSampler ( data . sampled ? Samplers . alwaysSample ( ) : Samplers . neverSample ( ) ) . startSpan ( ) ; span . end ( ) ; return span ; }
Create a root span .
115
5
158,757
@ Benchmark @ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Link createLink ( Data data ) { return Link . fromSpanContext ( SpanContext . create ( TraceId . fromBytes ( new byte [ ] { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 0 } ) , SpanId . fromBytes ( new byte [ ] { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 0 } ) , TraceOptions . DEFAULT , TRACESTATE_DEFAULT ) , Link . Type . PARENT_LINKED_SPAN ) ; }
Create a link .
155
4
158,758
@ Benchmark @ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public MessageEvent createMessageEvent ( Data data ) { return MessageEvent . builder ( MessageEvent . Type . SENT , MESSAGE_ID ) . build ( ) ; }
Create a message event .
66
5
158,759
@ Benchmark @ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Span getCurrentSpan ( Data data ) { return data . tracer . getCurrentSpan ( ) ; }
Get current trace span .
53
5
158,760
@ Benchmark @ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public byte [ ] encodeSpanBinary ( Data data ) { return data . propagation . getBinaryFormat ( ) . toByteArray ( data . spanToEncode . getContext ( ) ) ; }
Encode a span using binary format .
72
8
158,761
@ Benchmark @ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public SpanContext decodeSpanBinary ( Data data ) throws SpanContextParseException { return data . propagation . getBinaryFormat ( ) . fromByteArray ( data . spanToDecodeBinary ) ; }
Decode a span using binary format .
74
8
158,762
@ Benchmark @ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public String encodeSpanText ( Data data ) { return encodeSpanContextText ( data . propagation . getTraceContextFormat ( ) , data . spanToEncode . getContext ( ) ) ; }
Encode a span using text format .
72
8
158,763
@ Benchmark @ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public SpanContext decodeSpanText ( Data data ) throws SpanContextParseException { return data . propagation . getTraceContextFormat ( ) . extract ( data . spanToDecodeText , textGetter ) ; }
Decode a span using text format .
75
8
158,764
@ Benchmark @ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Span setStatus ( Data data ) { data . spanToSet . setStatus ( STATUS_OK ) ; return data . spanToSet ; }
Set status on a span .
60
6
158,765
@ Benchmark @ BenchmarkMode ( Mode . AverageTime ) @ OutputTimeUnit ( TimeUnit . NANOSECONDS ) public Span endSpan ( Data data ) { data . spanToEnd . end ( ) ; return data . spanToEnd ; }
End a span .
56
4
158,766
public static void createAndRegisterWithCredentialsAndProjectId ( Credentials credentials , String projectId ) throws IOException { StackdriverTraceExporter . createAndRegister ( StackdriverTraceConfiguration . builder ( ) . setCredentials ( credentials ) . setProjectId ( projectId ) . build ( ) ) ; }
Creates and registers the Stackdriver Trace exporter to the OpenCensus library for an explicit project ID and using explicit credentials . Only one Stackdriver exporter can be registered at any point .
70
39
158,767
public static void createAndRegisterWithProjectId ( String projectId ) throws IOException { StackdriverTraceExporter . createAndRegister ( StackdriverTraceConfiguration . builder ( ) . setCredentials ( GoogleCredentials . getApplicationDefault ( ) ) . setProjectId ( projectId ) . build ( ) ) ; }
Creates and registers the Stackdriver Trace exporter to the OpenCensus library for an explicit project ID . Only one Stackdriver exporter can be registered at any point .
70
35
158,768
static List < DataPoint > adapt ( Metric metric ) { MetricDescriptor metricDescriptor = metric . getMetricDescriptor ( ) ; MetricType metricType = getType ( metricDescriptor . getType ( ) ) ; if ( metricType == null ) { return Collections . emptyList ( ) ; } DataPoint . Builder shared = DataPoint . newBuilder ( ) ; shared . setMetric ( metricDescriptor . getName ( ) ) ; shared . setMetricType ( metricType ) ; ArrayList < DataPoint > datapoints = Lists . newArrayList ( ) ; for ( TimeSeries timeSeries : metric . getTimeSeriesList ( ) ) { DataPoint . Builder builder = shared . clone ( ) ; builder . addAllDimensions ( createDimensions ( metricDescriptor . getLabelKeys ( ) , timeSeries . getLabelValues ( ) ) ) ; List < Point > points = timeSeries . getPoints ( ) ; datapoints . ensureCapacity ( datapoints . size ( ) + points . size ( ) ) ; for ( Point point : points ) { datapoints . add ( builder . setValue ( createDatum ( point . getValue ( ) ) ) . build ( ) ) ; } } return datapoints ; }
Converts the given Metric into datapoints that can be sent to SignalFx .
280
20
158,769
@ SuppressWarnings ( "unused" ) public void setSmtpAuth ( String userName , String password ) { setSmtpUsername ( userName ) ; setSmtpPassword ( password ) ; }
Make API match Mailer plugin
46
6
158,770
private Object readResolve ( ) throws ObjectStreamException { if ( triggerScript != null && secureTriggerScript == null ) { this . secureTriggerScript = new SecureGroovyScript ( triggerScript , false , null ) ; this . secureTriggerScript . configuring ( ApprovalContext . create ( ) ) ; triggerScript = null ; } return this ; }
Called when object has been deserialized from a stream .
74
13
158,771
private String renderTemplate ( Run < ? , ? > build , FilePath workspace , TaskListener listener , InputStream templateStream ) throws IOException { String result ; final Map < String , Object > binding = new HashMap <> ( ) ; ExtendedEmailPublisherDescriptor descriptor = Jenkins . getActiveInstance ( ) . getDescriptorByType ( ExtendedEmailPublisherDescriptor . class ) ; binding . put ( "build" , build ) ; binding . put ( "listener" , listener ) ; binding . put ( "it" , new ScriptContentBuildWrapper ( build ) ) ; binding . put ( "rooturl" , descriptor . getHudsonUrl ( ) ) ; binding . put ( "project" , build . getParent ( ) ) ; binding . put ( "workspace" , workspace ) ; try { String text = IOUtils . toString ( templateStream ) ; boolean approvedScript = false ; if ( templateStream instanceof UserProvidedContentInputStream && ! AbstractEvalContent . isApprovedScript ( text , GroovyLanguage . get ( ) ) ) { approvedScript = false ; ScriptApproval . get ( ) . configuring ( text , GroovyLanguage . get ( ) , ApprovalContext . create ( ) . withItem ( build . getParent ( ) ) ) ; } else { approvedScript = true ; } // we add the binding to the SimpleTemplateEngine instead of the shell GroovyShell shell = createEngine ( descriptor , Collections . < String , Object > emptyMap ( ) , ! approvedScript ) ; SimpleTemplateEngine engine = new SimpleTemplateEngine ( shell ) ; Template tmpl ; synchronized ( templateCache ) { Reference < Template > templateR = templateCache . get ( text ) ; tmpl = templateR == null ? null : templateR . get ( ) ; if ( tmpl == null ) { tmpl = engine . createTemplate ( text ) ; templateCache . put ( text , new SoftReference <> ( tmpl ) ) ; } } final Template tmplR = tmpl ; if ( approvedScript ) { //The script has been approved by an admin, so run it as is result = tmplR . make ( binding ) . toString ( ) ; } else { //unapproved script, so run in sandbox StaticProxyInstanceWhitelist whitelist = new StaticProxyInstanceWhitelist ( build , "templates-instances.whitelist" ) ; result = GroovySandbox . runInSandbox ( new Callable < String > ( ) { @ Override public String call ( ) throws Exception { return tmplR . make ( binding ) . toString ( ) ; //TODO there is a PrintWriter instance created in make and bound to out } } , new ProxyWhitelist ( Whitelist . all ( ) , new TaskListenerInstanceWhitelist ( listener ) , new PrintStreamInstanceWhitelist ( listener . getLogger ( ) ) , new EmailExtScriptTokenMacroWhitelist ( ) , whitelist ) ) ; } } catch ( Exception e ) { StringWriter sw = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( sw ) ; e . printStackTrace ( pw ) ; result = "Exception raised during template rendering: " + e . getMessage ( ) + "\n\n" + sw . toString ( ) ; } return result ; }
Renders the template using a SimpleTemplateEngine
720
9
158,772
private String executeScript ( Run < ? , ? > build , FilePath workspace , TaskListener listener , InputStream scriptStream ) throws IOException { String result = "" ; Map binding = new HashMap <> ( ) ; ExtendedEmailPublisherDescriptor descriptor = Jenkins . getActiveInstance ( ) . getDescriptorByType ( ExtendedEmailPublisherDescriptor . class ) ; Item parent = build . getParent ( ) ; binding . put ( "build" , build ) ; binding . put ( "it" , new ScriptContentBuildWrapper ( build ) ) ; binding . put ( "project" , parent ) ; binding . put ( "rooturl" , descriptor . getHudsonUrl ( ) ) ; binding . put ( "workspace" , workspace ) ; PrintStream logger = listener . getLogger ( ) ; binding . put ( "logger" , logger ) ; String scriptContent = IOUtils . toString ( scriptStream , descriptor . getCharset ( ) ) ; if ( scriptStream instanceof UserProvidedContentInputStream ) { ScriptApproval . get ( ) . configuring ( scriptContent , GroovyLanguage . get ( ) , ApprovalContext . create ( ) . withItem ( parent ) ) ; } if ( scriptStream instanceof UserProvidedContentInputStream && ! AbstractEvalContent . isApprovedScript ( scriptContent , GroovyLanguage . get ( ) ) ) { //Unapproved script, run it in the sandbox GroovyShell shell = createEngine ( descriptor , binding , true ) ; Object res = GroovySandbox . run ( shell , scriptContent , new ProxyWhitelist ( Whitelist . all ( ) , new PrintStreamInstanceWhitelist ( logger ) , new EmailExtScriptTokenMacroWhitelist ( ) ) ) ; if ( res != null ) { result = res . toString ( ) ; } } else { if ( scriptStream instanceof UserProvidedContentInputStream ) { ScriptApproval . get ( ) . using ( scriptContent , GroovyLanguage . get ( ) ) ; } //Pre approved script, so run as is GroovyShell shell = createEngine ( descriptor , binding , false ) ; Script script = shell . parse ( scriptContent ) ; Object res = script . run ( ) ; if ( res != null ) { result = res . toString ( ) ; } } return result ; }
Executes a script and returns the last value as a String
502
12
158,773
private void addUpstreamCommittersTriggeringBuild ( Run < ? , ? > build , Set < InternetAddress > to , Set < InternetAddress > cc , Set < InternetAddress > bcc , EnvVars env , final ExtendedEmailPublisherContext context , RecipientProviderUtilities . IDebug debug ) { debug . send ( "Adding upstream committer from job %s with build number %s" , build . getParent ( ) . getDisplayName ( ) , build . getNumber ( ) ) ; List < ChangeLogSet < ? > > changeSets = new ArrayList <> ( ) ; if ( build instanceof AbstractBuild < ? , ? > ) { AbstractBuild < ? , ? > b = ( AbstractBuild < ? , ? > ) build ; changeSets . add ( b . getChangeSet ( ) ) ; } else { try { // check for getChangeSets which WorkflowRun has Method m = build . getClass ( ) . getMethod ( "getChangeSets" ) ; changeSets = ( List < ChangeLogSet < ? extends ChangeLogSet . Entry > > ) m . invoke ( build ) ; } catch ( NoSuchMethodException | InvocationTargetException | IllegalAccessException e ) { context . getListener ( ) . getLogger ( ) . print ( "Could not add upstream committers, build type does not provide change set" ) ; } } if ( ! changeSets . isEmpty ( ) ) { for ( ChangeLogSet < ? extends ChangeLogSet . Entry > changeSet : changeSets ) { for ( ChangeLogSet . Entry change : changeSet ) { addUserFromChangeSet ( change , to , cc , bcc , env , context , debug ) ; } } } }
Adds for the given upstream build the committers to the recipient list for each commit in the upstream build .
371
21
158,774
private void addUserFromChangeSet ( ChangeLogSet . Entry change , Set < InternetAddress > to , Set < InternetAddress > cc , Set < InternetAddress > bcc , EnvVars env , final ExtendedEmailPublisherContext context , RecipientProviderUtilities . IDebug debug ) { User user = change . getAuthor ( ) ; RecipientProviderUtilities . addUsers ( Collections . singleton ( user ) , context , env , to , cc , bcc , debug ) ; }
Adds a user to the recipients list based on a specific SCM change set
104
15
158,775
private String fetchStyles ( Document doc ) { Elements els = doc . select ( STYLE_TAG ) ; StringBuilder styles = new StringBuilder ( ) ; for ( Element e : els ) { if ( e . attr ( "data-inline" ) . equals ( "true" ) ) { styles . append ( e . data ( ) ) ; e . remove ( ) ; } } return styles . toString ( ) ; }
Generates a stylesheet from an html document
94
9
158,776
public String process ( String input ) { Document doc = Jsoup . parse ( input ) ; // check if the user wants to inline the data Elements elements = doc . getElementsByAttributeValue ( DATA_INLINE_ATTR , "true" ) ; if ( elements . isEmpty ( ) ) { return input ; } extractStyles ( doc ) ; applyStyles ( doc ) ; inlineImages ( doc ) ; doc . outputSettings ( doc . outputSettings ( ) . syntax ( Document . OutputSettings . Syntax . xml ) . prettyPrint ( false ) . escapeMode ( Entities . EscapeMode . extended ) ) ; return StringEscapeUtils . unescapeHtml ( doc . outerHtml ( ) ) ; }
Takes an input string representing an html document and processes it with the Css Inliner .
155
19
158,777
public static String unescapeString ( String escapedString ) { StringBuilder sb = new StringBuilder ( ) ; for ( int i = 1 ; i < escapedString . length ( ) - 1 ; ++ i ) { char c = escapedString . charAt ( i ) ; if ( c == ' ' ) { ++ i ; sb . append ( unescapeChar ( escapedString . charAt ( i ) ) ) ; } else { sb . append ( c ) ; } } return sb . toString ( ) ; }
Replaces all the printf - style escape sequences in a string with the appropriate characters .
111
17
158,778
public static void printf ( StringBuffer buf , String formatString , PrintfSpec printfSpec ) { for ( int i = 0 ; i < formatString . length ( ) ; ++ i ) { char c = formatString . charAt ( i ) ; if ( ( c == ' ' ) && ( i + 1 < formatString . length ( ) ) ) { ++ i ; char code = formatString . charAt ( i ) ; if ( code == ' ' ) { buf . append ( ' ' ) ; } else { boolean handled = printfSpec . printSpec ( buf , code ) ; if ( ! handled ) { buf . append ( ' ' ) ; buf . append ( code ) ; } } } else if ( ( c == ' ' ) && ( i + 1 < formatString . length ( ) ) ) { ++ i ; buf . append ( Util . unescapeChar ( formatString . charAt ( i ) ) ) ; } else { buf . append ( c ) ; } } }
Formats a string and puts the result into a StringBuffer . Allows for standard Java backslash escapes and a customized behavior for % escapes in the form of a PrintfSpec .
209
37
158,779
private ClassLoader expandClasspath ( ExtendedEmailPublisherContext context , ClassLoader loader ) throws IOException { List < ClasspathEntry > classpathList = new ArrayList <> ( ) ; if ( classpath != null && ! classpath . isEmpty ( ) ) { transformToClasspathEntries ( classpath , context , classpathList ) ; } List < GroovyScriptPath > globalClasspath = getDescriptor ( ) . getDefaultClasspath ( ) ; if ( globalClasspath != null && ! globalClasspath . isEmpty ( ) ) { transformToClasspathEntries ( globalClasspath , context , classpathList ) ; } boolean useSecurity = Jenkins . getActiveInstance ( ) . isUseSecurity ( ) ; if ( ! classpathList . isEmpty ( ) ) { GroovyClassLoader gloader = new GroovyClassLoader ( loader ) ; gloader . setShouldRecompile ( true ) ; for ( ClasspathEntry entry : classpathList ) { if ( useSecurity ) { ScriptApproval . get ( ) . using ( entry ) ; } gloader . addURL ( entry . getURL ( ) ) ; } loader = gloader ; } if ( useSecurity ) { return GroovySandbox . createSecureClassLoader ( loader ) ; } else { return loader ; } }
Expand the plugin class loader with URL taken from the project descriptor and the global configuration .
282
18
158,780
protected int getNumFailures ( Run < ? , ? > build ) { AbstractTestResultAction a = build . getAction ( AbstractTestResultAction . class ) ; if ( a instanceof AggregatedTestResultAction ) { int result = 0 ; AggregatedTestResultAction action = ( AggregatedTestResultAction ) a ; for ( ChildReport cr : action . getChildReports ( ) ) { if ( cr == null || cr . child == null || cr . child . getParent ( ) == null ) { continue ; } if ( cr . child . getParent ( ) . equals ( build . getParent ( ) ) ) { if ( cr . result instanceof TestResult ) { TestResult tr = ( TestResult ) cr . result ; result += tr . getFailCount ( ) ; } } } if ( result == 0 && action . getFailCount ( ) > 0 ) { result = action . getFailCount ( ) ; } return result ; } return a . getFailCount ( ) ; }
Determine the number of direct failures in the given build . If it aggregates downstream results ignore contributed failures . This is because at the time this trigger runs the current build s aggregated results aren t available yet but those of the previous build may be .
213
52
158,781
private Run < ? , ? > getPreviousRun ( Run < ? , ? > build , TaskListener listener ) { Run < ? , ? > prevBuild = ExtendedEmailPublisher . getPreviousRun ( build , listener ) ; // Skip ABORTED builds if ( prevBuild != null && prevBuild . getResult ( ) == Result . ABORTED ) { return getPreviousRun ( prevBuild , listener ) ; } return prevBuild ; }
Find most recent previous build matching certain criteria .
91
9
158,782
public static void setDnsCache ( long expireMillis , String host , String ... ips ) { try { InetAddressCacheUtil . setInetAddressCache ( host , ips , System . currentTimeMillis ( ) + expireMillis ) ; } catch ( Exception e ) { final String message = String . format ( "Fail to setDnsCache for host %s ip %s expireMillis %s, cause: %s" , host , Arrays . toString ( ips ) , expireMillis , e . toString ( ) ) ; throw new DnsCacheManipulatorException ( message , e ) ; } }
Set a dns cache entry .
138
7
158,783
public static void setDnsCache ( Properties properties ) { for ( Map . Entry < Object , Object > entry : properties . entrySet ( ) ) { final String host = ( String ) entry . getKey ( ) ; String ipList = ( String ) entry . getValue ( ) ; ipList = ipList . trim ( ) ; if ( ipList . isEmpty ( ) ) continue ; final String [ ] ips = COMMA_SEPARATOR . split ( ipList ) ; setDnsCache ( host , ips ) ; } }
Set dns cache entries by properties
115
7
158,784
public static void loadDnsCacheConfig ( String propertiesFileName ) { InputStream inputStream = Thread . currentThread ( ) . getContextClassLoader ( ) . getResourceAsStream ( propertiesFileName ) ; if ( inputStream == null ) { inputStream = DnsCacheManipulator . class . getClassLoader ( ) . getResourceAsStream ( propertiesFileName ) ; } if ( inputStream == null ) { throw new DnsCacheManipulatorException ( "Fail to find " + propertiesFileName + " on classpath!" ) ; } try { Properties properties = new Properties ( ) ; properties . load ( inputStream ) ; inputStream . close ( ) ; setDnsCache ( properties ) ; } catch ( Exception e ) { final String message = String . format ( "Fail to loadDnsCacheConfig from %s, cause: %s" , propertiesFileName , e . toString ( ) ) ; throw new DnsCacheManipulatorException ( message , e ) ; } }
Load dns config from the specified properties file on classpath then set dns cache .
212
18
158,785
@ Nullable public static DnsCacheEntry getDnsCache ( String host ) { try { return InetAddressCacheUtil . getInetAddressCache ( host ) ; } catch ( Exception e ) { throw new DnsCacheManipulatorException ( "Fail to getDnsCache, cause: " + e . toString ( ) , e ) ; } }
Get dns cache .
78
5
158,786
public static List < DnsCacheEntry > listDnsCache ( ) { try { return InetAddressCacheUtil . listInetAddressCache ( ) . getCache ( ) ; } catch ( Exception e ) { throw new DnsCacheManipulatorException ( "Fail to listDnsCache, cause: " + e . toString ( ) , e ) ; } }
Get all dns cache entries .
80
7
158,787
public static DnsCache getWholeDnsCache ( ) { try { return InetAddressCacheUtil . listInetAddressCache ( ) ; } catch ( Exception e ) { throw new DnsCacheManipulatorException ( "Fail to getWholeDnsCache, cause: " + e . toString ( ) , e ) ; } }
Get whole dns cache info .
75
7
158,788
public static void removeDnsCache ( String host ) { try { InetAddressCacheUtil . removeInetAddressCache ( host ) ; } catch ( Exception e ) { final String message = String . format ( "Fail to removeDnsCache for host %s, cause: %s" , host , e . toString ( ) ) ; throw new DnsCacheManipulatorException ( message , e ) ; } }
Remove dns cache entry cause lookup dns server for host after .
90
14
158,789
public static void setDnsNegativeCachePolicy ( int negativeCacheSeconds ) { try { InetAddressCacheUtil . setDnsNegativeCachePolicy ( negativeCacheSeconds ) ; } catch ( Exception e ) { throw new DnsCacheManipulatorException ( "Fail to setDnsNegativeCachePolicy, cause: " + e . toString ( ) , e ) ; } }
Set JVM DNS negative cache policy
85
7
158,790
private void initializeDrawableForDisplay ( Drawable d ) { if ( mBlockInvalidateCallback == null ) { mBlockInvalidateCallback = new BlockInvalidateCallback ( ) ; } // Temporary fix for suspending callbacks during initialization. We // don't want any of these setters causing an invalidate() since that // may call back into DrawableContainer. d . setCallback ( mBlockInvalidateCallback . wrap ( d . getCallback ( ) ) ) ; try { if ( mDrawableContainerState . mEnterFadeDuration <= 0 && mHasAlpha ) { d . setAlpha ( mAlpha ) ; } if ( mDrawableContainerState . mHasColorFilter ) { // Color filter always overrides tint. d . setColorFilter ( mDrawableContainerState . mColorFilter ) ; } else { if ( mDrawableContainerState . mHasTintList ) { DrawableCompat . setTintList ( d , mDrawableContainerState . mTintList ) ; } if ( mDrawableContainerState . mHasTintMode ) { DrawableCompat . setTintMode ( d , mDrawableContainerState . mTintMode ) ; } } d . setVisible ( isVisible ( ) , true ) ; d . setDither ( mDrawableContainerState . mDither ) ; d . setState ( getState ( ) ) ; d . setLevel ( getLevel ( ) ) ; d . setBounds ( getBounds ( ) ) ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . M ) { d . setLayoutDirection ( getLayoutDirection ( ) ) ; } if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . KITKAT ) { d . setAutoMirrored ( mDrawableContainerState . mAutoMirrored ) ; } final Rect hotspotBounds = mHotspotBounds ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . LOLLIPOP && hotspotBounds != null ) { d . setHotspotBounds ( hotspotBounds . left , hotspotBounds . top , hotspotBounds . right , hotspotBounds . bottom ) ; } } finally { d . setCallback ( mBlockInvalidateCallback . unwrap ( ) ) ; } }
Initializes a drawable for display in this container .
511
11
158,791
@ Override protected boolean onStateChange ( int [ ] stateSet ) { final boolean changed = super . onStateChange ( stateSet ) ; int idx = mAnimationScaleListState . getCurrentDrawableIndexBasedOnScale ( ) ; return selectDrawable ( idx ) || changed ; }
Set the current drawable according to the animation scale . If scale is 0 then pick the static drawable otherwise pick the animatable drawable .
63
29
158,792
public static int longToInt ( long inLong ) { if ( inLong < Integer . MIN_VALUE ) { return Integer . MIN_VALUE ; } if ( inLong > Integer . MAX_VALUE ) { return Integer . MAX_VALUE ; } return ( int ) inLong ; }
convert unsigned long to signed int .
60
8
158,793
public static void getAllInterfaces ( Class < ? > classObject , ArrayList < Type > interfaces ) { Type [ ] superInterfaces = classObject . getGenericInterfaces ( ) ; interfaces . addAll ( ( Arrays . asList ( superInterfaces ) ) ) ; // for cases where the extended class is defined with a Generic. Type tgs = classObject . getGenericSuperclass ( ) ; if ( tgs != null ) { if ( ( tgs ) instanceof ParameterizedType ) { interfaces . add ( tgs ) ; } } if ( tc . isDebugEnabled ( ) ) { Tr . debug ( tc , "updated interfaces to: " + interfaces ) ; } Class < ? > superClass = classObject . getSuperclass ( ) ; if ( superClass != null ) { getAllInterfaces ( superClass , interfaces ) ; } }
recursively gets all interfaces
183
6
158,794
public static String truncateCloseReason ( String reasonPhrase ) { if ( reasonPhrase != null ) { byte [ ] reasonBytes = reasonPhrase . getBytes ( Utils . UTF8_CHARSET ) ; int len = reasonBytes . length ; // Why 120? UTF-8 can take 4 bytes per character, so we either hit the boundary, or are off by 1-3 bytes. // Subtract 3 from 123 and we'll try to cut only if it is greater than that. if ( len > 120 ) { String updatedPhrase = cutStringByByteSize ( reasonPhrase , 120 ) ; reasonPhrase = updatedPhrase ; } } return reasonPhrase ; }
close reason needs to be truncated to 123 UTF - 8 encoded bytes
147
14
158,795
protected Converter getConverter ( FacesContext facesContext , UIComponent component ) { if ( component instanceof UISelectMany ) { return HtmlRendererUtils . findUISelectManyConverterFailsafe ( facesContext , ( UISelectMany ) component ) ; } else if ( component instanceof UISelectOne ) { return HtmlRendererUtils . findUIOutputConverterFailSafe ( facesContext , component ) ; } return null ; }
Gets the converter for the given component rendered by this renderer .
106
14
158,796
public void startConditional ( ) throws Exception { if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( tc , "startConditional" , this ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) SibTr . debug ( tc , "Activating MBean for ME " + getName ( ) ) ; setState ( STATE_STARTING ) ; start ( JsConstants . ME_START_DEFAULT ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "startConditional" ) ; }
Start the Messaging Engine if it is enabled
156
9
158,797
private boolean okayToSendServerStarted ( ) { if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( tc , "okayToSendServerStarted" , this ) ; synchronized ( lockObject ) { if ( ! _sentServerStarted ) { if ( ( _state == STATE_STARTED ) && _mainImpl . isServerStarted ( ) ) { _sentServerStarted = true ; } } } if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "okayToSendServerStarted" , new Boolean ( _sentServerStarted ) ) ; return _sentServerStarted ; }
Determine whether the conditions permitting a server started notification to be sent are met .
163
17
158,798
private boolean okayToSendServerStopping ( ) { // Removed the synchronized modifier of this method, as its only setting one private variable _sentServerStopping, // If its synchronized, then notification thread gets blocked here until JsActivationThread returns and so it doesnot set _sentServerStopping to true if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) // To enable the JsActivationThread to check for serverStopping notification while its still running, this method should not be synchronized. SibTr . entry ( tc , "okayToSendServerStopping" , this ) ; synchronized ( lockObject ) { // This should be run in a synchronized context if ( ! _sentServerStopping ) { if ( ( _state == STATE_STARTED || _state == STATE_AUTOSTARTING || _state == STATE_STARTING ) && _mainImpl . isServerStopping ( ) ) { // Adding additional ME states( STARTING and AUTOSTARTING) , so that sever stopping notification is also sent when ME is in those states. _sentServerStopping = true ; } } } if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "okayToSendServerStopping" , new Boolean ( _sentServerStopping ) ) ; return _sentServerStopping ; }
Determine whether the conditions permitting a server stopping notification to be sent are met . The ME state can be STARTED AUTOSTARTING or in STARTING state to receive server stopping notification
302
38
158,799
@ SuppressWarnings ( "unchecked" ) public < EngineComponent > EngineComponent getEngineComponent ( Class < EngineComponent > clazz ) { String thisMethodName = "getEngineComponent" ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) { SibTr . entry ( tc , thisMethodName , clazz ) ; } JsEngineComponent foundEngineComponent = null ; // No need to synchronize on jmeComponents to prevent concurrent // modification from dynamic config and runtime callbacks, because // jmeComponents is now a CopyOnWriteArrayList. Iterator < ComponentList > vIter = jmeComponents . iterator ( ) ; while ( vIter . hasNext ( ) && foundEngineComponent == null ) { ComponentList c = vIter . next ( ) ; if ( clazz . isInstance ( c . getRef ( ) ) ) { foundEngineComponent = c . getRef ( ) ; } } if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) { SibTr . exit ( tc , thisMethodName , foundEngineComponent ) ; } return ( EngineComponent ) foundEngineComponent ; }
The purpose of this method is to get an engine component that can be cast using the specified class . The EngineComponent is not a class name but represents the classes real type .
257
35