use of com.google.bigtable.repackaged.com.google.monitoring.v3.TimeSeries in project instrumentation-java by census-instrumentation.
the class StackdriverExportUtilsTest method createTimeSeriesList_Cumulative.
@Test
public void createTimeSeriesList_Cumulative() {
List<TimeSeries> timeSeriesList = StackdriverExportUtils.createTimeSeriesList(METRIC, DEFAULT_RESOURCE, CUSTOM_OPENCENSUS_DOMAIN, PROJECT_ID, DEFAULT_CONSTANT_LABELS);
assertThat(timeSeriesList).hasSize(1);
TimeSeries expectedTimeSeries = TimeSeries.newBuilder().setMetricKind(MetricKind.CUMULATIVE).setValueType(MetricDescriptor.ValueType.DOUBLE).setMetric(StackdriverExportUtils.createMetric(METRIC_DESCRIPTOR, LABEL_VALUE, CUSTOM_OPENCENSUS_DOMAIN, DEFAULT_CONSTANT_LABELS)).setResource(MonitoredResource.newBuilder().setType("global")).addPoints(StackdriverExportUtils.createPoint(POINT, TIMESTAMP_2)).build();
assertThat(timeSeriesList).containsExactly(expectedTimeSeries);
}
use of com.google.bigtable.repackaged.com.google.monitoring.v3.TimeSeries in project instrumentation-java by census-instrumentation.
the class StackdriverExportUtilsTest method createTimeSeriesList_withCustomMonitoredResource.
@Test
public void createTimeSeriesList_withCustomMonitoredResource() {
MonitoredResource resource = MonitoredResource.newBuilder().setType("global").putLabels("key", "value").build();
List<TimeSeries> timeSeriesList = StackdriverExportUtils.createTimeSeriesList(METRIC, resource, CUSTOM_OPENCENSUS_DOMAIN, PROJECT_ID, DEFAULT_CONSTANT_LABELS);
assertThat(timeSeriesList).containsExactly(TimeSeries.newBuilder().setMetricKind(MetricKind.CUMULATIVE).setValueType(MetricDescriptor.ValueType.DOUBLE).setMetric(StackdriverExportUtils.createMetric(METRIC_DESCRIPTOR, LABEL_VALUE, CUSTOM_OPENCENSUS_DOMAIN, DEFAULT_CONSTANT_LABELS)).setResource(resource).addPoints(StackdriverExportUtils.createPoint(POINT, TIMESTAMP_2)).build());
}
use of com.google.bigtable.repackaged.com.google.monitoring.v3.TimeSeries in project instrumentation-java by census-instrumentation.
the class CreateTimeSeriesExporter method export.
@Override
public void export(Collection<Metric> metrics) {
List<TimeSeries> timeSeriesList = new ArrayList<>(metrics.size());
for (Metric metric : metrics) {
timeSeriesList.addAll(StackdriverExportUtils.createTimeSeriesList(metric, monitoredResource, domain, projectName.getProject(), constantLabels));
}
Span span = tracer.getCurrentSpan();
for (List<TimeSeries> batchedTimeSeries : Lists.partition(timeSeriesList, MAX_BATCH_EXPORT_SIZE)) {
span.addAnnotation("Export Stackdriver TimeSeries.");
try {
CreateTimeSeriesRequest request = CreateTimeSeriesRequest.newBuilder().setName(projectName.toString()).addAllTimeSeries(batchedTimeSeries).build();
metricServiceClient.createTimeSeries(request);
span.addAnnotation("Finish exporting TimeSeries.");
} catch (ApiException e) {
logger.log(Level.WARNING, "ApiException thrown when exporting TimeSeries.", e);
span.setStatus(Status.CanonicalCode.valueOf(e.getStatusCode().getCode().name()).toStatus().withDescription("ApiException thrown when exporting TimeSeries: " + StackdriverExportUtils.exceptionMessage(e)));
} catch (Throwable e) {
logger.log(Level.WARNING, "Exception thrown when exporting TimeSeries.", e);
span.setStatus(Status.UNKNOWN.withDescription("Exception thrown when exporting TimeSeries: " + StackdriverExportUtils.exceptionMessage(e)));
}
}
}
use of com.google.bigtable.repackaged.com.google.monitoring.v3.TimeSeries in project googleads-java-lib by googleads.
the class GetTrafficData method runExample.
/**
* Runs the example.
*
* @param adManagerServices the services factory.
* @param session the session.
* @param advertiserId the ID of the advertiser (company) to forecast for. Setting an advertiser
* will cause the forecast to apply the appropriate unified blocking rules.
* @throws ApiException if the API request failed with one or more service errors.
* @throws RemoteException if the API request failed due to other errors.
*/
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session) throws RemoteException {
// Get the ForecastService.
ForecastServiceInterface forecastService = adManagerServices.get(session, ForecastServiceInterface.class);
// Get the NetworkService.
NetworkServiceInterface networkService = adManagerServices.get(session, NetworkServiceInterface.class);
// Get the root ad unit ID used to target the whole site.
String rootAdUnitId = networkService.getCurrentNetwork().getEffectiveRootAdUnitId();
// Create inventory targeting.
InventoryTargeting inventoryTargeting = new InventoryTargeting();
// Create ad unit targeting for the root ad unit.
AdUnitTargeting adUnitTargeting = new AdUnitTargeting();
adUnitTargeting.setAdUnitId(rootAdUnitId);
adUnitTargeting.setIncludeDescendants(true);
inventoryTargeting.setTargetedAdUnits(new AdUnitTargeting[] { adUnitTargeting });
// Create targeting.
Targeting targeting = new Targeting();
targeting.setInventoryTargeting(inventoryTargeting);
// Create the date range. Include the previous and next 7 days.
Interval interval = new Interval(Instant.now().plus(Duration.standardDays(-7)), Instant.now().plus(Duration.standardDays(7)));
DateRange dateRange = new DateRange();
dateRange.setStartDate(DateTimes.toDateTime(interval.getStart()).getDate());
dateRange.setEndDate(DateTimes.toDateTime(interval.getEnd()).getDate());
// Request the traffic data.
TrafficDataRequest trafficDataRequest = new TrafficDataRequest();
trafficDataRequest.setRequestedDateRange(dateRange);
trafficDataRequest.setTargeting(targeting);
TrafficDataResponse trafficData = forecastService.getTrafficData(trafficDataRequest);
// Read the historical traffic data.
TimeSeries historicalTimeSeries = trafficData.getHistoricalTimeSeries();
if (historicalTimeSeries != null) {
Date historicalStartDate = historicalTimeSeries.getTimeSeriesDateRange().getStartDate();
DateTime historicalStart = new DateTime(historicalStartDate.getYear(), historicalStartDate.getMonth(), historicalStartDate.getDay(), 0, 0, 0);
for (int i = 0; i < historicalTimeSeries.getValues().length; i++) {
System.out.printf("%s: %d historical ad opportunities%n", historicalStart.plus(Duration.standardDays(i)).toString(DateTimeFormat.longDate()), historicalTimeSeries.getValues()[i]);
}
}
// Read the forecasted traffic data.
TimeSeries forecastedTimeSeries = trafficData.getForecastedTimeSeries();
if (forecastedTimeSeries != null) {
Date forecastedStartDate = forecastedTimeSeries.getTimeSeriesDateRange().getStartDate();
DateTime forecastedStart = new DateTime(forecastedStartDate.getYear(), forecastedStartDate.getMonth(), forecastedStartDate.getDay(), 0, 0, 0);
for (int i = 0; i < forecastedTimeSeries.getValues().length; i++) {
System.out.printf("%s: %d forecasted ad opportunities%n", forecastedStart.plus(Duration.standardDays(i)).toString(DateTimeFormat.longDate()), forecastedTimeSeries.getValues()[i]);
}
}
}
use of com.google.bigtable.repackaged.com.google.monitoring.v3.TimeSeries in project java-docs-samples by GoogleCloudPlatform.
the class BigQueryRunner method runQuery.
public void runQuery() throws InterruptedException {
QueryJobConfiguration queryConfig = QueryJobConfiguration.newBuilder("SELECT " + "CONCAT('https://stackoverflow.com/questions/', CAST(id as STRING)) as url, " + "view_count " + "FROM `bigquery-public-data.stackoverflow.posts_questions` " + "WHERE tags like '%google-bigquery%' " + "ORDER BY favorite_count DESC LIMIT 10").setUseLegacySql(false).build();
List<TimeSeries> timeSeriesList = new ArrayList<>();
long queryStartTime = System.currentTimeMillis();
// Create a job ID so that we can safely retry.
JobId jobId = JobId.of(UUID.randomUUID().toString());
Job queryJob = bigquery.create(JobInfo.newBuilder(queryConfig).setJobId(jobId).build());
// Wait for the query to complete.
queryJob = queryJob.waitFor();
// Check for errors
if (queryJob == null) {
throw new RuntimeException("Job no longer exists");
} else if (queryJob.getStatus().getError() != null) {
// errors, not just the latest one.
throw new RuntimeException(queryJob.getStatus().getError().toString());
}
// Log the result metrics.
TableResult result = queryJob.getQueryResults();
long queryEndTime = System.currentTimeMillis();
// Add query duration metric.
timeSeriesList.add(prepareMetric(QUERY_DURATION_METRIC, queryEndTime - queryStartTime));
// Add rows returned metric.
timeSeriesList.add(prepareMetric(ROWS_RETURNED_METRIC, result.getTotalRows()));
// Prepares the time series request
CreateTimeSeriesRequest request = CreateTimeSeriesRequest.newBuilder().setName(projectName).addAllTimeSeries(timeSeriesList).build();
createMetricsIfNeeded();
client.createTimeSeries(request);
os.println("Done writing metrics.");
mostRecentRunResult = result;
}
Aggregations