repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
partition
stringclasses
1 value
census-instrumentation/opencensus-java
api/src/main/java/io/opencensus/stats/ViewData.java
ViewData.createInternal
private static ViewData createInternal( View view, Map<List</*@Nullable*/ TagValue>, AggregationData> aggregationMap, AggregationWindowData window, Timestamp start, Timestamp end) { @SuppressWarnings("nullness") Map<List<TagValue>, AggregationData> map = aggregationMap; return new AutoValue_ViewData(view, map, window, start, end); }
java
private static ViewData createInternal( View view, Map<List</*@Nullable*/ TagValue>, AggregationData> aggregationMap, AggregationWindowData window, Timestamp start, Timestamp end) { @SuppressWarnings("nullness") Map<List<TagValue>, AggregationData> map = aggregationMap; return new AutoValue_ViewData(view, map, window, start, end); }
[ "private", "static", "ViewData", "createInternal", "(", "View", "view", ",", "Map", "<", "List", "<", "/*@Nullable*/", "TagValue", ">", ",", "AggregationData", ">", "aggregationMap", ",", "AggregationWindowData", "window", ",", "Timestamp", "start", ",", "Timestamp", "end", ")", "{", "@", "SuppressWarnings", "(", "\"nullness\"", ")", "Map", "<", "List", "<", "TagValue", ">", ",", "AggregationData", ">", "map", "=", "aggregationMap", ";", "return", "new", "AutoValue_ViewData", "(", "view", ",", "map", ",", "window", ",", "start", ",", "end", ")", ";", "}" ]
constructor does not have the @Nullable annotation on TagValue.
[ "constructor", "does", "not", "have", "the" ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/api/src/main/java/io/opencensus/stats/ViewData.java#L195-L204
train
census-instrumentation/opencensus-java
exporters/trace/zipkin/src/main/java/io/opencensus/exporter/trace/zipkin/ZipkinExporterHandler.java
ZipkinExporterHandler.produceLocalEndpoint
static Endpoint produceLocalEndpoint(String serviceName) { Endpoint.Builder builder = Endpoint.newBuilder().serviceName(serviceName); try { Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces(); if (nics == null) { return builder.build(); } while (nics.hasMoreElements()) { NetworkInterface nic = nics.nextElement(); Enumeration<InetAddress> addresses = nic.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress address = addresses.nextElement(); if (address.isSiteLocalAddress()) { builder.ip(address); break; } } } } catch (Exception e) { // don't crash the caller if there was a problem reading nics. if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "error reading nics", e); } } return builder.build(); }
java
static Endpoint produceLocalEndpoint(String serviceName) { Endpoint.Builder builder = Endpoint.newBuilder().serviceName(serviceName); try { Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces(); if (nics == null) { return builder.build(); } while (nics.hasMoreElements()) { NetworkInterface nic = nics.nextElement(); Enumeration<InetAddress> addresses = nic.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress address = addresses.nextElement(); if (address.isSiteLocalAddress()) { builder.ip(address); break; } } } } catch (Exception e) { // don't crash the caller if there was a problem reading nics. if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "error reading nics", e); } } return builder.build(); }
[ "static", "Endpoint", "produceLocalEndpoint", "(", "String", "serviceName", ")", "{", "Endpoint", ".", "Builder", "builder", "=", "Endpoint", ".", "newBuilder", "(", ")", ".", "serviceName", "(", "serviceName", ")", ";", "try", "{", "Enumeration", "<", "NetworkInterface", ">", "nics", "=", "NetworkInterface", ".", "getNetworkInterfaces", "(", ")", ";", "if", "(", "nics", "==", "null", ")", "{", "return", "builder", ".", "build", "(", ")", ";", "}", "while", "(", "nics", ".", "hasMoreElements", "(", ")", ")", "{", "NetworkInterface", "nic", "=", "nics", ".", "nextElement", "(", ")", ";", "Enumeration", "<", "InetAddress", ">", "addresses", "=", "nic", ".", "getInetAddresses", "(", ")", ";", "while", "(", "addresses", ".", "hasMoreElements", "(", ")", ")", "{", "InetAddress", "address", "=", "addresses", ".", "nextElement", "(", ")", ";", "if", "(", "address", ".", "isSiteLocalAddress", "(", ")", ")", "{", "builder", ".", "ip", "(", "address", ")", ";", "break", ";", "}", "}", "}", "}", "catch", "(", "Exception", "e", ")", "{", "// don't crash the caller if there was a problem reading nics.", "if", "(", "logger", ".", "isLoggable", "(", "Level", ".", "FINE", ")", ")", "{", "logger", ".", "log", "(", "Level", ".", "FINE", ",", "\"error reading nics\"", ",", "e", ")", ";", "}", "}", "return", "builder", ".", "build", "(", ")", ";", "}" ]
Logic borrowed from brave.internal.Platform.produceLocalEndpoint
[ "Logic", "borrowed", "from", "brave", ".", "internal", ".", "Platform", ".", "produceLocalEndpoint" ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/trace/zipkin/src/main/java/io/opencensus/exporter/trace/zipkin/ZipkinExporterHandler.java#L75-L100
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/BasicDataBenchmark.java
BasicDataBenchmark.createAttributeValues
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public AttributeValue[] createAttributeValues(Data data) { return getAttributeValues(data.size, data.attributeType); }
java
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public AttributeValue[] createAttributeValues(Data data) { return getAttributeValues(data.size, data.attributeType); }
[ "@", "Benchmark", "@", "BenchmarkMode", "(", "Mode", ".", "AverageTime", ")", "@", "OutputTimeUnit", "(", "TimeUnit", ".", "NANOSECONDS", ")", "public", "AttributeValue", "[", "]", "createAttributeValues", "(", "Data", "data", ")", "{", "return", "getAttributeValues", "(", "data", ".", "size", ",", "data", ".", "attributeType", ")", ";", "}" ]
Create attribute values.
[ "Create", "attribute", "values", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/BasicDataBenchmark.java#L78-L83
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/BasicDataBenchmark.java
BasicDataBenchmark.createAttributeMap
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Map<String, AttributeValue> createAttributeMap(Data data) { Map<String, AttributeValue> attributeMap = new HashMap<>(data.size); for (int i = 0; i < data.size; i++) { attributeMap.put(data.attributeKeys[i], data.attributeValues[i]); } return attributeMap; }
java
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Map<String, AttributeValue> createAttributeMap(Data data) { Map<String, AttributeValue> attributeMap = new HashMap<>(data.size); for (int i = 0; i < data.size; i++) { attributeMap.put(data.attributeKeys[i], data.attributeValues[i]); } return attributeMap; }
[ "@", "Benchmark", "@", "BenchmarkMode", "(", "Mode", ".", "AverageTime", ")", "@", "OutputTimeUnit", "(", "TimeUnit", ".", "NANOSECONDS", ")", "public", "Map", "<", "String", ",", "AttributeValue", ">", "createAttributeMap", "(", "Data", "data", ")", "{", "Map", "<", "String", ",", "AttributeValue", ">", "attributeMap", "=", "new", "HashMap", "<>", "(", "data", ".", "size", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "data", ".", "size", ";", "i", "++", ")", "{", "attributeMap", ".", "put", "(", "data", ".", "attributeKeys", "[", "i", "]", ",", "data", ".", "attributeValues", "[", "i", "]", ")", ";", "}", "return", "attributeMap", ";", "}" ]
Create an AttributeMap.
[ "Create", "an", "AttributeMap", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/BasicDataBenchmark.java#L86-L95
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/BasicDataBenchmark.java
BasicDataBenchmark.createAnnotation
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Annotation createAnnotation(Data data) { return Annotation.fromDescriptionAndAttributes(ANNOTATION_DESCRIPTION, data.attributeMap); }
java
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Annotation createAnnotation(Data data) { return Annotation.fromDescriptionAndAttributes(ANNOTATION_DESCRIPTION, data.attributeMap); }
[ "@", "Benchmark", "@", "BenchmarkMode", "(", "Mode", ".", "AverageTime", ")", "@", "OutputTimeUnit", "(", "TimeUnit", ".", "NANOSECONDS", ")", "public", "Annotation", "createAnnotation", "(", "Data", "data", ")", "{", "return", "Annotation", ".", "fromDescriptionAndAttributes", "(", "ANNOTATION_DESCRIPTION", ",", "data", ".", "attributeMap", ")", ";", "}" ]
Create an Annotation.
[ "Create", "an", "Annotation", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/BasicDataBenchmark.java#L98-L103
train
census-instrumentation/opencensus-java
exporters/stats/prometheus/src/main/java/io/opencensus/exporter/stats/prometheus/PrometheusExportUtils.java
PrometheusExportUtils.createMetricFamilySamples
static MetricFamilySamples createMetricFamilySamples(Metric metric, String namespace) { MetricDescriptor metricDescriptor = metric.getMetricDescriptor(); String name = getNamespacedName(metricDescriptor.getName(), namespace); Type type = getType(metricDescriptor.getType()); List<String> labelNames = convertToLabelNames(metricDescriptor.getLabelKeys()); List<Sample> samples = Lists.newArrayList(); for (io.opencensus.metrics.export.TimeSeries timeSeries : metric.getTimeSeriesList()) { for (io.opencensus.metrics.export.Point point : timeSeries.getPoints()) { samples.addAll(getSamples(name, labelNames, timeSeries.getLabelValues(), point.getValue())); } } return new MetricFamilySamples(name, type, metricDescriptor.getDescription(), samples); }
java
static MetricFamilySamples createMetricFamilySamples(Metric metric, String namespace) { MetricDescriptor metricDescriptor = metric.getMetricDescriptor(); String name = getNamespacedName(metricDescriptor.getName(), namespace); Type type = getType(metricDescriptor.getType()); List<String> labelNames = convertToLabelNames(metricDescriptor.getLabelKeys()); List<Sample> samples = Lists.newArrayList(); for (io.opencensus.metrics.export.TimeSeries timeSeries : metric.getTimeSeriesList()) { for (io.opencensus.metrics.export.Point point : timeSeries.getPoints()) { samples.addAll(getSamples(name, labelNames, timeSeries.getLabelValues(), point.getValue())); } } return new MetricFamilySamples(name, type, metricDescriptor.getDescription(), samples); }
[ "static", "MetricFamilySamples", "createMetricFamilySamples", "(", "Metric", "metric", ",", "String", "namespace", ")", "{", "MetricDescriptor", "metricDescriptor", "=", "metric", ".", "getMetricDescriptor", "(", ")", ";", "String", "name", "=", "getNamespacedName", "(", "metricDescriptor", ".", "getName", "(", ")", ",", "namespace", ")", ";", "Type", "type", "=", "getType", "(", "metricDescriptor", ".", "getType", "(", ")", ")", ";", "List", "<", "String", ">", "labelNames", "=", "convertToLabelNames", "(", "metricDescriptor", ".", "getLabelKeys", "(", ")", ")", ";", "List", "<", "Sample", ">", "samples", "=", "Lists", ".", "newArrayList", "(", ")", ";", "for", "(", "io", ".", "opencensus", ".", "metrics", ".", "export", ".", "TimeSeries", "timeSeries", ":", "metric", ".", "getTimeSeriesList", "(", ")", ")", "{", "for", "(", "io", ".", "opencensus", ".", "metrics", ".", "export", ".", "Point", "point", ":", "timeSeries", ".", "getPoints", "(", ")", ")", "{", "samples", ".", "addAll", "(", "getSamples", "(", "name", ",", "labelNames", ",", "timeSeries", ".", "getLabelValues", "(", ")", ",", "point", ".", "getValue", "(", ")", ")", ")", ";", "}", "}", "return", "new", "MetricFamilySamples", "(", "name", ",", "type", ",", "metricDescriptor", ".", "getDescription", "(", ")", ",", "samples", ")", ";", "}" ]
Converts a Metric to a Prometheus MetricFamilySamples.
[ "Converts", "a", "Metric", "to", "a", "Prometheus", "MetricFamilySamples", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/stats/prometheus/src/main/java/io/opencensus/exporter/stats/prometheus/PrometheusExportUtils.java#L79-L92
train
census-instrumentation/opencensus-java
exporters/stats/prometheus/src/main/java/io/opencensus/exporter/stats/prometheus/PrometheusExportUtils.java
PrometheusExportUtils.createDescribableMetricFamilySamples
static MetricFamilySamples createDescribableMetricFamilySamples( MetricDescriptor metricDescriptor, String namespace) { String name = getNamespacedName(metricDescriptor.getName(), namespace); Type type = getType(metricDescriptor.getType()); List<String> labelNames = convertToLabelNames(metricDescriptor.getLabelKeys()); if (containsDisallowedLeLabelForHistogram(labelNames, type)) { throw new IllegalStateException( "Prometheus Histogram cannot have a label named 'le', " + "because it is a reserved label for bucket boundaries. " + "Please remove this key from your view."); } if (containsDisallowedQuantileLabelForSummary(labelNames, type)) { throw new IllegalStateException( "Prometheus Summary cannot have a label named 'quantile', " + "because it is a reserved label. Please remove this key from your view."); } return new MetricFamilySamples( name, type, metricDescriptor.getDescription(), Collections.<Sample>emptyList()); }
java
static MetricFamilySamples createDescribableMetricFamilySamples( MetricDescriptor metricDescriptor, String namespace) { String name = getNamespacedName(metricDescriptor.getName(), namespace); Type type = getType(metricDescriptor.getType()); List<String> labelNames = convertToLabelNames(metricDescriptor.getLabelKeys()); if (containsDisallowedLeLabelForHistogram(labelNames, type)) { throw new IllegalStateException( "Prometheus Histogram cannot have a label named 'le', " + "because it is a reserved label for bucket boundaries. " + "Please remove this key from your view."); } if (containsDisallowedQuantileLabelForSummary(labelNames, type)) { throw new IllegalStateException( "Prometheus Summary cannot have a label named 'quantile', " + "because it is a reserved label. Please remove this key from your view."); } return new MetricFamilySamples( name, type, metricDescriptor.getDescription(), Collections.<Sample>emptyList()); }
[ "static", "MetricFamilySamples", "createDescribableMetricFamilySamples", "(", "MetricDescriptor", "metricDescriptor", ",", "String", "namespace", ")", "{", "String", "name", "=", "getNamespacedName", "(", "metricDescriptor", ".", "getName", "(", ")", ",", "namespace", ")", ";", "Type", "type", "=", "getType", "(", "metricDescriptor", ".", "getType", "(", ")", ")", ";", "List", "<", "String", ">", "labelNames", "=", "convertToLabelNames", "(", "metricDescriptor", ".", "getLabelKeys", "(", ")", ")", ";", "if", "(", "containsDisallowedLeLabelForHistogram", "(", "labelNames", ",", "type", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Prometheus Histogram cannot have a label named 'le', \"", "+", "\"because it is a reserved label for bucket boundaries. \"", "+", "\"Please remove this key from your view.\"", ")", ";", "}", "if", "(", "containsDisallowedQuantileLabelForSummary", "(", "labelNames", ",", "type", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Prometheus Summary cannot have a label named 'quantile', \"", "+", "\"because it is a reserved label. Please remove this key from your view.\"", ")", ";", "}", "return", "new", "MetricFamilySamples", "(", "name", ",", "type", ",", "metricDescriptor", ".", "getDescription", "(", ")", ",", "Collections", ".", "<", "Sample", ">", "emptyList", "(", ")", ")", ";", "}" ]
Used only for Prometheus metric registry, should not contain any actual samples.
[ "Used", "only", "for", "Prometheus", "metric", "registry", "should", "not", "contain", "any", "actual", "samples", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/stats/prometheus/src/main/java/io/opencensus/exporter/stats/prometheus/PrometheusExportUtils.java#L96-L117
train
census-instrumentation/opencensus-java
exporters/stats/prometheus/src/main/java/io/opencensus/exporter/stats/prometheus/PrometheusExportUtils.java
PrometheusExportUtils.convertToLabelNames
@VisibleForTesting static List<String> convertToLabelNames(List<LabelKey> labelKeys) { final List<String> labelNames = new ArrayList<String>(labelKeys.size()); for (LabelKey labelKey : labelKeys) { labelNames.add(Collector.sanitizeMetricName(labelKey.getKey())); } return labelNames; }
java
@VisibleForTesting static List<String> convertToLabelNames(List<LabelKey> labelKeys) { final List<String> labelNames = new ArrayList<String>(labelKeys.size()); for (LabelKey labelKey : labelKeys) { labelNames.add(Collector.sanitizeMetricName(labelKey.getKey())); } return labelNames; }
[ "@", "VisibleForTesting", "static", "List", "<", "String", ">", "convertToLabelNames", "(", "List", "<", "LabelKey", ">", "labelKeys", ")", "{", "final", "List", "<", "String", ">", "labelNames", "=", "new", "ArrayList", "<", "String", ">", "(", "labelKeys", ".", "size", "(", ")", ")", ";", "for", "(", "LabelKey", "labelKey", ":", "labelKeys", ")", "{", "labelNames", ".", "add", "(", "Collector", ".", "sanitizeMetricName", "(", "labelKey", ".", "getKey", "(", ")", ")", ")", ";", "}", "return", "labelNames", ";", "}" ]
Converts the list of label keys to a list of string label names. Also sanitizes the label keys.
[ "Converts", "the", "list", "of", "label", "keys", "to", "a", "list", "of", "string", "label", "names", ".", "Also", "sanitizes", "the", "label", "keys", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/stats/prometheus/src/main/java/io/opencensus/exporter/stats/prometheus/PrometheusExportUtils.java#L263-L270
train
census-instrumentation/opencensus-java
exporters/trace/ocagent/src/main/java/io/opencensus/exporter/trace/ocagent/TraceProtoUtils.java
TraceProtoUtils.getCurrentTraceConfig
static TraceConfig getCurrentTraceConfig(io.opencensus.trace.config.TraceConfig traceConfig) { TraceParams traceParams = traceConfig.getActiveTraceParams(); return toTraceConfigProto(traceParams); }
java
static TraceConfig getCurrentTraceConfig(io.opencensus.trace.config.TraceConfig traceConfig) { TraceParams traceParams = traceConfig.getActiveTraceParams(); return toTraceConfigProto(traceParams); }
[ "static", "TraceConfig", "getCurrentTraceConfig", "(", "io", ".", "opencensus", ".", "trace", ".", "config", ".", "TraceConfig", "traceConfig", ")", "{", "TraceParams", "traceParams", "=", "traceConfig", ".", "getActiveTraceParams", "(", ")", ";", "return", "toTraceConfigProto", "(", "traceParams", ")", ";", "}" ]
Creates a TraceConfig proto message with current TraceParams.
[ "Creates", "a", "TraceConfig", "proto", "message", "with", "current", "TraceParams", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/trace/ocagent/src/main/java/io/opencensus/exporter/trace/ocagent/TraceProtoUtils.java#L380-L383
train
census-instrumentation/opencensus-java
exporters/trace/ocagent/src/main/java/io/opencensus/exporter/trace/ocagent/TraceProtoUtils.java
TraceProtoUtils.getUpdatedTraceParams
static TraceParams getUpdatedTraceParams( UpdatedLibraryConfig config, io.opencensus.trace.config.TraceConfig traceConfig) { TraceParams currentParams = traceConfig.getActiveTraceParams(); TraceConfig traceConfigProto = config.getConfig(); return fromTraceConfigProto(traceConfigProto, currentParams); }
java
static TraceParams getUpdatedTraceParams( UpdatedLibraryConfig config, io.opencensus.trace.config.TraceConfig traceConfig) { TraceParams currentParams = traceConfig.getActiveTraceParams(); TraceConfig traceConfigProto = config.getConfig(); return fromTraceConfigProto(traceConfigProto, currentParams); }
[ "static", "TraceParams", "getUpdatedTraceParams", "(", "UpdatedLibraryConfig", "config", ",", "io", ".", "opencensus", ".", "trace", ".", "config", ".", "TraceConfig", "traceConfig", ")", "{", "TraceParams", "currentParams", "=", "traceConfig", ".", "getActiveTraceParams", "(", ")", ";", "TraceConfig", "traceConfigProto", "=", "config", ".", "getConfig", "(", ")", ";", "return", "fromTraceConfigProto", "(", "traceConfigProto", ",", "currentParams", ")", ";", "}" ]
TraceParams, then applies the updated TraceParams.
[ "TraceParams", "then", "applies", "the", "updated", "TraceParams", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/trace/ocagent/src/main/java/io/opencensus/exporter/trace/ocagent/TraceProtoUtils.java#L387-L392
train
census-instrumentation/opencensus-java
exporters/trace/elasticsearch/src/main/java/io/opencensus/exporter/trace/elasticsearch/ElasticsearchTraceExporter.java
ElasticsearchTraceExporter.createAndRegister
@SuppressWarnings("nullness") public static void createAndRegister( ElasticsearchTraceConfiguration elasticsearchTraceConfiguration) throws MalformedURLException { synchronized (monitor) { Preconditions.checkState(handler == null, "Elasticsearch exporter already registered."); Preconditions.checkArgument( elasticsearchTraceConfiguration != null, "Elasticsearch " + "configuration not set."); Preconditions.checkArgument( elasticsearchTraceConfiguration.getElasticsearchIndex() != null, "Elasticsearch index not specified"); Preconditions.checkArgument( elasticsearchTraceConfiguration.getElasticsearchType() != null, "Elasticsearch type not specified"); Preconditions.checkArgument( elasticsearchTraceConfiguration.getElasticsearchUrl() != null, "Elasticsearch URL not specified"); handler = new ElasticsearchTraceHandler(elasticsearchTraceConfiguration); register(Tracing.getExportComponent().getSpanExporter(), handler); } }
java
@SuppressWarnings("nullness") public static void createAndRegister( ElasticsearchTraceConfiguration elasticsearchTraceConfiguration) throws MalformedURLException { synchronized (monitor) { Preconditions.checkState(handler == null, "Elasticsearch exporter already registered."); Preconditions.checkArgument( elasticsearchTraceConfiguration != null, "Elasticsearch " + "configuration not set."); Preconditions.checkArgument( elasticsearchTraceConfiguration.getElasticsearchIndex() != null, "Elasticsearch index not specified"); Preconditions.checkArgument( elasticsearchTraceConfiguration.getElasticsearchType() != null, "Elasticsearch type not specified"); Preconditions.checkArgument( elasticsearchTraceConfiguration.getElasticsearchUrl() != null, "Elasticsearch URL not specified"); handler = new ElasticsearchTraceHandler(elasticsearchTraceConfiguration); register(Tracing.getExportComponent().getSpanExporter(), handler); } }
[ "@", "SuppressWarnings", "(", "\"nullness\"", ")", "public", "static", "void", "createAndRegister", "(", "ElasticsearchTraceConfiguration", "elasticsearchTraceConfiguration", ")", "throws", "MalformedURLException", "{", "synchronized", "(", "monitor", ")", "{", "Preconditions", ".", "checkState", "(", "handler", "==", "null", ",", "\"Elasticsearch exporter already registered.\"", ")", ";", "Preconditions", ".", "checkArgument", "(", "elasticsearchTraceConfiguration", "!=", "null", ",", "\"Elasticsearch \"", "+", "\"configuration not set.\"", ")", ";", "Preconditions", ".", "checkArgument", "(", "elasticsearchTraceConfiguration", ".", "getElasticsearchIndex", "(", ")", "!=", "null", ",", "\"Elasticsearch index not specified\"", ")", ";", "Preconditions", ".", "checkArgument", "(", "elasticsearchTraceConfiguration", ".", "getElasticsearchType", "(", ")", "!=", "null", ",", "\"Elasticsearch type not specified\"", ")", ";", "Preconditions", ".", "checkArgument", "(", "elasticsearchTraceConfiguration", ".", "getElasticsearchUrl", "(", ")", "!=", "null", ",", "\"Elasticsearch URL not specified\"", ")", ";", "handler", "=", "new", "ElasticsearchTraceHandler", "(", "elasticsearchTraceConfiguration", ")", ";", "register", "(", "Tracing", ".", "getExportComponent", "(", ")", ".", "getSpanExporter", "(", ")", ",", "handler", ")", ";", "}", "}" ]
Creates and registers the ElasticsearchTraceExporter to the OpenCensus. @param elasticsearchTraceConfiguration {@link ElasticsearchTraceConfiguration} @throws MalformedURLException when the Elasticsearch url is invalid. @throws IllegalStateException if ElasticsearchTraceExporter is already created. @throws IllegalArgumentException when mandatory parameters in the configuration are missing. @since 0.20.0
[ "Creates", "and", "registers", "the", "ElasticsearchTraceExporter", "to", "the", "OpenCensus", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/trace/elasticsearch/src/main/java/io/opencensus/exporter/trace/elasticsearch/ElasticsearchTraceExporter.java#L69-L89
train
census-instrumentation/opencensus-java
contrib/agent/src/main/java/io/opencensus/contrib/agent/Settings.java
Settings.isEnabled
public boolean isEnabled(String featurePath) { checkArgument(!Strings.isNullOrEmpty(featurePath)); return config.getConfig(featurePath).getBoolean("enabled"); }
java
public boolean isEnabled(String featurePath) { checkArgument(!Strings.isNullOrEmpty(featurePath)); return config.getConfig(featurePath).getBoolean("enabled"); }
[ "public", "boolean", "isEnabled", "(", "String", "featurePath", ")", "{", "checkArgument", "(", "!", "Strings", ".", "isNullOrEmpty", "(", "featurePath", ")", ")", ";", "return", "config", ".", "getConfig", "(", "featurePath", ")", ".", "getBoolean", "(", "\"enabled\"", ")", ";", "}" ]
Checks whether a feature is enabled in the effective configuration. <p>A feature is identified by a path expression relative to {@link #CONFIG_ROOT}, such as {@code context-propagation.executor}. The feature is enabled iff the config element at the requested path has a child element {@code enabled} with a value of {@code true}, {@code on}, or {@code yes}. @param featurePath the feature's path expression @return true, if enabled, otherwise false @since 0.10
[ "Checks", "whether", "a", "feature", "is", "enabled", "in", "the", "effective", "configuration", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/contrib/agent/src/main/java/io/opencensus/contrib/agent/Settings.java#L69-L73
train
census-instrumentation/opencensus-java
exporters/trace/ocagent/src/main/java/io/opencensus/exporter/trace/ocagent/OcAgentTraceServiceConfigRpcHandler.java
OcAgentTraceServiceConfigRpcHandler.sendInitialMessage
synchronized void sendInitialMessage(Node node) { io.opencensus.proto.trace.v1.TraceConfig currentTraceConfigProto = TraceProtoUtils.getCurrentTraceConfig(traceConfig); // First config must have Node set. CurrentLibraryConfig firstConfig = CurrentLibraryConfig.newBuilder().setNode(node).setConfig(currentTraceConfigProto).build(); sendCurrentConfig(firstConfig); }
java
synchronized void sendInitialMessage(Node node) { io.opencensus.proto.trace.v1.TraceConfig currentTraceConfigProto = TraceProtoUtils.getCurrentTraceConfig(traceConfig); // First config must have Node set. CurrentLibraryConfig firstConfig = CurrentLibraryConfig.newBuilder().setNode(node).setConfig(currentTraceConfigProto).build(); sendCurrentConfig(firstConfig); }
[ "synchronized", "void", "sendInitialMessage", "(", "Node", "node", ")", "{", "io", ".", "opencensus", ".", "proto", ".", "trace", ".", "v1", ".", "TraceConfig", "currentTraceConfigProto", "=", "TraceProtoUtils", ".", "getCurrentTraceConfig", "(", "traceConfig", ")", ";", "// First config must have Node set.", "CurrentLibraryConfig", "firstConfig", "=", "CurrentLibraryConfig", ".", "newBuilder", "(", ")", ".", "setNode", "(", "node", ")", ".", "setConfig", "(", "currentTraceConfigProto", ")", ".", "build", "(", ")", ";", "sendCurrentConfig", "(", "firstConfig", ")", ";", "}" ]
subsequent updated library configs, unless the stream is interrupted.
[ "subsequent", "updated", "library", "configs", "unless", "the", "stream", "is", "interrupted", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/trace/ocagent/src/main/java/io/opencensus/exporter/trace/ocagent/OcAgentTraceServiceConfigRpcHandler.java#L84-L91
train
census-instrumentation/opencensus-java
exporters/trace/ocagent/src/main/java/io/opencensus/exporter/trace/ocagent/OcAgentTraceServiceConfigRpcHandler.java
OcAgentTraceServiceConfigRpcHandler.sendCurrentConfig
private synchronized void sendCurrentConfig() { // Bouncing back CurrentLibraryConfig to Agent. io.opencensus.proto.trace.v1.TraceConfig currentTraceConfigProto = TraceProtoUtils.getCurrentTraceConfig(traceConfig); CurrentLibraryConfig currentLibraryConfig = CurrentLibraryConfig.newBuilder().setConfig(currentTraceConfigProto).build(); sendCurrentConfig(currentLibraryConfig); }
java
private synchronized void sendCurrentConfig() { // Bouncing back CurrentLibraryConfig to Agent. io.opencensus.proto.trace.v1.TraceConfig currentTraceConfigProto = TraceProtoUtils.getCurrentTraceConfig(traceConfig); CurrentLibraryConfig currentLibraryConfig = CurrentLibraryConfig.newBuilder().setConfig(currentTraceConfigProto).build(); sendCurrentConfig(currentLibraryConfig); }
[ "private", "synchronized", "void", "sendCurrentConfig", "(", ")", "{", "// Bouncing back CurrentLibraryConfig to Agent.", "io", ".", "opencensus", ".", "proto", ".", "trace", ".", "v1", ".", "TraceConfig", "currentTraceConfigProto", "=", "TraceProtoUtils", ".", "getCurrentTraceConfig", "(", "traceConfig", ")", ";", "CurrentLibraryConfig", "currentLibraryConfig", "=", "CurrentLibraryConfig", ".", "newBuilder", "(", ")", ".", "setConfig", "(", "currentTraceConfigProto", ")", ".", "build", "(", ")", ";", "sendCurrentConfig", "(", "currentLibraryConfig", ")", ";", "}" ]
Follow up after applying the updated library config.
[ "Follow", "up", "after", "applying", "the", "updated", "library", "config", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/trace/ocagent/src/main/java/io/opencensus/exporter/trace/ocagent/OcAgentTraceServiceConfigRpcHandler.java#L94-L101
train
census-instrumentation/opencensus-java
exporters/trace/ocagent/src/main/java/io/opencensus/exporter/trace/ocagent/OcAgentTraceServiceConfigRpcHandler.java
OcAgentTraceServiceConfigRpcHandler.sendCurrentConfig
private synchronized void sendCurrentConfig(CurrentLibraryConfig currentLibraryConfig) { if (isCompleted() || currentConfigObserver == null) { return; } try { currentConfigObserver.onNext(currentLibraryConfig); } catch (Exception e) { // Catch client side exceptions. onComplete(e); } }
java
private synchronized void sendCurrentConfig(CurrentLibraryConfig currentLibraryConfig) { if (isCompleted() || currentConfigObserver == null) { return; } try { currentConfigObserver.onNext(currentLibraryConfig); } catch (Exception e) { // Catch client side exceptions. onComplete(e); } }
[ "private", "synchronized", "void", "sendCurrentConfig", "(", "CurrentLibraryConfig", "currentLibraryConfig", ")", "{", "if", "(", "isCompleted", "(", ")", "||", "currentConfigObserver", "==", "null", ")", "{", "return", ";", "}", "try", "{", "currentConfigObserver", ".", "onNext", "(", "currentLibraryConfig", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "// Catch client side exceptions.", "onComplete", "(", "e", ")", ";", "}", "}" ]
Sends current config to Agent if the stream is still connected, otherwise do nothing.
[ "Sends", "current", "config", "to", "Agent", "if", "the", "stream", "is", "still", "connected", "otherwise", "do", "nothing", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/trace/ocagent/src/main/java/io/opencensus/exporter/trace/ocagent/OcAgentTraceServiceConfigRpcHandler.java#L104-L113
train
census-instrumentation/opencensus-java
examples/src/main/java/io/opencensus/examples/stats/StackdriverQuickstart.java
StackdriverQuickstart.main
public static void main(String[] args) throws IOException, InterruptedException { // Register the view. It is imperative that this step exists, // otherwise recorded metrics will be dropped and never exported. View view = View.create( Name.create("task_latency_distribution"), "The distribution of the task latencies.", LATENCY_MS, Aggregation.Distribution.create(LATENCY_BOUNDARIES), Collections.<TagKey>emptyList()); // Create the view manager ViewManager viewManager = Stats.getViewManager(); // Then finally register the views viewManager.registerView(view); // [START setup_exporter] // Enable OpenCensus exporters to export metrics to Stackdriver Monitoring. // Exporters use Application Default Credentials to authenticate. // See https://developers.google.com/identity/protocols/application-default-credentials // for more details. StackdriverStatsExporter.createAndRegister(); // [END setup_exporter] // Record 100 fake latency values between 0 and 5 seconds. Random rand = new Random(); for (int i = 0; i < 100; i++) { long ms = (long) (TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS) * rand.nextDouble()); System.out.println(String.format("Latency %d: %d", i, ms)); STATS_RECORDER.newMeasureMap().put(LATENCY_MS, ms).record(); } // The default export interval is 60 seconds. The thread with the StackdriverStatsExporter must // live for at least the interval past any metrics that must be collected, or some risk being // lost if they are recorded after the last export. System.out.println( String.format( "Sleeping %d seconds before shutdown to ensure all records are flushed.", EXPORT_INTERVAL)); Thread.sleep(TimeUnit.MILLISECONDS.convert(EXPORT_INTERVAL, TimeUnit.SECONDS)); }
java
public static void main(String[] args) throws IOException, InterruptedException { // Register the view. It is imperative that this step exists, // otherwise recorded metrics will be dropped and never exported. View view = View.create( Name.create("task_latency_distribution"), "The distribution of the task latencies.", LATENCY_MS, Aggregation.Distribution.create(LATENCY_BOUNDARIES), Collections.<TagKey>emptyList()); // Create the view manager ViewManager viewManager = Stats.getViewManager(); // Then finally register the views viewManager.registerView(view); // [START setup_exporter] // Enable OpenCensus exporters to export metrics to Stackdriver Monitoring. // Exporters use Application Default Credentials to authenticate. // See https://developers.google.com/identity/protocols/application-default-credentials // for more details. StackdriverStatsExporter.createAndRegister(); // [END setup_exporter] // Record 100 fake latency values between 0 and 5 seconds. Random rand = new Random(); for (int i = 0; i < 100; i++) { long ms = (long) (TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS) * rand.nextDouble()); System.out.println(String.format("Latency %d: %d", i, ms)); STATS_RECORDER.newMeasureMap().put(LATENCY_MS, ms).record(); } // The default export interval is 60 seconds. The thread with the StackdriverStatsExporter must // live for at least the interval past any metrics that must be collected, or some risk being // lost if they are recorded after the last export. System.out.println( String.format( "Sleeping %d seconds before shutdown to ensure all records are flushed.", EXPORT_INTERVAL)); Thread.sleep(TimeUnit.MILLISECONDS.convert(EXPORT_INTERVAL, TimeUnit.SECONDS)); }
[ "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "IOException", ",", "InterruptedException", "{", "// Register the view. It is imperative that this step exists,", "// otherwise recorded metrics will be dropped and never exported.", "View", "view", "=", "View", ".", "create", "(", "Name", ".", "create", "(", "\"task_latency_distribution\"", ")", ",", "\"The distribution of the task latencies.\"", ",", "LATENCY_MS", ",", "Aggregation", ".", "Distribution", ".", "create", "(", "LATENCY_BOUNDARIES", ")", ",", "Collections", ".", "<", "TagKey", ">", "emptyList", "(", ")", ")", ";", "// Create the view manager", "ViewManager", "viewManager", "=", "Stats", ".", "getViewManager", "(", ")", ";", "// Then finally register the views", "viewManager", ".", "registerView", "(", "view", ")", ";", "// [START setup_exporter]", "// Enable OpenCensus exporters to export metrics to Stackdriver Monitoring.", "// Exporters use Application Default Credentials to authenticate.", "// See https://developers.google.com/identity/protocols/application-default-credentials", "// for more details.", "StackdriverStatsExporter", ".", "createAndRegister", "(", ")", ";", "// [END setup_exporter]", "// Record 100 fake latency values between 0 and 5 seconds.", "Random", "rand", "=", "new", "Random", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "100", ";", "i", "++", ")", "{", "long", "ms", "=", "(", "long", ")", "(", "TimeUnit", ".", "MILLISECONDS", ".", "convert", "(", "5", ",", "TimeUnit", ".", "SECONDS", ")", "*", "rand", ".", "nextDouble", "(", ")", ")", ";", "System", ".", "out", ".", "println", "(", "String", ".", "format", "(", "\"Latency %d: %d\"", ",", "i", ",", "ms", ")", ")", ";", "STATS_RECORDER", ".", "newMeasureMap", "(", ")", ".", "put", "(", "LATENCY_MS", ",", "ms", ")", ".", "record", "(", ")", ";", "}", "// The default export interval is 60 seconds. The thread with the StackdriverStatsExporter must", "// live for at least the interval past any metrics that must be collected, or some risk being", "// lost if they are recorded after the last export.", "System", ".", "out", ".", "println", "(", "String", ".", "format", "(", "\"Sleeping %d seconds before shutdown to ensure all records are flushed.\"", ",", "EXPORT_INTERVAL", ")", ")", ";", "Thread", ".", "sleep", "(", "TimeUnit", ".", "MILLISECONDS", ".", "convert", "(", "EXPORT_INTERVAL", ",", "TimeUnit", ".", "SECONDS", ")", ")", ";", "}" ]
Main launcher for the Stackdriver example.
[ "Main", "launcher", "for", "the", "Stackdriver", "example", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/examples/src/main/java/io/opencensus/examples/stats/StackdriverQuickstart.java#L50-L92
train
census-instrumentation/opencensus-java
exporters/trace/ocagent/src/main/java/io/opencensus/exporter/trace/ocagent/OcAgentTraceServiceExportRpcHandler.java
OcAgentTraceServiceExportRpcHandler.onExport
synchronized void onExport(ExportTraceServiceRequest request) { if (isCompleted() || exportRequestObserver == null) { return; } try { exportRequestObserver.onNext(request); } catch (Exception e) { // Catch client side exceptions. onComplete(e); } }
java
synchronized void onExport(ExportTraceServiceRequest request) { if (isCompleted() || exportRequestObserver == null) { return; } try { exportRequestObserver.onNext(request); } catch (Exception e) { // Catch client side exceptions. onComplete(e); } }
[ "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.
[ "Sends", "the", "export", "request", "to", "Agent", "if", "the", "stream", "is", "still", "connected", "otherwise", "do", "nothing", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/trace/ocagent/src/main/java/io/opencensus/exporter/trace/ocagent/OcAgentTraceServiceExportRpcHandler.java#L73-L82
train
census-instrumentation/opencensus-java
api/src/main/java/io/opencensus/common/Duration.java
Duration.create
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); }
java
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); }
[ "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. @param seconds Signed seconds of the span of time. Must be from -315,576,000,000 to +315,576,000,000 inclusive. @param nanos Signed fractions of a second at nanosecond resolution of the span of time. Durations less than one second are represented with a 0 `seconds` field and a positive or negative `nanos` field. For durations of one second or more, a non-zero value for the `nanos` field must be of the same sign as the `seconds` field. Must be from -999,999,999 to +999,999,999 inclusive. @return new {@code Duration} with specified fields. @throws IllegalArgumentException if the arguments are out of range or have inconsistent sign. @since 0.5
[ "Creates", "a", "new", "time", "duration", "from", "given", "seconds", "and", "nanoseconds", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/api/src/main/java/io/opencensus/common/Duration.java#L53-L75
train
census-instrumentation/opencensus-java
exporters/trace/ocagent/src/main/java/io/opencensus/exporter/trace/ocagent/OcAgentNodeUtils.java
OcAgentNodeUtils.getNodeInfo
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(); }
java
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(); }
[ "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.
[ "Creates", "a", "Node", "with", "information", "from", "the", "OpenCensus", "library", "and", "environment", "variables", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/trace/ocagent/src/main/java/io/opencensus/exporter/trace/ocagent/OcAgentNodeUtils.java#L48-L56
train
census-instrumentation/opencensus-java
exporters/trace/ocagent/src/main/java/io/opencensus/exporter/trace/ocagent/OcAgentNodeUtils.java
OcAgentNodeUtils.getLibraryInfo
@VisibleForTesting static LibraryInfo getLibraryInfo(String currentOcJavaVersion) { return LibraryInfo.newBuilder() .setLanguage(Language.JAVA) .setCoreLibraryVersion(currentOcJavaVersion) .setExporterVersion(OC_AGENT_EXPORTER_VERSION) .build(); }
java
@VisibleForTesting static LibraryInfo getLibraryInfo(String currentOcJavaVersion) { return LibraryInfo.newBuilder() .setLanguage(Language.JAVA) .setCoreLibraryVersion(currentOcJavaVersion) .setExporterVersion(OC_AGENT_EXPORTER_VERSION) .build(); }
[ "@", "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.
[ "Creates", "library", "info", "with", "the", "given", "OpenCensus", "Java", "version", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/trace/ocagent/src/main/java/io/opencensus/exporter/trace/ocagent/OcAgentNodeUtils.java#L92-L99
train
census-instrumentation/opencensus-java
exporters/trace/ocagent/src/main/java/io/opencensus/exporter/trace/ocagent/OcAgentNodeUtils.java
OcAgentNodeUtils.getServiceInfo
@VisibleForTesting static ServiceInfo getServiceInfo(String serviceName) { return ServiceInfo.newBuilder().setName(serviceName).build(); }
java
@VisibleForTesting static ServiceInfo getServiceInfo(String serviceName) { return ServiceInfo.newBuilder().setName(serviceName).build(); }
[ "@", "VisibleForTesting", "static", "ServiceInfo", "getServiceInfo", "(", "String", "serviceName", ")", "{", "return", "ServiceInfo", ".", "newBuilder", "(", ")", ".", "setName", "(", "serviceName", ")", ".", "build", "(", ")", ";", "}" ]
Creates service info with the given service name.
[ "Creates", "service", "info", "with", "the", "given", "service", "name", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/trace/ocagent/src/main/java/io/opencensus/exporter/trace/ocagent/OcAgentNodeUtils.java#L102-L105
train
census-instrumentation/opencensus-java
contrib/http_util/src/main/java/io/opencensus/contrib/http/HttpServerHandler.java
HttpServerHandler.handleStart
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()); }
java
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()); }
[ "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. <p>This method will create a span under the deserialized propagated parent context. If the parent context is not present, the span will be created under the current context. <p>The generated span will NOT be set as current context. User can control when to enter the scope of this span. Use {@link AbstractHttpHandler#getSpanFromContext} to retrieve the span. @param carrier the entity that holds the HTTP information. @param request the request entity. @return the {@link HttpRequestContext} that contains stats and trace data associated with the request. @since 0.19
[ "Instrument", "an", "incoming", "request", "before", "it", "is", "handled", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/contrib/http_util/src/main/java/io/opencensus/contrib/http/HttpServerHandler.java#L118-L147
train
census-instrumentation/opencensus-java
contrib/zpages/src/main/java/io/opencensus/contrib/zpages/RpczZPageHandler.java
RpczZPageHandler.getStatsSnapshots
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; }
java
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; }
[ "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.
[ "Gets", "stats", "snapshot", "for", "each", "method", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/contrib/zpages/src/main/java/io/opencensus/contrib/zpages/RpczZPageHandler.java#L331-L343
train
census-instrumentation/opencensus-java
contrib/zpages/src/main/java/io/opencensus/contrib/zpages/RpczZPageHandler.java
RpczZPageHandler.getDurationInSecs
private static double getDurationInSecs( ViewData.AggregationWindowData.CumulativeData cumulativeData) { return toDoubleSeconds(cumulativeData.getEnd().subtractTimestamp(cumulativeData.getStart())); }
java
private static double getDurationInSecs( ViewData.AggregationWindowData.CumulativeData cumulativeData) { return toDoubleSeconds(cumulativeData.getEnd().subtractTimestamp(cumulativeData.getStart())); }
[ "private", "static", "double", "getDurationInSecs", "(", "ViewData", ".", "AggregationWindowData", ".", "CumulativeData", "cumulativeData", ")", "{", "return", "toDoubleSeconds", "(", "cumulativeData", ".", "getEnd", "(", ")", ".", "subtractTimestamp", "(", "cumulativeData", ".", "getStart", "(", ")", ")", ")", ";", "}" ]
Calculates the duration of the given CumulativeData in seconds.
[ "Calculates", "the", "duration", "of", "the", "given", "CumulativeData", "in", "seconds", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/contrib/zpages/src/main/java/io/opencensus/contrib/zpages/RpczZPageHandler.java#L446-L449
train
census-instrumentation/opencensus-java
examples/src/main/java/io/opencensus/examples/helloworld/QuickStart.java
QuickStart.main
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)); }
java
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)); }
[ "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.
[ "Main", "launcher", "for", "the", "QuickStart", "example", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/examples/src/main/java/io/opencensus/examples/helloworld/QuickStart.java#L77-L110
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/tags/TagsBenchmarksUtil.java
TagsBenchmarksUtil.createTagKeys
@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; }
java
@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; }
[ "@", "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.
[ "Creates", "an", "array", "of", "TagKeys", "of", "size", "with", "name", "prefix", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/tags/TagsBenchmarksUtil.java#L78-L85
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/tags/TagsBenchmarksUtil.java
TagsBenchmarksUtil.createTagValues
@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; }
java
@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; }
[ "@", "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.
[ "Creates", "an", "array", "of", "TagValues", "of", "size", "with", "name", "prefix", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/tags/TagsBenchmarksUtil.java#L88-L95
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/tags/TagsBenchmarksUtil.java
TagsBenchmarksUtil.createTagContext
@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(); }
java
@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(); }
[ "@", "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.
[ "Adds", "numTags", "tags", "to", "tagsBuilder", "and", "returns", "the", "associated", "tag", "context", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/tags/TagsBenchmarksUtil.java#L98-L104
train
census-instrumentation/opencensus-java
impl/src/main/java/io/opencensus/impl/internal/DisruptorEventQueue.java
DisruptorEventQueue.create
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); }
java
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); }
[ "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.
[ "Creates", "a", "new", "EventQueue", ".", "Private", "to", "prevent", "creation", "of", "non", "-", "singleton", "instance", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/impl/src/main/java/io/opencensus/impl/internal/DisruptorEventQueue.java#L115-L144
train
census-instrumentation/opencensus-java
impl/src/main/java/io/opencensus/impl/internal/DisruptorEventQueue.java
DisruptorEventQueue.shutdown
@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(); }
java
@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(); }
[ "@", "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.
[ "Shuts", "down", "the", "underlying", "disruptor", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/impl/src/main/java/io/opencensus/impl/internal/DisruptorEventQueue.java#L166-L181
train
census-instrumentation/opencensus-java
api/src/main/java/io/opencensus/trace/Tracer.java
Tracer.getCurrentSpan
public final Span getCurrentSpan() { Span currentSpan = CurrentSpanUtils.getCurrentSpan(); return currentSpan != null ? currentSpan : BlankSpan.INSTANCE; }
java
public final Span getCurrentSpan() { Span currentSpan = CurrentSpanUtils.getCurrentSpan(); return currentSpan != null ? currentSpan : BlankSpan.INSTANCE; }
[ "public", "final", "Span", "getCurrentSpan", "(", ")", "{", "Span", "currentSpan", "=", "CurrentSpanUtils", ".", "getCurrentSpan", "(", ")", ";", "return", "currentSpan", "!=", "null", "?", "currentSpan", ":", "BlankSpan", ".", "INSTANCE", ";", "}" ]
Gets the current Span from the current Context. <p>To install a {@link Span} to the current Context use {@link #withSpan(Span)} OR use {@link SpanBuilder#startScopedSpan} methods to start a new {@code Span}. <p>startSpan methods do NOT modify the current Context {@code Span}. @return a default {@code Span} that does nothing and has an invalid {@link SpanContext} if no {@code Span} is associated with the current Context, otherwise the current {@code Span} from the Context. @since 0.5
[ "Gets", "the", "current", "Span", "from", "the", "current", "Context", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/api/src/main/java/io/opencensus/trace/Tracer.java#L97-L100
train
census-instrumentation/opencensus-java
exporters/trace/zipkin/src/main/java/io/opencensus/exporter/trace/zipkin/ZipkinTraceExporter.java
ZipkinTraceExporter.unregister
public static void unregister() { synchronized (monitor) { checkState(handler != null, "Zipkin exporter is not registered."); unregister(Tracing.getExportComponent().getSpanExporter()); handler = null; } }
java
public static void unregister() { synchronized (monitor) { checkState(handler != null, "Zipkin exporter is not registered."); unregister(Tracing.getExportComponent().getSpanExporter()); handler = null; } }
[ "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. @throws IllegalStateException if a Zipkin exporter is not registered. @since 0.12
[ "Unregisters", "the", "Zipkin", "Trace", "exporter", "from", "the", "OpenCensus", "library", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/trace/zipkin/src/main/java/io/opencensus/exporter/trace/zipkin/ZipkinTraceExporter.java#L106-L112
train
census-instrumentation/opencensus-java
contrib/spring_sleuth_v1x/src/main/java/io/opencensus/contrib/spring/sleuth/v1x/OpenCensusSleuthSpanContextHolder.java
OpenCensusSleuthSpanContextHolder.getCurrentSpan
@javax.annotation.Nullable static Span getCurrentSpan() { SpanContext currentSpanContext = CURRENT_SPAN.get(); return currentSpanContext != null ? currentSpanContext.span : null; }
java
@javax.annotation.Nullable static Span getCurrentSpan() { SpanContext currentSpanContext = CURRENT_SPAN.get(); return currentSpanContext != null ? currentSpanContext.span : null; }
[ "@", "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.
[ "Get", "the", "current", "span", "out", "of", "the", "thread", "context", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/contrib/spring_sleuth_v1x/src/main/java/io/opencensus/contrib/spring/sleuth/v1x/OpenCensusSleuthSpanContextHolder.java#L39-L43
train
census-instrumentation/opencensus-java
contrib/spring_sleuth_v1x/src/main/java/io/opencensus/contrib/spring/sleuth/v1x/OpenCensusSleuthSpanContextHolder.java
OpenCensusSleuthSpanContextHolder.setCurrentSpan
static void setCurrentSpan(Span span) { if (log.isTraceEnabled()) { log.trace("Setting current span " + span); } push(span, /* autoClose= */ false); }
java
static void setCurrentSpan(Span span) { if (log.isTraceEnabled()) { log.trace("Setting current span " + span); } push(span, /* autoClose= */ false); }
[ "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
[ "Set", "the", "current", "span", "in", "the", "thread", "context" ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/contrib/spring_sleuth_v1x/src/main/java/io/opencensus/contrib/spring/sleuth/v1x/OpenCensusSleuthSpanContextHolder.java#L46-L51
train
census-instrumentation/opencensus-java
contrib/spring_sleuth_v1x/src/main/java/io/opencensus/contrib/spring/sleuth/v1x/OpenCensusSleuthSpanContextHolder.java
OpenCensusSleuthSpanContextHolder.close
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; } } }
java
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; } } }
[ "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.
[ "will", "be", "applied", "on", "the", "closed", "Span", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/contrib/spring_sleuth_v1x/src/main/java/io/opencensus/contrib/spring/sleuth/v1x/OpenCensusSleuthSpanContextHolder.java#L82-L91
train
census-instrumentation/opencensus-java
contrib/spring_sleuth_v1x/src/main/java/io/opencensus/contrib/spring/sleuth/v1x/OpenCensusSleuthSpanContextHolder.java
OpenCensusSleuthSpanContextHolder.push
static void push(Span span, boolean autoClose) { if (isCurrent(span)) { return; } setSpanContextInternal(new SpanContext(span, autoClose)); }
java
static void push(Span span, boolean autoClose) { if (isCurrent(span)) { return; } setSpanContextInternal(new SpanContext(span, autoClose)); }
[ "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.
[ "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", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/contrib/spring_sleuth_v1x/src/main/java/io/opencensus/contrib/spring/sleuth/v1x/OpenCensusSleuthSpanContextHolder.java#L103-L108
train
census-instrumentation/opencensus-java
examples/src/main/java/io/opencensus/examples/quickstart/Repl.java
Repl.main
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; } } }
java
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; } } }
[ "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.
[ "Main", "launcher", "for", "the", "Repl", "example", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/examples/src/main/java/io/opencensus/examples/quickstart/Repl.java#L71-L93
train
census-instrumentation/opencensus-java
api/src/main/java/io/opencensus/trace/Tracestate.java
Tracestate.get
@javax.annotation.Nullable public String get(String key) { for (Entry entry : getEntries()) { if (entry.getKey().equals(key)) { return entry.getValue(); } } return null; }
java
@javax.annotation.Nullable public String get(String key) { for (Entry entry : getEntries()) { if (entry.getKey().equals(key)) { return entry.getValue(); } } return null; }
[ "@", "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. @param key with which the specified value is to be associated @return the value to which the specified key is mapped, or null if this map contains no mapping for the key. @since 0.16
[ "Returns", "the", "value", "to", "which", "the", "specified", "key", "is", "mapped", "or", "null", "if", "this", "map", "contains", "no", "mapping", "for", "the", "key", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/api/src/main/java/io/opencensus/trace/Tracestate.java#L59-L67
train
census-instrumentation/opencensus-java
api/src/main/java/io/opencensus/trace/Tracestate.java
Tracestate.validateValue
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; }
java
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; }
[ "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 =.
[ "0x20", "to", "0x7E", ")", "except", "comma", "and", "=", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/api/src/main/java/io/opencensus/trace/Tracestate.java#L254-L265
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/tags/NestedTagContextCreationBenchmark.java
NestedTagContextCreationBenchmark.timeNestedTagContext
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public TagContext timeNestedTagContext(Data data) { return TagsBenchmarksUtil.createTagContext( data.tagger.toBuilder(data.baseTagContext), data.numTags); }
java
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public TagContext timeNestedTagContext(Data data) { return TagsBenchmarksUtil.createTagContext( data.tagger.toBuilder(data.baseTagContext), data.numTags); }
[ "@", "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.
[ "Build", "nested", "tag", "context", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/tags/NestedTagContextCreationBenchmark.java#L55-L61
train
census-instrumentation/opencensus-java
exporters/trace/jaeger/src/main/java/io/opencensus/exporter/trace/jaeger/JaegerTraceExporter.java
JaegerTraceExporter.createAndRegister
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); } }
java
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); } }
[ "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. @param thriftEndpoint the Thrift endpoint of your Jaeger instance, e.g.: "http://127.0.0.1:14268/api/traces" @param serviceName the local service name of the process. @throws IllegalStateException if a Jaeger exporter is already registered. @since 0.13
[ "Creates", "and", "registers", "the", "Jaeger", "Trace", "exporter", "to", "the", "OpenCensus", "library", ".", "Only", "one", "Jaeger", "exporter", "can", "be", "registered", "at", "any", "point", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/trace/jaeger/src/main/java/io/opencensus/exporter/trace/jaeger/JaegerTraceExporter.java#L63-L70
train
census-instrumentation/opencensus-java
exporters/trace/jaeger/src/main/java/io/opencensus/exporter/trace/jaeger/JaegerTraceExporter.java
JaegerTraceExporter.createWithSender
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); } }
java
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); } }
[ "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. @param sender the pre-configured ThriftSender to use with the exporter @param serviceName the local service name of the process. @throws IllegalStateException if a Jaeger exporter is already registered. @since 0.17
[ "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", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/trace/jaeger/src/main/java/io/opencensus/exporter/trace/jaeger/JaegerTraceExporter.java#L81-L88
train
census-instrumentation/opencensus-java
examples/src/main/java/io/opencensus/examples/grpc/helloworld/HelloWorldServer.java
HelloWorldServer.performWork
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."); } }
java
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."); } }
[ "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.
[ "A", "helper", "function", "that", "performs", "some", "work", "in", "its", "own", "Span", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/examples/src/main/java/io/opencensus/examples/grpc/helloworld/HelloWorldServer.java#L61-L74
train
census-instrumentation/opencensus-java
contrib/zpages/src/main/java/io/opencensus/contrib/zpages/TraceConfigzZPageHandler.java
TraceConfigzZPageHandler.emitTraceParamsTable
@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"); }
java
@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"); }
[ "@", "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.
[ "Prints", "a", "table", "to", "a", "PrintWriter", "that", "shows", "existing", "trace", "parameters", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/contrib/zpages/src/main/java/io/opencensus/contrib/zpages/TraceConfigzZPageHandler.java#L192-L218
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/RecordTraceEventsBenchmark.java
RecordTraceEventsBenchmark.putAttribute
@Benchmark @BenchmarkMode(Mode.SampleTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Span putAttribute(Data data) { data.span.putAttribute(ATTRIBUTE_KEY, AttributeValue.stringAttributeValue(ATTRIBUTE_VALUE)); return data.span; }
java
@Benchmark @BenchmarkMode(Mode.SampleTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Span putAttribute(Data data) { data.span.putAttribute(ATTRIBUTE_KEY, AttributeValue.stringAttributeValue(ATTRIBUTE_VALUE)); return data.span; }
[ "@", "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.
[ "This", "benchmark", "attempts", "to", "measure", "performance", "of", "adding", "an", "attribute", "to", "the", "span", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/RecordTraceEventsBenchmark.java#L84-L90
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/RecordTraceEventsBenchmark.java
RecordTraceEventsBenchmark.addAnnotation
@Benchmark @BenchmarkMode(Mode.SampleTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Span addAnnotation(Data data) { data.span.addAnnotation(ANNOTATION_DESCRIPTION); return data.span; }
java
@Benchmark @BenchmarkMode(Mode.SampleTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Span addAnnotation(Data data) { data.span.addAnnotation(ANNOTATION_DESCRIPTION); return data.span; }
[ "@", "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.
[ "This", "benchmark", "attempts", "to", "measure", "performance", "of", "adding", "an", "annotation", "to", "the", "span", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/RecordTraceEventsBenchmark.java#L93-L99
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/RecordTraceEventsBenchmark.java
RecordTraceEventsBenchmark.addMessageEvent
@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; }
java
@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; }
[ "@", "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.
[ "This", "benchmark", "attempts", "to", "measure", "performance", "of", "adding", "a", "network", "event", "to", "the", "span", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/RecordTraceEventsBenchmark.java#L102-L111
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/RecordTraceEventsBenchmark.java
RecordTraceEventsBenchmark.addLink
@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; }
java
@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; }
[ "@", "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.
[ "This", "benchmark", "attempts", "to", "measure", "performance", "of", "adding", "a", "link", "to", "the", "span", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/RecordTraceEventsBenchmark.java#L114-L121
train
census-instrumentation/opencensus-java
exporters/metrics/ocagent/src/main/java/io/opencensus/exporter/metrics/ocagent/OcAgentMetricsServiceExportRpcHandler.java
OcAgentMetricsServiceExportRpcHandler.create
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; }
java
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; }
[ "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.
[ "given", "MetricsServiceStub", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/metrics/ocagent/src/main/java/io/opencensus/exporter/metrics/ocagent/OcAgentMetricsServiceExportRpcHandler.java#L58-L70
train
census-instrumentation/opencensus-java
api/src/main/java/io/opencensus/common/Timestamp.java
Timestamp.create
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); }
java
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); }
[ "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. @param seconds Represents seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. Must be from from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive. @param nanos Non-negative fractions of a second at nanosecond resolution. Negative second values with fractions must still have non-negative nanos values that count forward in time. Must be from 0 to 999,999,999 inclusive. @return new {@code Timestamp} with specified fields. @throws IllegalArgumentException if the arguments are out of range. @since 0.5
[ "Creates", "a", "new", "timestamp", "from", "given", "seconds", "and", "nanoseconds", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/api/src/main/java/io/opencensus/common/Timestamp.java#L57-L74
train
census-instrumentation/opencensus-java
api/src/main/java/io/opencensus/common/Timestamp.java
Timestamp.fromMillis
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 }
java
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 }
[ "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. @param epochMilli the timestamp represented in milliseconds since epoch. @return new {@code Timestamp} with specified fields. @throws IllegalArgumentException if the number of milliseconds is out of the range that can be represented by {@code Timestamp}. @since 0.5
[ "Creates", "a", "new", "timestamp", "from", "the", "given", "milliseconds", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/api/src/main/java/io/opencensus/common/Timestamp.java#L85-L89
train
census-instrumentation/opencensus-java
api/src/main/java/io/opencensus/common/Timestamp.java
Timestamp.plus
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); }
java
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); }
[ "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.
[ "Returns", "a", "Timestamp", "with", "the", "specified", "duration", "added", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/api/src/main/java/io/opencensus/common/Timestamp.java#L172-L181
train
census-instrumentation/opencensus-java
api/src/main/java/io/opencensus/common/Timestamp.java
Timestamp.floorDiv
private static long floorDiv(long x, long y) { return BigDecimal.valueOf(x).divide(BigDecimal.valueOf(y), 0, RoundingMode.FLOOR).longValue(); }
java
private static long floorDiv(long x, long y) { return BigDecimal.valueOf(x).divide(BigDecimal.valueOf(y), 0, RoundingMode.FLOOR).longValue(); }
[ "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.
[ "Returns", "the", "result", "of", "dividing", "x", "by", "y", "rounded", "using", "floor", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/api/src/main/java/io/opencensus/common/Timestamp.java#L192-L194
train
census-instrumentation/opencensus-java
contrib/resource_util/src/main/java/io/opencensus/contrib/resource/util/AwsIdentityDocUtils.java
AwsIdentityDocUtils.initializeAwsIdentityDocument
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(); }
java
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(); }
[ "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.
[ "This", "method", "should", "only", "be", "called", "once", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/contrib/resource_util/src/main/java/io/opencensus/contrib/resource/util/AwsIdentityDocUtils.java#L53-L72
train
census-instrumentation/opencensus-java
impl_core/src/main/java/io/opencensus/implcore/stats/MeasureToViewMap.java
MeasureToViewMap.filterExportedViews
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); }
java
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); }
[ "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
[ "Returns", "the", "subset", "of", "the", "given", "views", "that", "should", "be", "exported" ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/impl_core/src/main/java/io/opencensus/implcore/stats/MeasureToViewMap.java#L89-L97
train
census-instrumentation/opencensus-java
impl_core/src/main/java/io/opencensus/implcore/stats/MeasureToViewMap.java
MeasureToViewMap.record
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); } } }
java
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); } } }
[ "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.
[ "Records", "stats", "with", "a", "set", "of", "tags", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/impl_core/src/main/java/io/opencensus/implcore/stats/MeasureToViewMap.java#L148-L164
train
census-instrumentation/opencensus-java
impl_core/src/main/java/io/opencensus/implcore/stats/MeasureToViewMap.java
MeasureToViewMap.clearStats
synchronized void clearStats() { for (Entry<String, Collection<MutableViewData>> entry : mutableMap.asMap().entrySet()) { for (MutableViewData mutableViewData : entry.getValue()) { mutableViewData.clearStats(); } } }
java
synchronized void clearStats() { for (Entry<String, Collection<MutableViewData>> entry : mutableMap.asMap().entrySet()) { for (MutableViewData mutableViewData : entry.getValue()) { mutableViewData.clearStats(); } } }
[ "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
[ "Clear", "stats", "for", "all", "the", "current", "MutableViewData" ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/impl_core/src/main/java/io/opencensus/implcore/stats/MeasureToViewMap.java#L179-L185
train
census-instrumentation/opencensus-java
impl_core/src/main/java/io/opencensus/implcore/stats/MeasureToViewMap.java
MeasureToViewMap.resumeStatsCollection
synchronized void resumeStatsCollection(Timestamp now) { for (Entry<String, Collection<MutableViewData>> entry : mutableMap.asMap().entrySet()) { for (MutableViewData mutableViewData : entry.getValue()) { mutableViewData.resumeStatsCollection(now); } } }
java
synchronized void resumeStatsCollection(Timestamp now) { for (Entry<String, Collection<MutableViewData>> entry : mutableMap.asMap().entrySet()) { for (MutableViewData mutableViewData : entry.getValue()) { mutableViewData.resumeStatsCollection(now); } } }
[ "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.
[ "Resume", "stats", "collection", "for", "all", "MutableViewData", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/impl_core/src/main/java/io/opencensus/implcore/stats/MeasureToViewMap.java#L188-L194
train
census-instrumentation/opencensus-java
exporters/metrics/ocagent/src/main/java/io/opencensus/exporter/metrics/ocagent/OcAgentNodeUtils.java
OcAgentNodeUtils.getProcessIdentifier
@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(); }
java
@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(); }
[ "@", "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.
[ "Creates", "process", "identifier", "with", "the", "given", "JVM", "name", "and", "start", "time", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/metrics/ocagent/src/main/java/io/opencensus/exporter/metrics/ocagent/OcAgentNodeUtils.java#L60-L90
train
census-instrumentation/opencensus-java
examples/src/main/java/io/opencensus/examples/ocagent/OcAgentExportersQuickStart.java
OcAgentExportersQuickStart.main
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. } }
java
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. } }
[ "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.
[ "Main", "launcher", "of", "the", "example", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/examples/src/main/java/io/opencensus/examples/ocagent/OcAgentExportersQuickStart.java#L173-L192
train
census-instrumentation/opencensus-java
impl_core/src/main/java/io/opencensus/implcore/internal/CurrentState.java
CurrentState.get
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; }
java
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; }
[ "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. @return the current state and updates the status as being read.
[ "Returns", "the", "current", "state", "and", "updates", "the", "status", "as", "being", "read", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/impl_core/src/main/java/io/opencensus/implcore/internal/CurrentState.java#L79-L93
train
census-instrumentation/opencensus-java
impl_core/src/main/java/io/opencensus/implcore/internal/CurrentState.java
CurrentState.set
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; } } }
java
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; } } }
[ "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. @param state the state to be set. @return true if the current state is changed, false otherwise.
[ "Sets", "current", "state", "to", "the", "given", "state", ".", "Returns", "true", "if", "the", "current", "state", "is", "changed", "false", "otherwise", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/impl_core/src/main/java/io/opencensus/implcore/internal/CurrentState.java#L111-L130
train
census-instrumentation/opencensus-java
impl_core/src/main/java/io/opencensus/implcore/tags/propagation/CorrelationContextFormat.java
CorrelationContextFormat.encodeTag
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; }
java
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; }
[ "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.
[ "Encodes", "the", "tag", "to", "the", "given", "string", "builder", "and", "returns", "the", "length", "of", "encoded", "key", "-", "value", "pair", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/impl_core/src/main/java/io/opencensus/implcore/tags/propagation/CorrelationContextFormat.java#L127-L139
train
census-instrumentation/opencensus-java
impl_core/src/main/java/io/opencensus/implcore/tags/propagation/CorrelationContextFormat.java
CorrelationContextFormat.decodeTag
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); }
java
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); }
[ "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.
[ "The", "format", "of", "encoded", "string", "tag", "is", "name1", "=", "value1", ";", "properties1", "=", "p1", ";", "properties2", "=", "p2", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/impl_core/src/main/java/io/opencensus/implcore/tags/propagation/CorrelationContextFormat.java#L171-L187
train
census-instrumentation/opencensus-java
contrib/zpages/src/main/java/io/opencensus/contrib/zpages/TracezZPageHandler.java
TracezZPageHandler.emitSpans
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"); }
java
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"); }
[ "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.
[ "Emits", "the", "list", "of", "SampledRequets", "with", "a", "header", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/contrib/zpages/src/main/java/io/opencensus/contrib/zpages/TracezZPageHandler.java#L281-L302
train
census-instrumentation/opencensus-java
contrib/zpages/src/main/java/io/opencensus/contrib/zpages/TracezZPageHandler.java
TracezZPageHandler.emitSummaryTable
private void emitSummaryTable(PrintWriter out, Formatter formatter) throws UnsupportedEncodingException { if (runningSpanStore == null || sampledSpanStore == null) { return; } RunningSpanStore.Summary runningSpanStoreSummary = runningSpanStore.getSummary(); SampledSpanStore.Summary sampledSpanStoreSummary = sampledSpanStore.getSummary(); out.write("<table style='border-spacing: 0;\n"); out.write("border-left:1px solid #3D3D3D;border-right:1px solid #3D3D3D;'>\n"); emitSummaryTableHeader(out, formatter); Set<String> spanNames = new TreeSet<>(runningSpanStoreSummary.getPerSpanNameSummary().keySet()); spanNames.addAll(sampledSpanStoreSummary.getPerSpanNameSummary().keySet()); boolean zebraColor = true; for (String spanName : spanNames) { out.write("<tr class=\"border\">\n"); if (!zebraColor) { out.write("<tr class=\"border\">\n"); } else { formatter.format("<tr class=\"border\" style=\"background: %s\">%n", ZEBRA_STRIPE_COLOR); } zebraColor = !zebraColor; formatter.format("<td>%s</td>%n", htmlEscaper().escape(spanName)); // Running out.write("<td class=\"borderRL\">&nbsp;&nbsp;&nbsp;&nbsp;</td>"); RunningSpanStore.PerSpanNameSummary runningSpanStorePerSpanNameSummary = runningSpanStoreSummary.getPerSpanNameSummary().get(spanName); // subtype ignored for running requests. emitSingleCell( out, formatter, spanName, runningSpanStorePerSpanNameSummary == null ? 0 : runningSpanStorePerSpanNameSummary.getNumRunningSpans(), RequestType.RUNNING, 0); SampledSpanStore.PerSpanNameSummary sampledSpanStorePerSpanNameSummary = sampledSpanStoreSummary.getPerSpanNameSummary().get(spanName); // Latency based samples out.write("<td class=\"borderLC\">&nbsp;&nbsp;&nbsp;&nbsp;</td>"); Map<LatencyBucketBoundaries, Integer> latencyBucketsSummaries = sampledSpanStorePerSpanNameSummary != null ? sampledSpanStorePerSpanNameSummary.getNumbersOfLatencySampledSpans() : null; int subtype = 0; for (LatencyBucketBoundaries latencyBucketsBoundaries : LatencyBucketBoundaries.values()) { if (latencyBucketsSummaries != null) { int numSamples = latencyBucketsSummaries.containsKey(latencyBucketsBoundaries) ? latencyBucketsSummaries.get(latencyBucketsBoundaries) : 0; emitSingleCell(out, formatter, spanName, numSamples, RequestType.FINISHED, subtype++); } else { // numSamples < -1 means "Not Available". emitSingleCell(out, formatter, spanName, -1, RequestType.FINISHED, subtype++); } } // Error based samples. out.write("<td class=\"borderRL\">&nbsp;&nbsp;&nbsp;&nbsp;</td>"); if (sampledSpanStorePerSpanNameSummary != null) { Map<CanonicalCode, Integer> errorBucketsSummaries = sampledSpanStorePerSpanNameSummary.getNumbersOfErrorSampledSpans(); int numErrorSamples = 0; for (Map.Entry<CanonicalCode, Integer> it : errorBucketsSummaries.entrySet()) { numErrorSamples += it.getValue(); } // subtype 0 means all; emitSingleCell(out, formatter, spanName, numErrorSamples, RequestType.FAILED, 0); } else { // numSamples < -1 means "Not Available". emitSingleCell(out, formatter, spanName, -1, RequestType.FAILED, 0); } out.write("</tr>\n"); } out.write("</table>"); }
java
private void emitSummaryTable(PrintWriter out, Formatter formatter) throws UnsupportedEncodingException { if (runningSpanStore == null || sampledSpanStore == null) { return; } RunningSpanStore.Summary runningSpanStoreSummary = runningSpanStore.getSummary(); SampledSpanStore.Summary sampledSpanStoreSummary = sampledSpanStore.getSummary(); out.write("<table style='border-spacing: 0;\n"); out.write("border-left:1px solid #3D3D3D;border-right:1px solid #3D3D3D;'>\n"); emitSummaryTableHeader(out, formatter); Set<String> spanNames = new TreeSet<>(runningSpanStoreSummary.getPerSpanNameSummary().keySet()); spanNames.addAll(sampledSpanStoreSummary.getPerSpanNameSummary().keySet()); boolean zebraColor = true; for (String spanName : spanNames) { out.write("<tr class=\"border\">\n"); if (!zebraColor) { out.write("<tr class=\"border\">\n"); } else { formatter.format("<tr class=\"border\" style=\"background: %s\">%n", ZEBRA_STRIPE_COLOR); } zebraColor = !zebraColor; formatter.format("<td>%s</td>%n", htmlEscaper().escape(spanName)); // Running out.write("<td class=\"borderRL\">&nbsp;&nbsp;&nbsp;&nbsp;</td>"); RunningSpanStore.PerSpanNameSummary runningSpanStorePerSpanNameSummary = runningSpanStoreSummary.getPerSpanNameSummary().get(spanName); // subtype ignored for running requests. emitSingleCell( out, formatter, spanName, runningSpanStorePerSpanNameSummary == null ? 0 : runningSpanStorePerSpanNameSummary.getNumRunningSpans(), RequestType.RUNNING, 0); SampledSpanStore.PerSpanNameSummary sampledSpanStorePerSpanNameSummary = sampledSpanStoreSummary.getPerSpanNameSummary().get(spanName); // Latency based samples out.write("<td class=\"borderLC\">&nbsp;&nbsp;&nbsp;&nbsp;</td>"); Map<LatencyBucketBoundaries, Integer> latencyBucketsSummaries = sampledSpanStorePerSpanNameSummary != null ? sampledSpanStorePerSpanNameSummary.getNumbersOfLatencySampledSpans() : null; int subtype = 0; for (LatencyBucketBoundaries latencyBucketsBoundaries : LatencyBucketBoundaries.values()) { if (latencyBucketsSummaries != null) { int numSamples = latencyBucketsSummaries.containsKey(latencyBucketsBoundaries) ? latencyBucketsSummaries.get(latencyBucketsBoundaries) : 0; emitSingleCell(out, formatter, spanName, numSamples, RequestType.FINISHED, subtype++); } else { // numSamples < -1 means "Not Available". emitSingleCell(out, formatter, spanName, -1, RequestType.FINISHED, subtype++); } } // Error based samples. out.write("<td class=\"borderRL\">&nbsp;&nbsp;&nbsp;&nbsp;</td>"); if (sampledSpanStorePerSpanNameSummary != null) { Map<CanonicalCode, Integer> errorBucketsSummaries = sampledSpanStorePerSpanNameSummary.getNumbersOfErrorSampledSpans(); int numErrorSamples = 0; for (Map.Entry<CanonicalCode, Integer> it : errorBucketsSummaries.entrySet()) { numErrorSamples += it.getValue(); } // subtype 0 means all; emitSingleCell(out, formatter, spanName, numErrorSamples, RequestType.FAILED, 0); } else { // numSamples < -1 means "Not Available". emitSingleCell(out, formatter, spanName, -1, RequestType.FAILED, 0); } out.write("</tr>\n"); } out.write("</table>"); }
[ "private", "void", "emitSummaryTable", "(", "PrintWriter", "out", ",", "Formatter", "formatter", ")", "throws", "UnsupportedEncodingException", "{", "if", "(", "runningSpanStore", "==", "null", "||", "sampledSpanStore", "==", "null", ")", "{", "return", ";", "}", "RunningSpanStore", ".", "Summary", "runningSpanStoreSummary", "=", "runningSpanStore", ".", "getSummary", "(", ")", ";", "SampledSpanStore", ".", "Summary", "sampledSpanStoreSummary", "=", "sampledSpanStore", ".", "getSummary", "(", ")", ";", "out", ".", "write", "(", "\"<table style='border-spacing: 0;\\n\"", ")", ";", "out", ".", "write", "(", "\"border-left:1px solid #3D3D3D;border-right:1px solid #3D3D3D;'>\\n\"", ")", ";", "emitSummaryTableHeader", "(", "out", ",", "formatter", ")", ";", "Set", "<", "String", ">", "spanNames", "=", "new", "TreeSet", "<>", "(", "runningSpanStoreSummary", ".", "getPerSpanNameSummary", "(", ")", ".", "keySet", "(", ")", ")", ";", "spanNames", ".", "addAll", "(", "sampledSpanStoreSummary", ".", "getPerSpanNameSummary", "(", ")", ".", "keySet", "(", ")", ")", ";", "boolean", "zebraColor", "=", "true", ";", "for", "(", "String", "spanName", ":", "spanNames", ")", "{", "out", ".", "write", "(", "\"<tr class=\\\"border\\\">\\n\"", ")", ";", "if", "(", "!", "zebraColor", ")", "{", "out", ".", "write", "(", "\"<tr class=\\\"border\\\">\\n\"", ")", ";", "}", "else", "{", "formatter", ".", "format", "(", "\"<tr class=\\\"border\\\" style=\\\"background: %s\\\">%n\"", ",", "ZEBRA_STRIPE_COLOR", ")", ";", "}", "zebraColor", "=", "!", "zebraColor", ";", "formatter", ".", "format", "(", "\"<td>%s</td>%n\"", ",", "htmlEscaper", "(", ")", ".", "escape", "(", "spanName", ")", ")", ";", "// Running", "out", ".", "write", "(", "\"<td class=\\\"borderRL\\\">&nbsp;&nbsp;&nbsp;&nbsp;</td>\"", ")", ";", "RunningSpanStore", ".", "PerSpanNameSummary", "runningSpanStorePerSpanNameSummary", "=", "runningSpanStoreSummary", ".", "getPerSpanNameSummary", "(", ")", ".", "get", "(", "spanName", ")", ";", "// subtype ignored for running requests.", "emitSingleCell", "(", "out", ",", "formatter", ",", "spanName", ",", "runningSpanStorePerSpanNameSummary", "==", "null", "?", "0", ":", "runningSpanStorePerSpanNameSummary", ".", "getNumRunningSpans", "(", ")", ",", "RequestType", ".", "RUNNING", ",", "0", ")", ";", "SampledSpanStore", ".", "PerSpanNameSummary", "sampledSpanStorePerSpanNameSummary", "=", "sampledSpanStoreSummary", ".", "getPerSpanNameSummary", "(", ")", ".", "get", "(", "spanName", ")", ";", "// Latency based samples", "out", ".", "write", "(", "\"<td class=\\\"borderLC\\\">&nbsp;&nbsp;&nbsp;&nbsp;</td>\"", ")", ";", "Map", "<", "LatencyBucketBoundaries", ",", "Integer", ">", "latencyBucketsSummaries", "=", "sampledSpanStorePerSpanNameSummary", "!=", "null", "?", "sampledSpanStorePerSpanNameSummary", ".", "getNumbersOfLatencySampledSpans", "(", ")", ":", "null", ";", "int", "subtype", "=", "0", ";", "for", "(", "LatencyBucketBoundaries", "latencyBucketsBoundaries", ":", "LatencyBucketBoundaries", ".", "values", "(", ")", ")", "{", "if", "(", "latencyBucketsSummaries", "!=", "null", ")", "{", "int", "numSamples", "=", "latencyBucketsSummaries", ".", "containsKey", "(", "latencyBucketsBoundaries", ")", "?", "latencyBucketsSummaries", ".", "get", "(", "latencyBucketsBoundaries", ")", ":", "0", ";", "emitSingleCell", "(", "out", ",", "formatter", ",", "spanName", ",", "numSamples", ",", "RequestType", ".", "FINISHED", ",", "subtype", "++", ")", ";", "}", "else", "{", "// numSamples < -1 means \"Not Available\".", "emitSingleCell", "(", "out", ",", "formatter", ",", "spanName", ",", "-", "1", ",", "RequestType", ".", "FINISHED", ",", "subtype", "++", ")", ";", "}", "}", "// Error based samples.", "out", ".", "write", "(", "\"<td class=\\\"borderRL\\\">&nbsp;&nbsp;&nbsp;&nbsp;</td>\"", ")", ";", "if", "(", "sampledSpanStorePerSpanNameSummary", "!=", "null", ")", "{", "Map", "<", "CanonicalCode", ",", "Integer", ">", "errorBucketsSummaries", "=", "sampledSpanStorePerSpanNameSummary", ".", "getNumbersOfErrorSampledSpans", "(", ")", ";", "int", "numErrorSamples", "=", "0", ";", "for", "(", "Map", ".", "Entry", "<", "CanonicalCode", ",", "Integer", ">", "it", ":", "errorBucketsSummaries", ".", "entrySet", "(", ")", ")", "{", "numErrorSamples", "+=", "it", ".", "getValue", "(", ")", ";", "}", "// subtype 0 means all;", "emitSingleCell", "(", "out", ",", "formatter", ",", "spanName", ",", "numErrorSamples", ",", "RequestType", ".", "FAILED", ",", "0", ")", ";", "}", "else", "{", "// numSamples < -1 means \"Not Available\".", "emitSingleCell", "(", "out", ",", "formatter", ",", "spanName", ",", "-", "1", ",", "RequestType", ".", "FAILED", ",", "0", ")", ";", "}", "out", ".", "write", "(", "\"</tr>\\n\"", ")", ";", "}", "out", ".", "write", "(", "\"</table>\"", ")", ";", "}" ]
Emits the summary table with links to all samples.
[ "Emits", "the", "summary", "table", "with", "links", "to", "all", "samples", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/contrib/zpages/src/main/java/io/opencensus/contrib/zpages/TracezZPageHandler.java#L416-L499
train
census-instrumentation/opencensus-java
impl_core/src/main/java/io/opencensus/implcore/internal/VarInt.java
VarInt.getVarInt
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; }
java
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; }
[ "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. @param src source buffer to retrieve from @param offset offset within src @param dst the resulting int value @return the updated offset after reading the varint
[ "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", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/impl_core/src/main/java/io/opencensus/implcore/internal/VarInt.java#L61-L77
train
census-instrumentation/opencensus-java
impl_core/src/main/java/io/opencensus/implcore/internal/VarInt.java
VarInt.getVarInt
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; }
java
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; }
[ "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. <p>The position of the buffer is advanced to the first byte after the decoded varint. @param src the ByteBuffer to get the var int from @return The integer value of the decoded varint
[ "Reads", "a", "varint", "from", "the", "current", "position", "of", "the", "given", "ByteBuffer", "and", "returns", "the", "decoded", "value", "as", "32", "bit", "integer", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/impl_core/src/main/java/io/opencensus/implcore/internal/VarInt.java#L108-L137
train
census-instrumentation/opencensus-java
impl_core/src/main/java/io/opencensus/implcore/internal/VarInt.java
VarInt.putVarInt
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)); } }
java
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)); } }
[ "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. @param v the value to encode @param sink the ByteBuffer to add the encoded value
[ "Encodes", "an", "integer", "in", "a", "variable", "-", "length", "encoding", "7", "bits", "per", "byte", "to", "a", "ByteBuffer", "sink", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/impl_core/src/main/java/io/opencensus/implcore/internal/VarInt.java#L145-L155
train
census-instrumentation/opencensus-java
impl_core/src/main/java/io/opencensus/implcore/internal/VarInt.java
VarInt.getVarInt
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; }
java
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; }
[ "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. @param inputStream the InputStream to read from
[ "Reads", "a", "varint", "from", "the", "given", "InputStream", "and", "returns", "the", "decoded", "value", "as", "an", "int", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/impl_core/src/main/java/io/opencensus/implcore/internal/VarInt.java#L162-L177
train
census-instrumentation/opencensus-java
impl_core/src/main/java/io/opencensus/implcore/internal/VarInt.java
VarInt.putVarInt
public static void putVarInt(int v, OutputStream outputStream) throws IOException { byte[] bytes = new byte[varIntSize(v)]; putVarInt(v, bytes, 0); outputStream.write(bytes); }
java
public static void putVarInt(int v, OutputStream outputStream) throws IOException { byte[] bytes = new byte[varIntSize(v)]; putVarInt(v, bytes, 0); outputStream.write(bytes); }
[ "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. @param v the value to encode @param outputStream the OutputStream to write to
[ "Encodes", "an", "integer", "in", "a", "variable", "-", "length", "encoding", "7", "bits", "per", "byte", "and", "writes", "it", "to", "the", "given", "OutputStream", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/impl_core/src/main/java/io/opencensus/implcore/internal/VarInt.java#L186-L190
train
census-instrumentation/opencensus-java
impl_core/src/main/java/io/opencensus/implcore/internal/VarInt.java
VarInt.getVarLong
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; }
java
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; }
[ "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. <p>The position of the buffer is advanced to the first byte after the decoded varint. @param src the ByteBuffer to get the var int from @return The integer value of the decoded long varint
[ "Reads", "an", "up", "to", "64", "bit", "long", "varint", "from", "the", "current", "position", "of", "the", "given", "ByteBuffer", "and", "returns", "the", "decoded", "value", "as", "long", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/impl_core/src/main/java/io/opencensus/implcore/internal/VarInt.java#L216-L264
train
census-instrumentation/opencensus-java
impl_core/src/main/java/io/opencensus/implcore/internal/VarInt.java
VarInt.putVarLong
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)); } }
java
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)); } }
[ "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. @param v the value to encode @param sink the ByteBuffer to add the encoded value
[ "Encodes", "a", "long", "integer", "in", "a", "variable", "-", "length", "encoding", "7", "bits", "per", "byte", "to", "a", "ByteBuffer", "sink", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/impl_core/src/main/java/io/opencensus/implcore/internal/VarInt.java#L272-L282
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/BasicOperationsBenchmark.java
BasicOperationsBenchmark.createRootSpan
@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; }
java
@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; }
[ "@", "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.
[ "Create", "a", "root", "span", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/BasicOperationsBenchmark.java#L132-L144
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/BasicOperationsBenchmark.java
BasicOperationsBenchmark.createLink
@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); }
java
@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); }
[ "@", "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.
[ "Create", "a", "link", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/BasicOperationsBenchmark.java#L192-L203
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/BasicOperationsBenchmark.java
BasicOperationsBenchmark.createMessageEvent
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public MessageEvent createMessageEvent(Data data) { return MessageEvent.builder(MessageEvent.Type.SENT, MESSAGE_ID).build(); }
java
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public MessageEvent createMessageEvent(Data data) { return MessageEvent.builder(MessageEvent.Type.SENT, MESSAGE_ID).build(); }
[ "@", "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.
[ "Create", "a", "message", "event", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/BasicOperationsBenchmark.java#L206-L211
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/BasicOperationsBenchmark.java
BasicOperationsBenchmark.getCurrentSpan
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Span getCurrentSpan(Data data) { return data.tracer.getCurrentSpan(); }
java
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Span getCurrentSpan(Data data) { return data.tracer.getCurrentSpan(); }
[ "@", "Benchmark", "@", "BenchmarkMode", "(", "Mode", ".", "AverageTime", ")", "@", "OutputTimeUnit", "(", "TimeUnit", ".", "NANOSECONDS", ")", "public", "Span", "getCurrentSpan", "(", "Data", "data", ")", "{", "return", "data", ".", "tracer", ".", "getCurrentSpan", "(", ")", ";", "}" ]
Get current trace span.
[ "Get", "current", "trace", "span", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/BasicOperationsBenchmark.java#L224-L229
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/BasicOperationsBenchmark.java
BasicOperationsBenchmark.encodeSpanBinary
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public byte[] encodeSpanBinary(Data data) { return data.propagation.getBinaryFormat().toByteArray(data.spanToEncode.getContext()); }
java
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public byte[] encodeSpanBinary(Data data) { return data.propagation.getBinaryFormat().toByteArray(data.spanToEncode.getContext()); }
[ "@", "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.
[ "Encode", "a", "span", "using", "binary", "format", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/BasicOperationsBenchmark.java#L232-L237
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/BasicOperationsBenchmark.java
BasicOperationsBenchmark.decodeSpanBinary
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public SpanContext decodeSpanBinary(Data data) throws SpanContextParseException { return data.propagation.getBinaryFormat().fromByteArray(data.spanToDecodeBinary); }
java
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public SpanContext decodeSpanBinary(Data data) throws SpanContextParseException { return data.propagation.getBinaryFormat().fromByteArray(data.spanToDecodeBinary); }
[ "@", "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.
[ "Decode", "a", "span", "using", "binary", "format", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/BasicOperationsBenchmark.java#L240-L245
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/BasicOperationsBenchmark.java
BasicOperationsBenchmark.encodeSpanText
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public String encodeSpanText(Data data) { return encodeSpanContextText( data.propagation.getTraceContextFormat(), data.spanToEncode.getContext()); }
java
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public String encodeSpanText(Data data) { return encodeSpanContextText( data.propagation.getTraceContextFormat(), data.spanToEncode.getContext()); }
[ "@", "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.
[ "Encode", "a", "span", "using", "text", "format", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/BasicOperationsBenchmark.java#L248-L254
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/BasicOperationsBenchmark.java
BasicOperationsBenchmark.decodeSpanText
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public SpanContext decodeSpanText(Data data) throws SpanContextParseException { return data.propagation.getTraceContextFormat().extract(data.spanToDecodeText, textGetter); }
java
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public SpanContext decodeSpanText(Data data) throws SpanContextParseException { return data.propagation.getTraceContextFormat().extract(data.spanToDecodeText, textGetter); }
[ "@", "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.
[ "Decode", "a", "span", "using", "text", "format", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/BasicOperationsBenchmark.java#L257-L262
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/BasicOperationsBenchmark.java
BasicOperationsBenchmark.setStatus
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Span setStatus(Data data) { data.spanToSet.setStatus(STATUS_OK); return data.spanToSet; }
java
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Span setStatus(Data data) { data.spanToSet.setStatus(STATUS_OK); return data.spanToSet; }
[ "@", "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.
[ "Set", "status", "on", "a", "span", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/BasicOperationsBenchmark.java#L265-L271
train
census-instrumentation/opencensus-java
benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/BasicOperationsBenchmark.java
BasicOperationsBenchmark.endSpan
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Span endSpan(Data data) { data.spanToEnd.end(); return data.spanToEnd; }
java
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Span endSpan(Data data) { data.spanToEnd.end(); return data.spanToEnd; }
[ "@", "Benchmark", "@", "BenchmarkMode", "(", "Mode", ".", "AverageTime", ")", "@", "OutputTimeUnit", "(", "TimeUnit", ".", "NANOSECONDS", ")", "public", "Span", "endSpan", "(", "Data", "data", ")", "{", "data", ".", "spanToEnd", ".", "end", "(", ")", ";", "return", "data", ".", "spanToEnd", ";", "}" ]
End a span.
[ "End", "a", "span", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/benchmarks/src/jmh/java/io/opencensus/benchmarks/trace/BasicOperationsBenchmark.java#L274-L280
train
census-instrumentation/opencensus-java
exporters/trace/stackdriver/src/main/java/io/opencensus/exporter/trace/stackdriver/StackdriverExporter.java
StackdriverExporter.createAndRegisterWithCredentialsAndProjectId
public static void createAndRegisterWithCredentialsAndProjectId( Credentials credentials, String projectId) throws IOException { StackdriverTraceExporter.createAndRegister( StackdriverTraceConfiguration.builder() .setCredentials(credentials) .setProjectId(projectId) .build()); }
java
public static void createAndRegisterWithCredentialsAndProjectId( Credentials credentials, String projectId) throws IOException { StackdriverTraceExporter.createAndRegister( StackdriverTraceConfiguration.builder() .setCredentials(credentials) .setProjectId(projectId) .build()); }
[ "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. @param credentials a credentials used to authenticate API calls. @param projectId the cloud project id. @throws IllegalStateException if a Stackdriver exporter is already registered. @since 0.6
[ "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", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/trace/stackdriver/src/main/java/io/opencensus/exporter/trace/stackdriver/StackdriverExporter.java#L55-L62
train
census-instrumentation/opencensus-java
exporters/trace/stackdriver/src/main/java/io/opencensus/exporter/trace/stackdriver/StackdriverExporter.java
StackdriverExporter.createAndRegisterWithProjectId
public static void createAndRegisterWithProjectId(String projectId) throws IOException { StackdriverTraceExporter.createAndRegister( StackdriverTraceConfiguration.builder() .setCredentials(GoogleCredentials.getApplicationDefault()) .setProjectId(projectId) .build()); }
java
public static void createAndRegisterWithProjectId(String projectId) throws IOException { StackdriverTraceExporter.createAndRegister( StackdriverTraceConfiguration.builder() .setCredentials(GoogleCredentials.getApplicationDefault()) .setProjectId(projectId) .build()); }
[ "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. <p>This uses the default application credentials see {@link GoogleCredentials#getApplicationDefault}. <p>This is equivalent with: <pre>{@code StackdriverExporter.createAndRegisterWithCredentialsAndProjectId( GoogleCredentials.getApplicationDefault(), projectId); }</pre> @param projectId the cloud project id. @throws IllegalStateException if a Stackdriver exporter is already registered. @since 0.6
[ "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", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/trace/stackdriver/src/main/java/io/opencensus/exporter/trace/stackdriver/StackdriverExporter.java#L82-L88
train
census-instrumentation/opencensus-java
exporters/stats/signalfx/src/main/java/io/opencensus/exporter/stats/signalfx/SignalFxSessionAdaptor.java
SignalFxSessionAdaptor.adapt
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; }
java
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; }
[ "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. @param metric The {@link Metric} containing the timeseries of each combination of label values. @return A list of datapoints for the corresponding metric timeseries of this metric.
[ "Converts", "the", "given", "Metric", "into", "datapoints", "that", "can", "be", "sent", "to", "SignalFx", "." ]
deefac9bed77e40a2297bff1ca5ec5aa48a5f755
https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/exporters/stats/signalfx/src/main/java/io/opencensus/exporter/stats/signalfx/SignalFxSessionAdaptor.java#L98-L122
train
jenkinsci/email-ext-plugin
src/main/java/hudson/plugins/emailext/ExtendedEmailPublisherDescriptor.java
ExtendedEmailPublisherDescriptor.setSmtpAuth
@SuppressWarnings("unused") public void setSmtpAuth(String userName, String password) { setSmtpUsername(userName); setSmtpPassword(password); }
java
@SuppressWarnings("unused") public void setSmtpAuth(String userName, String password) { setSmtpUsername(userName); setSmtpPassword(password); }
[ "@", "SuppressWarnings", "(", "\"unused\"", ")", "public", "void", "setSmtpAuth", "(", "String", "userName", ",", "String", "password", ")", "{", "setSmtpUsername", "(", "userName", ")", ";", "setSmtpPassword", "(", "password", ")", ";", "}" ]
Make API match Mailer plugin
[ "Make", "API", "match", "Mailer", "plugin" ]
21fbd402665848a18205b26751424149e51e86e4
https://github.com/jenkinsci/email-ext-plugin/blob/21fbd402665848a18205b26751424149e51e86e4/src/main/java/hudson/plugins/emailext/ExtendedEmailPublisherDescriptor.java#L345-L349
train
jenkinsci/email-ext-plugin
src/main/java/hudson/plugins/emailext/plugins/trigger/AbstractScriptTrigger.java
AbstractScriptTrigger.readResolve
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; }
java
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; }
[ "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. @return {@code this}, or a replacement for {@code this}. @throws ObjectStreamException if the object cannot be restored. @see <a href="http://download.oracle.com/javase/1.3/docs/guide/serialization/spec/input.doc6.html">The Java Object Serialization Specification</a>
[ "Called", "when", "object", "has", "been", "deserialized", "from", "a", "stream", "." ]
21fbd402665848a18205b26751424149e51e86e4
https://github.com/jenkinsci/email-ext-plugin/blob/21fbd402665848a18205b26751424149e51e86e4/src/main/java/hudson/plugins/emailext/plugins/trigger/AbstractScriptTrigger.java#L176-L183
train
jenkinsci/email-ext-plugin
src/main/java/hudson/plugins/emailext/plugins/content/ScriptContent.java
ScriptContent.renderTemplate
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; }
java
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; }
[ "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 @param build the build to act on @param templateStream the template file stream @return the rendered template content @throws IOException
[ "Renders", "the", "template", "using", "a", "SimpleTemplateEngine" ]
21fbd402665848a18205b26751424149e51e86e4
https://github.com/jenkinsci/email-ext-plugin/blob/21fbd402665848a18205b26751424149e51e86e4/src/main/java/hudson/plugins/emailext/plugins/content/ScriptContent.java#L114-L176
train
jenkinsci/email-ext-plugin
src/main/java/hudson/plugins/emailext/plugins/content/ScriptContent.java
ScriptContent.executeScript
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; }
java
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; }
[ "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 @param build the build to act on @param scriptStream the script input stream @return a String containing the toString of the last item in the script @throws IOException
[ "Executes", "a", "script", "and", "returns", "the", "last", "value", "as", "a", "String" ]
21fbd402665848a18205b26751424149e51e86e4
https://github.com/jenkinsci/email-ext-plugin/blob/21fbd402665848a18205b26751424149e51e86e4/src/main/java/hudson/plugins/emailext/plugins/content/ScriptContent.java#L186-L233
train
jenkinsci/email-ext-plugin
src/main/java/hudson/plugins/emailext/plugins/recipients/UpstreamComitterRecipientProvider.java
UpstreamComitterRecipientProvider.addUpstreamCommittersTriggeringBuild
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); } } } }
java
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); } } } }
[ "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. @param build the upstream build @param to the to recipient list @param cc the cc recipient list @param bcc the bcc recipient list @param env @param listener
[ "Adds", "for", "the", "given", "upstream", "build", "the", "committers", "to", "the", "recipient", "list", "for", "each", "commit", "in", "the", "upstream", "build", "." ]
21fbd402665848a18205b26751424149e51e86e4
https://github.com/jenkinsci/email-ext-plugin/blob/21fbd402665848a18205b26751424149e51e86e4/src/main/java/hudson/plugins/emailext/plugins/recipients/UpstreamComitterRecipientProvider.java#L77-L101
train
jenkinsci/email-ext-plugin
src/main/java/hudson/plugins/emailext/plugins/recipients/UpstreamComitterRecipientProvider.java
UpstreamComitterRecipientProvider.addUserFromChangeSet
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); }
java
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); }
[ "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 @param change The ChangeLogSet.Entry to get the user information from @param to The list of to addresses to add to @param cc The list of cc addresses to add to @param bcc The list of bcc addresses to add to @param env The build environment @param listener The listener for logging
[ "Adds", "a", "user", "to", "the", "recipients", "list", "based", "on", "a", "specific", "SCM", "change", "set" ]
21fbd402665848a18205b26751424149e51e86e4
https://github.com/jenkinsci/email-ext-plugin/blob/21fbd402665848a18205b26751424149e51e86e4/src/main/java/hudson/plugins/emailext/plugins/recipients/UpstreamComitterRecipientProvider.java#L112-L115
train
jenkinsci/email-ext-plugin
src/main/java/hudson/plugins/emailext/plugins/CssInliner.java
CssInliner.fetchStyles
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(); }
java
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(); }
[ "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 @param doc the html document @return a string representing the stylesheet.
[ "Generates", "a", "stylesheet", "from", "an", "html", "document" ]
21fbd402665848a18205b26751424149e51e86e4
https://github.com/jenkinsci/email-ext-plugin/blob/21fbd402665848a18205b26751424149e51e86e4/src/main/java/hudson/plugins/emailext/plugins/CssInliner.java#L63-L73
train
jenkinsci/email-ext-plugin
src/main/java/hudson/plugins/emailext/plugins/CssInliner.java
CssInliner.process
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()); }
java
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()); }
[ "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. @param input the html document @return the processed html document
[ "Takes", "an", "input", "string", "representing", "an", "html", "document", "and", "processes", "it", "with", "the", "Css", "Inliner", "." ]
21fbd402665848a18205b26751424149e51e86e4
https://github.com/jenkinsci/email-ext-plugin/blob/21fbd402665848a18205b26751424149e51e86e4/src/main/java/hudson/plugins/emailext/plugins/CssInliner.java#L86-L101
train
jenkinsci/email-ext-plugin
src/main/java/hudson/plugins/emailext/Util.java
Util.unescapeString
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(); }
java
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(); }
[ "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. @param escapedString the string containing escapes @return the string with all the escape sequences replaced
[ "Replaces", "all", "the", "printf", "-", "style", "escape", "sequences", "in", "a", "string", "with", "the", "appropriate", "characters", "." ]
21fbd402665848a18205b26751424149e51e86e4
https://github.com/jenkinsci/email-ext-plugin/blob/21fbd402665848a18205b26751424149e51e86e4/src/main/java/hudson/plugins/emailext/Util.java#L22-L34
train
jenkinsci/email-ext-plugin
src/main/java/hudson/plugins/emailext/Util.java
Util.printf
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); } } }
java
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); } } }
[ "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. @param buf the buffer to append the result to @param formatString the string to format @param printfSpec the specialization for printf
[ "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", "." ]
21fbd402665848a18205b26751424149e51e86e4
https://github.com/jenkinsci/email-ext-plugin/blob/21fbd402665848a18205b26751424149e51e86e4/src/main/java/hudson/plugins/emailext/Util.java#L82-L104
train
jenkinsci/email-ext-plugin
src/main/java/hudson/plugins/emailext/ExtendedEmailPublisher.java
ExtendedEmailPublisher.expandClasspath
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; } }
java
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; } }
[ "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. @param context the current email context @param loader the class loader to expand @return the new expanded classloader
[ "Expand", "the", "plugin", "class", "loader", "with", "URL", "taken", "from", "the", "project", "descriptor", "and", "the", "global", "configuration", "." ]
21fbd402665848a18205b26751424149e51e86e4
https://github.com/jenkinsci/email-ext-plugin/blob/21fbd402665848a18205b26751424149e51e86e4/src/main/java/hudson/plugins/emailext/ExtendedEmailPublisher.java#L661-L689
train
jenkinsci/email-ext-plugin
src/main/java/hudson/plugins/emailext/plugins/EmailTrigger.java
EmailTrigger.getNumFailures
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(); }
java
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(); }
[ "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. @param build The project run to get the number of test failures for. @return The number of test failures for the Run
[ "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", "." ]
21fbd402665848a18205b26751424149e51e86e4
https://github.com/jenkinsci/email-ext-plugin/blob/21fbd402665848a18205b26751424149e51e86e4/src/main/java/hudson/plugins/emailext/plugins/EmailTrigger.java#L154-L177
train
jenkinsci/email-ext-plugin
src/main/java/hudson/plugins/emailext/plugins/trigger/FixedUnhealthyTrigger.java
FixedUnhealthyTrigger.getPreviousRun
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; }
java
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; }
[ "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.
[ "Find", "most", "recent", "previous", "build", "matching", "certain", "criteria", "." ]
21fbd402665848a18205b26751424149e51e86e4
https://github.com/jenkinsci/email-ext-plugin/blob/21fbd402665848a18205b26751424149e51e86e4/src/main/java/hudson/plugins/emailext/plugins/trigger/FixedUnhealthyTrigger.java#L50-L60
train
alibaba/java-dns-cache-manipulator
library/src/main/java/com/alibaba/dcm/DnsCacheManipulator.java
DnsCacheManipulator.setDnsCache
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); } }
java
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); } }
[ "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. @param expireMillis expire time in milliseconds. @param host host @param ips ips @throws DnsCacheManipulatorException Operation fail
[ "Set", "a", "dns", "cache", "entry", "." ]
eab50ee5c27671f9159b55458301f9429b2fcc47
https://github.com/alibaba/java-dns-cache-manipulator/blob/eab50ee5c27671f9159b55458301f9429b2fcc47/library/src/main/java/com/alibaba/dcm/DnsCacheManipulator.java#L53-L61
train