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.
993
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;
  }
806325
def metric(self, measurement_name, values, tags=None, timestamp=None):
        
        if not measurement_name or values in (None, {}):
            # Don't try to send empty data
            return

        tags = tags or {}

        # Do a shallow merge of the metric tags and global tags
        all_tags = dict(self.tags, **tags)

        # Create a metric line from the input and then send it to socket
        line = Line(measurement_name, values, all_tags, timestamp)
        self.send(line.to_line_protocol())
1092141
public TopologyMaster.MetricResponse getMetrics(TopologyMaster.MetricRequest request) {
    String componentName = request.getComponentName();
    if (!cache.componentInstanceExists(componentName, null)) {
      return buildResponseNotOk(
          String.format("Unknown component %s found in MetricRequest %s", componentName, request)
      ).build();
    }
    if (request.getInstanceIdCount() > 0) {
      for (String instanceId : request.getInstanceIdList()) {
        if (!cache.componentInstanceExists(componentName, instanceId)) {
          return buildResponseNotOk(
              String.format("Unknown instance %s found in MetricRequest %s", instanceId, request)
          ).build();
        }
      }
    }
    if (!request.hasInterval() && !request.hasExplicitInterval()) {
      return buildResponseNotOk("No purgeIntervalSec or explicit purgeIntervalSec set").build();
    }

    MetricRequest request1 = MetricsCacheQueryUtils.fromProtobuf(request);
    MetricResponse response1 = cache.getMetrics(request1, metricNameType);
    TopologyMaster.MetricResponse response = MetricsCacheQueryUtils.toProtobuf(response1, request1);
    return response;
  }
954596
public Metric getMetricAsync(String metricName) throws ExecutionException, InterruptedException {
    // [START getMetricAsync]
    Future<Metric> future = logging.getMetricAsync(metricName);
    // ...
    Metric metric = future.get();
    if (metric == null) {
      // metric was not found
    }
    // [END getMetricAsync]
    return metric;
  }
1157229
public IncludeExcludePatterns metricToPatterns(String metric) {
    IncludeExcludePatterns foundPatterns = metricNameToPatterns.get(metric);
    if (foundPatterns != null) {
        return foundPatterns;
    }

    // Since the keys in the prototype can be regular expressions,
    // need to look at all of them and can potentially match multiple,
    // each having a different set of rules.
    foundPatterns = new IncludeExcludePatterns();
    for (MeterFilterPattern meterPattern : includePatterns) {
      if (meterPattern.namePattern.matcher(metric).matches()) {
        foundPatterns.include.addAll(meterPattern.values);
      }
    }
    for (MeterFilterPattern meterPattern : excludePatterns) {
      if (meterPattern.namePattern.matcher(metric).matches()) {
        foundPatterns.exclude.addAll(meterPattern.values);
      }
    }
    metricNameToPatterns.put(metric, foundPatterns);
    return foundPatterns;
  }
778579
public boolean createOrReplaceMetric(Metric metric) {
        String metricName = metric.getName();
        checkMetricIsEmpty(metricName);
        QueryPart<Metric> queryPart = new Query<Metric>("metrics")
                .path(metricName, true);
        return httpClientManager.updateMetaData(queryPart, put(metric));
    }
654993
public function getMetrics(Metric $metric)
    {
        $type = Binput::get('filter', AutoPresenter::decorate($metric)->view_name);
        $metrics = app(MetricRepository::class);

        switch ($type) {
            case 'last_hour': $metricData = $metrics->listPointsLastHour($metric); break;
            case 'today': $metricData = $metrics->listPointsToday($metric); break;
            case 'week': $metricData = $metrics->listPointsForWeek($metric); break;
            case 'month': $metricData = $metrics->listPointsForMonth($metric); break;
            default: $metricData = [];
        }

        return $this->item([
            'metric' => $metric->toArray(),
            'items'  => $metricData,
        ]);
    }
768032
@Override
    public List<Metric> transform(QueryContext context, List<Metric> metrics) {
        if (metrics == null) {
            throw new MissingDataException("The metrics list cannot be null or empty while performing arithmetic transformations.");
        }
        if (metrics.isEmpty()) {
            return metrics;
        }

        Metric result = new Metric(getResultScopeName(), RESULT_METRIC_NAME);
        Map<Long, Double> resultDatapoints = new HashMap<>();
        Iterator<Entry<Long, Double>> it = metrics.get(0).getDatapoints().entrySet().iterator();

        while (it.hasNext()) {
            Entry<Long, Double> entry = it.next();
            List<Double> operands = null;

            try {
                operands = getOperands(entry.getKey(), metrics);
            } catch (MissingDataException mde) {
                continue;
            }
            resultDatapoints.put(entry.getKey(), performOperation(operands));
        }
        result.setDatapoints(resultDatapoints);
        MetricDistiller.setCommonAttributes(metrics, result);

        List<Metric> resultMetrics = new ArrayList<>();

        Collections.addAll(resultMetrics, result);
        return resultMetrics;
    }
1202442
public List<Metric> getAverages(int span) {
        Map<String,Metric> accum = new LinkedHashMap<>();
        int count = span / period;
        if (count > dataList.size())
            count = dataList.size();
        for (int i = dataList.size() - count; i < dataList.size(); i++) {
            MetricData metricData = dataList.get(i);
            for (Metric metric : metricData.getMetrics()) {
                Metric total = accum.get(metric.getName());
                if (total == null) {
                    total = new Metric(metric.getId(), metric.getName(), metric.getValue());
                    accum.put(metric.getName(), total);
                }
                else {
                    total.setValue(total.getValue() + metric.getValue());
                }
            }
        }
        for (Metric metric : accum.values()) {
            metric.setValue(Math.round((double)metric.getValue() / count));
        }
        return new ArrayList<>(accum.values());
    }
436979
@SuppressWarnings("rawtypes")
  @Nullable
  private Metric collectGauge(String dropwizardName, Gauge gauge) {
    String metricName = DropWizardUtils.generateFullMetricName(dropwizardName, "gauge");
    String metricDescription = DropWizardUtils.generateFullMetricDescription(dropwizardName, gauge);

    // Figure out which gauge instance and call the right method to get value
    Type type;
    Value value;

    Object obj = gauge.getValue();
    if (obj instanceof Number) {
      type = Type.GAUGE_DOUBLE;
      value = Value.doubleValue(((Number) obj).doubleValue());
    } else if (obj instanceof Boolean) {
      type = Type.GAUGE_INT64;
      value = Value.longValue(((Boolean) obj) ? 1 : 0);
    } else {
      // Ignoring Gauge (gauge.getKey()) with unhandled type.
      return null;
    }

    MetricDescriptor metricDescriptor =
        MetricDescriptor.create(
            metricName, metricDescription, DEFAULT_UNIT, type, Collections.<LabelKey>emptyList());
    TimeSeries timeSeries =
        TimeSeries.createWithOnePoint(
            Collections.<LabelValue>emptyList(), Point.create(value, clock.now()), null);
    return Metric.createWithOneTimeSeries(metricDescriptor, timeSeries);
  }
402003
private Metric collectMeter(MetricName dropwizardMetric, Meter meter) {
    String metricName = DropWizardUtils.generateFullMetricName(dropwizardMetric.getKey(), "meter");
    String metricDescription =
        DropWizardUtils.generateFullMetricDescription(dropwizardMetric.getKey(), meter);
    final AbstractMap.SimpleImmutableEntry<List<LabelKey>, List<LabelValue>> labels =
        DropWizardUtils.generateLabels(dropwizardMetric);

    MetricDescriptor metricDescriptor =
        MetricDescriptor.create(
            metricName, metricDescription, DEFAULT_UNIT, Type.CUMULATIVE_INT64, labels.getKey());
    TimeSeries timeSeries =
        TimeSeries.createWithOnePoint(
            labels.getValue(),
            Point.create(Value.longValue(meter.getCount()), clock.now()),
            cumulativeStartTimestamp);

    return Metric.createWithOneTimeSeries(metricDescriptor, timeSeries);
  }
605767
public void readAndExport(MetricExporter metricExporter) {
    Span span =
        tracer
            .spanBuilder(spanName)
            .setRecordEvents(true)
            .setSampler(probabilitySampler)
            .startSpan();
    Scope scope = tracer.withSpan(span);
    try {
      ArrayList<Metric> metricsList = new ArrayList<>();
      for (MetricProducer metricProducer : metricProducerManager.getAllMetricProducer()) {
        metricsList.addAll(metricProducer.getMetrics());
      }
      metricExporter.export(metricsList);
    } catch (Throwable e) {
      logger.log(Level.WARNING, "Exception thrown by the metrics exporter.", e);
      span.setStatus(
          Status.UNKNOWN.withDescription("Exception when export metrics: " + exceptionMessage(e)));
    } finally {
      scope.close();
      span.end();
    }
  }
472152
public void setMetricData(java.util.Collection<MetricDatapoint> metricData) {
        if (metricData == null) {
            this.metricData = null;
            return;
        }

        this.metricData = new java.util.ArrayList<MetricDatapoint>(metricData);
    }
284607
public void addMetric(final IMetric<?> metric) {
    // metric null or already present
    if (metric == null) {
      throw new IllegalArgumentException("Cannot add a null metric");
    }

    if (getMetricFromName(metric.getName()) == null) {
      logger.debug(String.format("Adding %s metric in Metric Manager", metric.getName()));
      this.metrics.add(metric);
      metric.updateMetricManager(this);
    } else {
      logger.error("Failed to add metric");
    }
  }
215863
private Iterable<PutMetricDataRequest> toPutMetricDataRequests(Map<String, MetricDatum> uniqueMetrics) {
        // Opportunistically generates some machine metrics whenever there
        // is metrics consolidation
        for (MetricDatum datum: machineMetricFactory.generateMetrics()) {
            summarize(datum, uniqueMetrics);
        }
        List<PutMetricDataRequest> list = new ArrayList<PutMetricDataRequest>();
        List<MetricDatum> data = new ArrayList<MetricDatum>();
        for (MetricDatum m: uniqueMetrics.values()) {
            data.add(m);
            if (data.size() == CloudWatchMetricConfig.MAX_METRICS_DATUM_SIZE) {
                list.addAll(newPutMetricDataRequests(data));
                data.clear();
            }
        }

        if (data.size() > 0) {
            list.addAll(newPutMetricDataRequests(data));
        }
        return list;
    }
1194966
public static MetricDto transformToDto(Metric metric) {
        if (metric == null) {
            throw new WebApplicationException("Null entity object cannot be converted to Dto object.", Status.INTERNAL_SERVER_ERROR);
        }

        MetricDto result = createDtoObject(MetricDto.class, metric);

        return result;
    }
1343148
@POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/metrics")
    @Description("Submits externally collected metric data.")
    public Map<String, Object> submitMetrics(@Context HttpServletRequest req, final List<MetricDto> metricDtos) {
        PrincipalUser remoteUser = getRemoteUser(req);

        SystemAssert.requireArgument(metricDtos != null, "Cannot submit null timeseries metrics list.");

        List<Metric> legalMetrics = new ArrayList<>();
        List<MetricDto> illegalMetrics = new ArrayList<>();
        List<String> errorMessages = new ArrayList<>();

        for (MetricDto metricDto : metricDtos) {
            try {
                Metric metric = new Metric(metricDto.getScope(), metricDto.getMetric());
                metric.setTags(metricDto.getTags());
                if (metricDto.getMetatags() != null) {
                    metric.setMetatagsRecord(new MetatagsRecord(metricDto.getMetatags(), metricDto.getMetatagsKey()));
                }

                copyProperties(metric, metricDto);
                legalMetrics.add(metric);
            } catch (Exception e) {
                illegalMetrics.add(metricDto);
                errorMessages.add(e.getMessage());
            }
        }
        _collectionService.submitMetrics(remoteUser, legalMetrics);

        Map<String, Object> result = new HashMap<>();

        result.put("Success", legalMetrics.size() + " metrics");
        result.put("Error", illegalMetrics.size() + " metrics");
        result.put("Error Messages", errorMessages);
        return result;
    }