diff --git a/sdk/monitor/azure-monitor-query/CHANGELOG.md b/sdk/monitor/azure-monitor-query/CHANGELOG.md
index 4b3b335929cee..d826041f590b3 100644
--- a/sdk/monitor/azure-monitor-query/CHANGELOG.md
+++ b/sdk/monitor/azure-monitor-query/CHANGELOG.md
@@ -1,17 +1,23 @@
# Release History
-## 1.3.0-beta.1 (Unreleased)
+## 1.3.0-beta.1 (2023-08-10)
### Features Added
+- Added `MetricsBatchQueryClient` and `MetricsBatchQueryAsyncClient` to support batch querying metrics.
-### Breaking Changes
+### Other Changes
+
+#### Dependency Updates
+
+- Upgraded `azure-core` from `1.41.0` to version `1.42.0`.
+- Upgraded `azure-core-http-netty` from `1.13.5` to version `1.13.6`.
+
+## 1.2.3 (2023-07-28)
### Bugs Fixed
- Fixed bug that disabled sovereign cloud support.
-### Other Changes
-
## 1.2.2 (2023-07-25)
### Other Changes
@@ -21,7 +27,6 @@
- Upgraded `azure-core` from `1.40.0` to version `1.41.0`.
- Upgraded `azure-core-http-netty` from `1.13.4` to version `1.13.5`.
-
## 1.2.1 (2023-06-20)
### Other Changes
diff --git a/sdk/monitor/azure-monitor-query/README.md b/sdk/monitor/azure-monitor-query/README.md
index 204760c7d137f..17519efad4a5f 100644
--- a/sdk/monitor/azure-monitor-query/README.md
+++ b/sdk/monitor/azure-monitor-query/README.md
@@ -66,7 +66,7 @@ add the direct dependency to your project as follows.
com.azure
azure-monitor-query
- 1.2.2
+ 1.3.0-beta.1
```
@@ -87,7 +87,7 @@ To use the [DefaultAzureCredential][DefaultAzureCredential] provider shown below
com.azure
azure-identity
- 1.9.2
+ 1.10.0
```
[//]: # ({x-version-update-end})
@@ -108,6 +108,13 @@ MetricsQueryClient metricsQueryClient = new MetricsQueryClientBuilder()
.buildClient();
```
+```java readme-sample-createMetricsBatchQueryClient
+MetricsBatchQueryClient metricsBatchQueryClient = new MetricsBatchQueryClientBuilder()
+ .credential(new DefaultAzureCredentialBuilder().build())
+ .endpoint("{endpoint}")
+ .buildClient();
+```
+
#### Asynchronous clients
```java readme-sample-createLogsQueryAsyncClient
@@ -122,6 +129,13 @@ MetricsQueryAsyncClient metricsQueryAsyncClient = new MetricsQueryClientBuilder(
.buildAsyncClient();
```
+```java readme-sample-createMetricsBatchQueryAsyncClient
+MetricsBatchQueryAsyncClient metricsBatchQueryAsyncClient = new MetricsBatchQueryClientBuilder()
+ .credential(new DefaultAzureCredentialBuilder().build())
+ .endpoint("{endpoint}")
+ .buildAsyncClient();
+```
+
#### Configure clients for non-public Azure clouds
By default, `LogQueryClient` and `MetricQueryClient` are configured to connect to the public Azure Cloud. These can be configured to connect to non-public Azure clouds by setting the correct `endpoint` in the client builders: For example:
@@ -182,16 +196,17 @@ Each set of metric values is a time series with the following characteristics:
- [Handle metrics query response](#handle-metrics-query-response)
- [Get average and count metrics](#get-average-and-count-metrics)
- [Create a metrics client for non-public Azure clouds](#configure-clients-for-non-public-azure-clouds)
-
+- [Metrics batch query](#metrics-batch-query)
+ - [Handle metrics batch query response](#handle-metrics-batch-query-response)
### Logs query
```java readme-sample-logsquery
LogsQueryClient logsQueryClient = new LogsQueryClientBuilder()
- .credential(new DefaultAzureCredentialBuilder().build())
- .buildClient();
+ .credential(new DefaultAzureCredentialBuilder().build())
+ .buildClient();
LogsQueryResult queryResults = logsQueryClient.queryWorkspace("{workspace-id}", "{kusto-query}",
- new QueryTimeInterval(Duration.ofDays(2)));
+ new QueryTimeInterval(Duration.ofDays(2)));
for (LogsTableRow row : queryResults.getTable().getRows()) {
System.out.println(row.getColumnValue("OperationName") + " " + row.getColumnValue("ResourceGroup"));
@@ -217,11 +232,11 @@ public class CustomLogModel {
```java readme-sample-logsquerycustommodel
LogsQueryClient logsQueryClient = new LogsQueryClientBuilder()
- .credential(new DefaultAzureCredentialBuilder().build())
- .buildClient();
+ .credential(new DefaultAzureCredentialBuilder().build())
+ .buildClient();
List customLogModels = logsQueryClient.queryWorkspace("{workspace-id}", "{kusto-query}",
- new QueryTimeInterval(Duration.ofDays(2)), CustomLogModel.class);
+ new QueryTimeInterval(Duration.ofDays(2)), CustomLogModel.class);
for (CustomLogModel customLogModel : customLogModels) {
System.out.println(customLogModel.getOperationName() + " " + customLogModel.getResourceGroup());
@@ -270,8 +285,8 @@ for (LogsTableRow row : queryResults.getTable().getRows()) {
```java readme-sample-batchlogsquery
LogsQueryClient logsQueryClient = new LogsQueryClientBuilder()
- .credential(new DefaultAzureCredentialBuilder().build())
- .buildClient();
+ .credential(new DefaultAzureCredentialBuilder().build())
+ .buildClient();
LogsBatchQuery logsBatchQuery = new LogsBatchQuery();
String query1 = logsBatchQuery.addWorkspaceQuery("{workspace-id}", "{query-1}", new QueryTimeInterval(Duration.ofDays(2)));
@@ -279,7 +294,7 @@ String query2 = logsBatchQuery.addWorkspaceQuery("{workspace-id}", "{query-2}",
String query3 = logsBatchQuery.addWorkspaceQuery("{workspace-id}", "{query-3}", new QueryTimeInterval(Duration.ofDays(10)));
LogsBatchQueryResultCollection batchResults = logsQueryClient
- .queryBatchWithResponse(logsBatchQuery, Context.NONE).getValue();
+ .queryBatchWithResponse(logsBatchQuery, Context.NONE).getValue();
LogsBatchQueryResult query1Result = batchResults.getResult(query1);
for (LogsTableRow row : query1Result.getTable().getRows()) {
@@ -311,7 +326,7 @@ LogsQueryOptions options = new LogsQueryOptions()
.setServerTimeout(Duration.ofMinutes(10));
Response response = logsQueryClient.queryWorkspaceWithResponse("{workspace-id}",
- "{kusto-query}", new QueryTimeInterval(Duration.ofDays(2)), options, Context.NONE);
+ "{kusto-query}", new QueryTimeInterval(Duration.ofDays(2)), options, Context.NONE);
```
#### Query multiple workspaces
@@ -325,13 +340,13 @@ to include this column.
```java readme-sample-logsquerymultipleworkspaces
LogsQueryClient logsQueryClient = new LogsQueryClientBuilder()
- .credential(new DefaultAzureCredentialBuilder().build())
- .buildClient();
+ .credential(new DefaultAzureCredentialBuilder().build())
+ .buildClient();
Response response = logsQueryClient.queryWorkspaceWithResponse("{workspace-id}", "{kusto-query}",
- new QueryTimeInterval(Duration.ofDays(2)), new LogsQueryOptions()
- .setAdditionalWorkspaces(Arrays.asList("{additional-workspace-identifiers}")),
- Context.NONE);
+ new QueryTimeInterval(Duration.ofDays(2)), new LogsQueryOptions()
+ .setAdditionalWorkspaces(Arrays.asList("{additional-workspace-identifiers}")),
+ Context.NONE);
LogsQueryResult result = response.getValue();
```
@@ -345,13 +360,13 @@ To get logs query execution statistics, such as CPU and memory consumption:
The following example prints the query execution time:
```java readme-sample-includestatistics
LogsQueryClient client = new LogsQueryClientBuilder()
- .credential(credential)
- .buildClient();
+ .credential(credential)
+ .buildClient();
LogsQueryOptions options = new LogsQueryOptions()
- .setIncludeStatistics(true);
+ .setIncludeStatistics(true);
Response response = client.queryWorkspaceWithResponse("{workspace-id}",
- "AzureActivity | top 10 by TimeGenerated", QueryTimeInterval.LAST_1_HOUR, options, Context.NONE);
+ "AzureActivity | top 10 by TimeGenerated", QueryTimeInterval.LAST_1_HOUR, options, Context.NONE);
LogsQueryResult result = response.getValue();
BinaryData statistics = result.getStatistics();
@@ -384,18 +399,18 @@ To get visualization data for logs queries using the [render operator](https://l
For example:
```java readme-sample-includevisualization
LogsQueryClient client = new LogsQueryClientBuilder()
- .credential(credential)
- .buildClient();
+ .credential(credential)
+ .buildClient();
String visualizationQuery = "StormEvents"
- + "| summarize event_count = count() by State"
- + "| where event_count > 10"
- + "| project State, event_count"
- + "| render columnchart";
+ + "| summarize event_count = count() by State"
+ + "| where event_count > 10"
+ + "| project State, event_count"
+ + "| render columnchart";
LogsQueryOptions options = new LogsQueryOptions()
- .setIncludeVisualization(true);
+ .setIncludeVisualization(true);
Response response = client.queryWorkspaceWithResponse("{workspace-id}", visualizationQuery,
- QueryTimeInterval.LAST_7_DAYS, options, Context.NONE);
+ QueryTimeInterval.LAST_7_DAYS, options, Context.NONE);
LogsQueryResult result = response.getValue();
BinaryData visualization = result.getVisualization();
@@ -439,11 +454,11 @@ A resource ID, as denoted by the `{resource-id}` placeholder in the sample below
```java readme-sample-metricsquery
MetricsQueryClient metricsQueryClient = new MetricsQueryClientBuilder()
- .credential(new DefaultAzureCredentialBuilder().build())
- .buildClient();
+ .credential(new DefaultAzureCredentialBuilder().build())
+ .buildClient();
MetricsQueryResult metricsQueryResult = metricsQueryClient.queryResource("{resource-uri}",
- Arrays.asList("SuccessfulCalls", "TotalCalls"));
+ Arrays.asList("SuccessfulCalls", "TotalCalls"));
for (MetricResult metric : metricsQueryResult.getMetrics()) {
System.out.println("Metric name " + metric.getMetricName());
@@ -510,6 +525,41 @@ for (MetricResult metric : metricsQueryResult.getMetrics()) {
}
```
+### Metrics batch query
+
+#### Handle metrics batch query response
+
+```java readme-sample-metricsquerybatch
+MetricsBatchQueryClient metricsBatchQueryClient = new MetricsBatchQueryClientBuilder()
+ .credential(new DefaultAzureCredentialBuilder().build())
+ .endpoint("{endpoint}")
+ .buildClient();
+
+MetricsBatchResult metricsBatchResult = metricsBatchQueryClient.queryBatch(
+ Arrays.asList("{resourceId1}", "{resourceId2}"),
+ Arrays.asList("{metric1}", "{metric2}"),
+ "{metricNamespace}");
+
+for (MetricsQueryResult metricsQueryResult : metricsBatchResult.getMetricsQueryResults()) {
+ // Each MetricsQueryResult corresponds to one of the resourceIds in the batch request.
+ List metrics = metricsQueryResult.getMetrics();
+ metrics.forEach(metric -> {
+ System.out.println(metric.getMetricName());
+ System.out.println(metric.getId());
+ System.out.println(metric.getResourceType());
+ System.out.println(metric.getUnit());
+ System.out.println(metric.getTimeSeries().size());
+ System.out.println(metric.getTimeSeries().get(0).getValues().size());
+ metric.getTimeSeries()
+ .stream()
+ .flatMap(ts -> ts.getValues().stream())
+ .forEach(mv -> System.out.println(mv.getTimeStamp().toString()
+ + "; Count = " + mv.getCount()
+ + "; Average = " + mv.getAverage()));
+ });
+}
+```
+
## Troubleshooting
See our [troubleshooting guide](https://github.com/Azure/azure-sdk-for-java/blob/main/sdk/monitor/azure-monitor-query/TROUBLESHOOTING.md)
diff --git a/sdk/monitor/azure-monitor-query/TROUBLESHOOTING.md b/sdk/monitor/azure-monitor-query/TROUBLESHOOTING.md
index a5d5465cda8fe..1f67f6578d95e 100644
--- a/sdk/monitor/azure-monitor-query/TROUBLESHOOTING.md
+++ b/sdk/monitor/azure-monitor-query/TROUBLESHOOTING.md
@@ -44,14 +44,14 @@ MetricsQueryClient can be configured as shown below:
```java readme-sample-enablehttplogging
LogsQueryClient logsQueryClient = new LogsQueryClientBuilder()
- .credential(credential)
- .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
- .buildClient();
+ .credential(credential)
+ .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
+ .buildClient();
// or
MetricsQueryClient metricsQueryClient = new MetricsQueryClientBuilder()
- .credential(credential)
- .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
- .buildClient();
+ .credential(credential)
+ .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
+ .buildClient();
```
Alternatively, you can configure logging HTTP requests and responses for your entire application by setting the
@@ -149,9 +149,9 @@ following.
```java readme-sample-responsetimeout
LogsQueryClient client = new LogsQueryClientBuilder()
- .credential(credential)
- .clientOptions(new HttpClientOptions().setResponseTimeout(Duration.ofSeconds(120)))
- .buildClient();
+ .credential(credential)
+ .clientOptions(new HttpClientOptions().setResponseTimeout(Duration.ofSeconds(120)))
+ .buildClient();
```
The above code will create a LogsQueryClient with a Netty HTTP client that waits for a response for up to 120 seconds.
@@ -170,11 +170,11 @@ previous section.
```java readme-sample-servertimeout
LogsQueryClient client = new LogsQueryClientBuilder()
- .credential(credential)
- .buildClient();
+ .credential(credential)
+ .buildClient();
client.queryWorkspaceWithResponse("{workspaceId}", "{kusto-query-string}", QueryTimeInterval.LAST_DAY,
- new LogsQueryOptions().setServerTimeout(Duration.ofMinutes(10)), Context.NONE);
+ new LogsQueryOptions().setServerTimeout(Duration.ofMinutes(10)), Context.NONE);
```
### Troubleshooting server timeouts on OkHTTP client
@@ -185,9 +185,9 @@ below. The downside to doing this is that every request from this client will ha
```java readme-sample-okhttpresponsetimeout
LogsQueryClient client = new LogsQueryClientBuilder()
- .credential(credential)
- .clientOptions(new HttpClientOptions().setResponseTimeout(Duration.ofSeconds(120)))
- .buildClient();
+ .credential(credential)
+ .clientOptions(new HttpClientOptions().setResponseTimeout(Duration.ofSeconds(120)))
+ .buildClient();
```
### Troubleshooting partially successful logs query requests
@@ -199,7 +199,7 @@ in `LogsQueryOptions` as shown below:
```java readme-sample-allowpartialerrors
client.queryWorkspaceWithResponse("{workspaceId}", "{kusto-query-string}", QueryTimeInterval.LAST_DAY,
- new LogsQueryOptions().setAllowPartialErrors(true), Context.NONE);
+ new LogsQueryOptions().setAllowPartialErrors(true), Context.NONE);
```
## Troubleshooting Metrics Query
diff --git a/sdk/monitor/azure-monitor-query/assets.json b/sdk/monitor/azure-monitor-query/assets.json
index 646765acedabf..301ac10c7eadf 100644
--- a/sdk/monitor/azure-monitor-query/assets.json
+++ b/sdk/monitor/azure-monitor-query/assets.json
@@ -2,5 +2,5 @@
"AssetsRepo": "Azure/azure-sdk-assets",
"AssetsRepoPrefixPath": "java",
"TagPrefix": "java/monitor/azure-monitor-query",
- "Tag": "java/monitor/azure-monitor-query_9cf6f47b0a"
+ "Tag": "java/monitor/azure-monitor-query_c61b998a77"
}
diff --git a/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/MetricsBatchQueryAsyncClient.java b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/MetricsBatchQueryAsyncClient.java
new file mode 100644
index 0000000000000..c14ecc758c2a8
--- /dev/null
+++ b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/MetricsBatchQueryAsyncClient.java
@@ -0,0 +1,102 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+package com.azure.monitor.query;
+
+import com.azure.core.annotation.ReturnType;
+import com.azure.core.annotation.ServiceClient;
+import com.azure.core.annotation.ServiceMethod;
+import com.azure.core.http.rest.Response;
+import com.azure.core.http.rest.SimpleResponse;
+import com.azure.core.util.CoreUtils;
+import com.azure.core.util.logging.ClientLogger;
+import com.azure.monitor.query.implementation.metricsbatch.AzureMonitorMetricBatch;
+import com.azure.monitor.query.implementation.metricsbatch.models.MetricResultsResponse;
+import com.azure.monitor.query.implementation.metricsbatch.models.MetricResultsResponseValuesItem;
+import com.azure.monitor.query.implementation.metricsbatch.models.ResourceIdList;
+import com.azure.monitor.query.models.MetricsBatchResult;
+import com.azure.monitor.query.models.MetricsQueryResult;
+import reactor.core.publisher.Mono;
+
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+import static com.azure.core.util.FluxUtil.monoError;
+import static com.azure.monitor.query.implementation.metrics.models.MetricsHelper.getSubscriptionFromResourceId;
+import static com.azure.monitor.query.implementation.metrics.models.MetricsHelper.mapToMetricsQueryResult;
+
+/**
+ * This class provides an asynchronous client that contains all the query operations that use batch requests to retrieve
+ * metrics for multiple resources.
+ */
+@ServiceClient(builder = MetricsBatchQueryClientBuilder.class, isAsync = true)
+public final class MetricsBatchQueryAsyncClient {
+ private static final ClientLogger LOGGER = new ClientLogger(MetricsBatchQueryAsyncClient.class);
+
+ private final AzureMonitorMetricBatch serviceClient;
+
+ MetricsBatchQueryAsyncClient(AzureMonitorMetricBatch azureMonitorMetricBatch) {
+ this.serviceClient = azureMonitorMetricBatch;
+ }
+
+ /**
+ * Returns all the Azure Monitor metrics requested for the batch of resources.
+ *
+ * @param resourceUris The resource URIs for which the metrics is requested.
+ * @param metricsNames The names of the metrics to query.
+ * @param metricsNamespace The namespace of the metrics to query.
+ * @return A time-series metrics result for the requested metric names.
+ */
+ @ServiceMethod(returns = ReturnType.SINGLE)
+ public Mono queryBatch(List resourceUris, List metricsNames, String metricsNamespace) {
+ return this.queryBatchWithResponse(resourceUris, metricsNames, metricsNamespace)
+ .map(Response::getValue);
+ }
+
+ /**
+ * Returns all the Azure Monitor metrics requested for the batch of resources.
+ *
+ * @param resourceUris The resource URIs for which the metrics is requested.
+ * @param metricsNames The names of the metrics to query.
+ * @param metricsNamespace The namespace of the metrics to query.
+ * @return A time-series metrics result for the requested metric names.
+ * @throws IllegalArgumentException thrown if {@code resourceUris}, {@code metricsNames} or {@code metricsNamespace} are empty.
+ * @throws NullPointerException thrown if {@code resourceUris}, {@code metricsNames} or {@code metricsNamespace} are null.
+ */
+ @ServiceMethod(returns = ReturnType.SINGLE)
+ public Mono> queryBatchWithResponse(List resourceUris, List metricsNames,
+ String metricsNamespace) {
+
+ if (CoreUtils.isNullOrEmpty(Objects.requireNonNull(resourceUris, "'resourceUris cannot be null."))) {
+ return monoError(LOGGER, new IllegalArgumentException("resourceUris cannot be empty"));
+ }
+
+ if (CoreUtils.isNullOrEmpty(Objects.requireNonNull(metricsNames, "metricsNames cannot be null"))) {
+ return monoError(LOGGER, new IllegalArgumentException("metricsNames cannot be empty"));
+ }
+
+ if (CoreUtils.isNullOrEmpty(Objects.requireNonNull(metricsNamespace, "metricsNamespace cannot be null"))) {
+ return monoError(LOGGER, new IllegalArgumentException("metricsNamespace cannot be empty"));
+ }
+
+ String subscriptionId = getSubscriptionFromResourceId(resourceUris.get(0));
+ ResourceIdList resourceIdList = new ResourceIdList();
+ resourceIdList.setResourceids(resourceUris);
+ Mono> responseMono = this.serviceClient.getMetrics()
+ .batchWithResponseAsync(subscriptionId, metricsNamespace, metricsNames, resourceIdList, null,
+ null, null, null, null, null, null);
+
+
+ return responseMono.map(response -> {
+ MetricResultsResponse value = response.getValue();
+ List values = value.getValues();
+ List metricsQueryResults = values.stream()
+ .map(result -> mapToMetricsQueryResult(result))
+ .collect(Collectors.toList());
+ MetricsBatchResult metricsBatchResult = new MetricsBatchResult(metricsQueryResults);
+ return new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
+ response.getHeaders(), metricsBatchResult);
+ });
+ }
+}
diff --git a/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/MetricsBatchQueryClient.java b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/MetricsBatchQueryClient.java
new file mode 100644
index 0000000000000..b1a113f22a0b9
--- /dev/null
+++ b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/MetricsBatchQueryClient.java
@@ -0,0 +1,99 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+package com.azure.monitor.query;
+
+import com.azure.core.annotation.ReturnType;
+import com.azure.core.annotation.ServiceClient;
+import com.azure.core.annotation.ServiceMethod;
+import com.azure.core.http.rest.Response;
+import com.azure.core.http.rest.SimpleResponse;
+import com.azure.core.util.Context;
+import com.azure.core.util.CoreUtils;
+import com.azure.core.util.logging.ClientLogger;
+import com.azure.monitor.query.implementation.metricsbatch.AzureMonitorMetricBatch;
+import com.azure.monitor.query.implementation.metricsbatch.models.MetricResultsResponse;
+import com.azure.monitor.query.implementation.metricsbatch.models.MetricResultsResponseValuesItem;
+import com.azure.monitor.query.implementation.metricsbatch.models.ResourceIdList;
+import com.azure.monitor.query.models.MetricsBatchResult;
+import com.azure.monitor.query.models.MetricsQueryResult;
+
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+import static com.azure.monitor.query.implementation.metrics.models.MetricsHelper.getSubscriptionFromResourceId;
+import static com.azure.monitor.query.implementation.metrics.models.MetricsHelper.mapToMetricsQueryResult;
+
+/**
+ * This class provides an asynchronous client that contains all the query operations that use batch requests to retrieve
+ * metrics for multiple resources.
+ */
+@ServiceClient(builder = MetricsBatchQueryClientBuilder.class)
+public final class MetricsBatchQueryClient {
+ private static final ClientLogger LOGGER = new ClientLogger(MetricsBatchQueryClient.class);
+
+ private final AzureMonitorMetricBatch serviceClient;
+
+ MetricsBatchQueryClient(AzureMonitorMetricBatch azureMonitorMetricBatch) {
+ this.serviceClient = azureMonitorMetricBatch;
+ }
+
+ /**
+ * Returns all the Azure Monitor metrics requested for the batch of resources.
+ *
+ * @param resourceUris The resource URIs for which the metrics is requested.
+ * @param metricsNames The names of the metrics to query.
+ * @param metricsNamespace The namespace of the metrics to query.
+ * @return A time-series metrics result for the requested metric names.
+ */
+ @ServiceMethod(returns = ReturnType.SINGLE)
+ public MetricsBatchResult queryBatch(List resourceUris, List metricsNames, String metricsNamespace) {
+ return this.queryBatchWithResponse(resourceUris, metricsNames, metricsNamespace, Context.NONE).getValue();
+ }
+
+ /**
+ * Returns all the Azure Monitor metrics requested for the batch of resources.
+ *
+ * @param resourceUris The resource URIs for which the metrics is requested.
+ * @param metricsNames The names of the metrics to query.
+ * @param metricsNamespace The namespace of the metrics to query.
+ * @param context The context to associate with this operation.
+ * @return A time-series metrics result for the requested metric names.
+ * @throws IllegalArgumentException thrown if {@code resourceUris}, {@code metricsNames} or {@code metricsNamespace} are empty.
+ * @throws NullPointerException thrown if {@code resourceUris}, {@code metricsNames} or {@code metricsNamespace} are null.
+ */
+ @ServiceMethod(returns = ReturnType.SINGLE)
+ public Response queryBatchWithResponse(List resourceUris, List metricsNames,
+ String metricsNamespace, Context context) {
+ if (CoreUtils.isNullOrEmpty(Objects.requireNonNull(resourceUris, "'resourceUris cannot be null."))) {
+ throw LOGGER.logExceptionAsError(new IllegalArgumentException("resourceUris cannot be empty"));
+ }
+
+ if (CoreUtils.isNullOrEmpty(Objects.requireNonNull(metricsNames, "metricsNames cannot be null"))) {
+ throw LOGGER.logExceptionAsError(new IllegalArgumentException("metricsNames cannot be empty"));
+ }
+
+ if (CoreUtils.isNullOrEmpty(Objects.requireNonNull(metricsNamespace, "metricsNamespace cannot be null"))) {
+ throw LOGGER.logExceptionAsError(new IllegalArgumentException("metricsNamespace cannot be empty"));
+ }
+
+ String subscriptionId = getSubscriptionFromResourceId(resourceUris.get(0));
+ ResourceIdList resourceIdList = new ResourceIdList();
+ resourceIdList.setResourceids(resourceUris);
+ Response response = this.serviceClient.getMetrics()
+ .batchWithResponse(subscriptionId, metricsNamespace, metricsNames, resourceIdList, null,
+ null, null, null, null, null, null, context);
+ MetricResultsResponse value = response.getValue();
+ List values = value.getValues();
+ List metricsQueryResults = values.stream()
+ .map(result -> mapToMetricsQueryResult(result))
+ .collect(Collectors.toList());
+ MetricsBatchResult metricsBatchResult = new MetricsBatchResult(metricsQueryResults);
+
+ return new SimpleResponse<>(response.getRequest(), response.getStatusCode(),
+ response.getHeaders(), metricsBatchResult);
+
+ }
+
+}
diff --git a/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/MetricsBatchQueryClientBuilder.java b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/MetricsBatchQueryClientBuilder.java
new file mode 100644
index 0000000000000..639c077fac7cb
--- /dev/null
+++ b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/MetricsBatchQueryClientBuilder.java
@@ -0,0 +1,166 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+package com.azure.monitor.query;
+
+import com.azure.core.annotation.ServiceClientBuilder;
+import com.azure.core.client.traits.ConfigurationTrait;
+import com.azure.core.client.traits.EndpointTrait;
+import com.azure.core.client.traits.HttpTrait;
+import com.azure.core.client.traits.TokenCredentialTrait;
+import com.azure.core.credential.TokenCredential;
+import com.azure.core.http.HttpClient;
+import com.azure.core.http.HttpPipeline;
+import com.azure.core.http.policy.HttpLogOptions;
+import com.azure.core.http.policy.HttpPipelinePolicy;
+import com.azure.core.http.policy.RetryOptions;
+import com.azure.core.http.policy.RetryPolicy;
+import com.azure.core.util.ClientOptions;
+import com.azure.core.util.Configuration;
+import com.azure.monitor.query.implementation.metricsbatch.AzureMonitorMetricBatchBuilder;
+
+/**
+ * Fluent builder for creating instances of {@link MetricsBatchQueryClient} and {@link MetricsBatchQueryAsyncClient}.
+ */
+@ServiceClientBuilder(serviceClients = {MetricsBatchQueryClient.class, MetricsBatchQueryAsyncClient.class})
+public final class MetricsBatchQueryClientBuilder implements EndpointTrait,
+ HttpTrait, ConfigurationTrait, TokenCredentialTrait {
+
+ private final AzureMonitorMetricBatchBuilder innerMetricsBatchBuilder = new AzureMonitorMetricBatchBuilder();
+
+ /**
+ * Sets the metrics batch query endpoint.
+ * @param endpoint the endpoint.
+ * @return the {@link MetricsBatchQueryClientBuilder}.
+ */
+ @Override
+ public MetricsBatchQueryClientBuilder endpoint(String endpoint) {
+ innerMetricsBatchBuilder.endpoint(endpoint);
+ return this;
+ }
+
+ /**
+ * Sets The HTTP pipeline to send requests through.
+ * @param pipeline the pipeline value.
+ * @return the {@link MetricsBatchQueryClientBuilder}.
+ */
+ @Override
+ public MetricsBatchQueryClientBuilder pipeline(HttpPipeline pipeline) {
+ innerMetricsBatchBuilder.pipeline(pipeline);
+ return this;
+ }
+
+ /**
+ * Sets The HTTP client used to send the request.
+ * @param httpClient the httpClient value.
+ * @return the {@link MetricsBatchQueryClientBuilder}.
+ */
+ @Override
+ public MetricsBatchQueryClientBuilder httpClient(HttpClient httpClient) {
+ innerMetricsBatchBuilder.httpClient(httpClient);
+ return this;
+ }
+
+ /**
+ * Sets The configuration store that is used during construction of the service client.
+ * @param configuration the configuration value.
+ * @return the {@link MetricsBatchQueryClientBuilder}.
+ */
+ @Override
+ public MetricsBatchQueryClientBuilder configuration(Configuration configuration) {
+ innerMetricsBatchBuilder.configuration(configuration);
+ return this;
+ }
+
+ /**
+ * Sets The logging configuration for HTTP requests and responses.
+ * @param httpLogOptions the httpLogOptions value.
+ * @return the {@link MetricsBatchQueryClientBuilder}.
+ */
+ @Override
+ public MetricsBatchQueryClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
+ innerMetricsBatchBuilder.httpLogOptions(httpLogOptions);
+ return this;
+ }
+
+ /**
+ * Sets The retry policy that will attempt to retry failed requests, if applicable.
+ * @param retryPolicy the retryPolicy value.
+ * @return the {@link MetricsBatchQueryClientBuilder}.
+ */
+ public MetricsBatchQueryClientBuilder retryPolicy(RetryPolicy retryPolicy) {
+ innerMetricsBatchBuilder.retryPolicy(retryPolicy);
+ return this;
+ }
+
+ /**
+ * Sets the {@link RetryOptions} used for creating the client.
+ * @param retryOptions The {@link RetryOptions}.
+ * @return the updated {@link MetricsBatchQueryClientBuilder}.
+ */
+ @Override
+ public MetricsBatchQueryClientBuilder retryOptions(RetryOptions retryOptions) {
+ innerMetricsBatchBuilder.retryOptions(retryOptions);
+ return this;
+ }
+
+ /**
+ * Adds a custom Http pipeline policy.
+ * @param customPolicy The custom Http pipeline policy to add.
+ * @return the {@link MetricsBatchQueryClientBuilder}.
+ */
+ @Override
+ public MetricsBatchQueryClientBuilder addPolicy(HttpPipelinePolicy customPolicy) {
+ innerMetricsBatchBuilder.addPolicy(customPolicy);
+ return this;
+ }
+
+ /**
+ * Sets The TokenCredential used for authentication.
+ * @param tokenCredential the tokenCredential value.
+ * @return the {@link MetricsBatchQueryClientBuilder}.
+ */
+ @Override
+ public MetricsBatchQueryClientBuilder credential(TokenCredential tokenCredential) {
+ innerMetricsBatchBuilder.credential(tokenCredential);
+ return this;
+ }
+
+ /**
+ * Set the {@link ClientOptions} used for creating the client.
+ * @param clientOptions The {@link ClientOptions}.
+ * @return the {@link MetricsBatchQueryClientBuilder}.
+ */
+ @Override
+ public MetricsBatchQueryClientBuilder clientOptions(ClientOptions clientOptions) {
+ innerMetricsBatchBuilder.clientOptions(clientOptions);
+ return this;
+ }
+
+ /**
+ * The service version to use when creating the client.
+ * @param serviceVersion The {@link MetricsBatchQueryServiceVersion}.
+ * @return the {@link MetricsBatchQueryClientBuilder}.
+ */
+ public MetricsBatchQueryClientBuilder serviceVersion(MetricsBatchQueryServiceVersion serviceVersion) {
+ innerMetricsBatchBuilder.apiVersion(serviceVersion.getVersion());
+ return this;
+ }
+
+ /**
+ * Creates a synchronous client with the configured options in this builder.
+ * @return A synchronous {@link MetricsBatchQueryClient}.
+ */
+ public MetricsBatchQueryClient buildClient() {
+ return new MetricsBatchQueryClient(innerMetricsBatchBuilder.buildClient());
+ }
+
+ /**
+ * Creates an asynchronous client with the configured options in this builder.
+ * @return An asynchronous {@link MetricsBatchQueryAsyncClient}.
+ */
+ public MetricsBatchQueryAsyncClient buildAsyncClient() {
+ return new MetricsBatchQueryAsyncClient(innerMetricsBatchBuilder.buildClient());
+ }
+
+}
diff --git a/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/MetricsBatchQueryServiceVersion.java b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/MetricsBatchQueryServiceVersion.java
new file mode 100644
index 0000000000000..bb9ff02b5de8b
--- /dev/null
+++ b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/MetricsBatchQueryServiceVersion.java
@@ -0,0 +1,35 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+package com.azure.monitor.query;
+
+import com.azure.core.util.ServiceVersion;
+
+/**
+ * The versions of Azure Monitor Metrics Batch Query supported by this client library.
+ */
+public enum MetricsBatchQueryServiceVersion implements ServiceVersion {
+ /**
+ * The preview version of the Metrics Batch Query service.
+ */
+ V2023_05_01_PREVIEW("2023-05-01-preview");
+
+ private final String version;
+
+ MetricsBatchQueryServiceVersion(String version) {
+ this.version = version;
+ }
+
+ @Override
+ public String getVersion() {
+ return version;
+ }
+
+ /**
+ * Gets the latest service version supported by this client library.
+ * @return the latest {@link MetricsBatchQueryServiceVersion}.
+ */
+ public static MetricsBatchQueryServiceVersion getLatest() {
+ return V2023_05_01_PREVIEW;
+ }
+}
diff --git a/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/MetricsQueryClientBuilder.java b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/MetricsQueryClientBuilder.java
index dc180ef4887b1..c9227ecfae538 100644
--- a/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/MetricsQueryClientBuilder.java
+++ b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/MetricsQueryClientBuilder.java
@@ -19,6 +19,7 @@
import com.azure.core.util.Configuration;
import com.azure.core.util.logging.ClientLogger;
import com.azure.monitor.query.implementation.metrics.MonitorManagementClientImplBuilder;
+import com.azure.monitor.query.implementation.metricsbatch.AzureMonitorMetricBatchBuilder;
import com.azure.monitor.query.implementation.metricsdefinitions.MetricsDefinitionsClientImplBuilder;
import com.azure.monitor.query.implementation.metricsnamespaces.MetricsNamespacesClientImplBuilder;
@@ -54,6 +55,8 @@ public final class MetricsQueryClientBuilder implements EndpointTrait metrics = item.getValue()
+ .stream()
+ .map(metric -> mapToMetrics(metric))
+ .collect(Collectors.toList());
+
+ MetricsQueryResult metricsQueryResult = new MetricsQueryResult(/* TODO (srnagar): fix this item.getCost() */ null,
+ new QueryTimeInterval(item.getInterval()), item.getInterval(), item.getNamespace(), item.getResourceregion(), metrics);
+ return metricsQueryResult;
+ }
+
+ public static MetricResult mapToMetrics(com.azure.monitor.query.implementation.metricsbatch.models.Metric metric) {
+ List timeSeries = metric.getTimeseries().stream().map(ts -> mapToTimeSeries(ts)).collect(Collectors.toList());
+ MetricResult metricResult = new MetricResult(metric.getId(), metric.getType(), MetricUnit.fromString(metric.getUnit().name()),
+ metric.getName().getValue(), timeSeries, metric.getDisplayDescription(),
+ new ResponseError(metric.getErrorCode(), metric.getErrorMessage()));
+ return metricResult;
+ }
+
+ public static com.azure.monitor.query.models.TimeSeriesElement mapToTimeSeries(com.azure.monitor.query.implementation.metricsbatch.models.TimeSeriesElement ts) {
+ List values = ts.getData().stream().map(mv -> mapToMetricValue(mv)).collect(Collectors.toList());
+ Map metadata = ts.getMetadatavalues().stream().collect(Collectors.toMap(md -> md.getName().getValue(), md -> md.getValue()));
+ com.azure.monitor.query.models.TimeSeriesElement timeSeriesElement = new com.azure.monitor.query.models.TimeSeriesElement(values, metadata);
+ return timeSeriesElement;
+ }
+
+ public static com.azure.monitor.query.models.MetricValue mapToMetricValue(com.azure.monitor.query.implementation.metricsbatch.models.MetricValue mv) {
+ com.azure.monitor.query.models.MetricValue metricValue = new com.azure.monitor.query.models.MetricValue(mv.getTimeStamp(), mv.getAverage(), mv.getMinimum(), mv.getMaximum(), mv.getTotal(), mv.getCount());
+ return metricValue;
+ }
+
+ public static String getSubscriptionFromResourceId(String s) {
+ int i = s.indexOf("subscriptions/") + 14;
+ String subscriptionId = s.substring(i, s.indexOf("/", i));
+ return subscriptionId;
+ }
+
+
}
diff --git a/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/AzureMonitorMetricBatch.java b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/AzureMonitorMetricBatch.java
new file mode 100644
index 0000000000000..eae3fc3c99cb5
--- /dev/null
+++ b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/AzureMonitorMetricBatch.java
@@ -0,0 +1,127 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+// Code generated by Microsoft (R) AutoRest Code Generator.
+
+package com.azure.monitor.query.implementation.metricsbatch;
+
+import com.azure.core.http.HttpPipeline;
+import com.azure.core.http.HttpPipelineBuilder;
+import com.azure.core.http.policy.CookiePolicy;
+import com.azure.core.http.policy.RetryPolicy;
+import com.azure.core.http.policy.UserAgentPolicy;
+import com.azure.core.util.serializer.JacksonAdapter;
+import com.azure.core.util.serializer.SerializerAdapter;
+
+/** Initializes a new instance of the AzureMonitorMetricBatch type. */
+public final class AzureMonitorMetricBatch {
+ /**
+ * The regional endpoint to use, for example https://eastus.metrics.monitor.azure.com. The region should match the
+ * region of the requested resources. For global resources, the region should be 'global'.
+ */
+ private final String endpoint;
+
+ /**
+ * Gets The regional endpoint to use, for example https://eastus.metrics.monitor.azure.com. The region should match
+ * the region of the requested resources. For global resources, the region should be 'global'.
+ *
+ * @return the endpoint value.
+ */
+ public String getEndpoint() {
+ return this.endpoint;
+ }
+
+ /** Api Version. */
+ private final String apiVersion;
+
+ /**
+ * Gets Api Version.
+ *
+ * @return the apiVersion value.
+ */
+ public String getApiVersion() {
+ return this.apiVersion;
+ }
+
+ /** The HTTP pipeline to send requests through. */
+ private final HttpPipeline httpPipeline;
+
+ /**
+ * Gets The HTTP pipeline to send requests through.
+ *
+ * @return the httpPipeline value.
+ */
+ public HttpPipeline getHttpPipeline() {
+ return this.httpPipeline;
+ }
+
+ /** The serializer to serialize an object into a string. */
+ private final SerializerAdapter serializerAdapter;
+
+ /**
+ * Gets The serializer to serialize an object into a string.
+ *
+ * @return the serializerAdapter value.
+ */
+ public SerializerAdapter getSerializerAdapter() {
+ return this.serializerAdapter;
+ }
+
+ /** The Metrics object to access its operations. */
+ private final Metrics metrics;
+
+ /**
+ * Gets the Metrics object to access its operations.
+ *
+ * @return the Metrics object.
+ */
+ public Metrics getMetrics() {
+ return this.metrics;
+ }
+
+ /**
+ * Initializes an instance of AzureMonitorMetricBatch client.
+ *
+ * @param endpoint The regional endpoint to use, for example https://eastus.metrics.monitor.azure.com. The region
+ * should match the region of the requested resources. For global resources, the region should be 'global'.
+ * @param apiVersion Api Version.
+ */
+ AzureMonitorMetricBatch(String endpoint, String apiVersion) {
+ this(
+ new HttpPipelineBuilder()
+ .policies(new UserAgentPolicy(), new RetryPolicy(), new CookiePolicy())
+ .build(),
+ JacksonAdapter.createDefaultSerializerAdapter(),
+ endpoint,
+ apiVersion);
+ }
+
+ /**
+ * Initializes an instance of AzureMonitorMetricBatch client.
+ *
+ * @param httpPipeline The HTTP pipeline to send requests through.
+ * @param endpoint The regional endpoint to use, for example https://eastus.metrics.monitor.azure.com. The region
+ * should match the region of the requested resources. For global resources, the region should be 'global'.
+ * @param apiVersion Api Version.
+ */
+ AzureMonitorMetricBatch(HttpPipeline httpPipeline, String endpoint, String apiVersion) {
+ this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), endpoint, apiVersion);
+ }
+
+ /**
+ * Initializes an instance of AzureMonitorMetricBatch client.
+ *
+ * @param httpPipeline The HTTP pipeline to send requests through.
+ * @param serializerAdapter The serializer to serialize an object into a string.
+ * @param endpoint The regional endpoint to use, for example https://eastus.metrics.monitor.azure.com. The region
+ * should match the region of the requested resources. For global resources, the region should be 'global'.
+ * @param apiVersion Api Version.
+ */
+ AzureMonitorMetricBatch(
+ HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String endpoint, String apiVersion) {
+ this.httpPipeline = httpPipeline;
+ this.serializerAdapter = serializerAdapter;
+ this.endpoint = endpoint;
+ this.apiVersion = apiVersion;
+ this.metrics = new Metrics(this);
+ }
+}
diff --git a/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/AzureMonitorMetricBatchBuilder.java b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/AzureMonitorMetricBatchBuilder.java
new file mode 100644
index 0000000000000..8c117d9772fa9
--- /dev/null
+++ b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/AzureMonitorMetricBatchBuilder.java
@@ -0,0 +1,286 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+// Code generated by Microsoft (R) AutoRest Code Generator.
+
+package com.azure.monitor.query.implementation.metricsbatch;
+
+import com.azure.core.annotation.Generated;
+import com.azure.core.annotation.ServiceClientBuilder;
+import com.azure.core.client.traits.ConfigurationTrait;
+import com.azure.core.client.traits.EndpointTrait;
+import com.azure.core.client.traits.HttpTrait;
+import com.azure.core.client.traits.TokenCredentialTrait;
+import com.azure.core.credential.TokenCredential;
+import com.azure.core.http.HttpClient;
+import com.azure.core.http.HttpHeaders;
+import com.azure.core.http.HttpPipeline;
+import com.azure.core.http.HttpPipelineBuilder;
+import com.azure.core.http.HttpPipelinePosition;
+import com.azure.core.http.policy.AddDatePolicy;
+import com.azure.core.http.policy.AddHeadersFromContextPolicy;
+import com.azure.core.http.policy.AddHeadersPolicy;
+import com.azure.core.http.policy.BearerTokenAuthenticationPolicy;
+import com.azure.core.http.policy.CookiePolicy;
+import com.azure.core.http.policy.HttpLogOptions;
+import com.azure.core.http.policy.HttpLoggingPolicy;
+import com.azure.core.http.policy.HttpPipelinePolicy;
+import com.azure.core.http.policy.HttpPolicyProviders;
+import com.azure.core.http.policy.RequestIdPolicy;
+import com.azure.core.http.policy.RetryOptions;
+import com.azure.core.http.policy.RetryPolicy;
+import com.azure.core.http.policy.UserAgentPolicy;
+import com.azure.core.util.ClientOptions;
+import com.azure.core.util.Configuration;
+import com.azure.core.util.CoreUtils;
+import com.azure.core.util.builder.ClientBuilderUtil;
+import com.azure.core.util.serializer.JacksonAdapter;
+import com.azure.core.util.serializer.SerializerAdapter;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+/** A builder for creating a new instance of the AzureMonitorMetricBatch type. */
+@ServiceClientBuilder(serviceClients = {AzureMonitorMetricBatch.class})
+public final class AzureMonitorMetricBatchBuilder
+ implements HttpTrait,
+ ConfigurationTrait,
+ TokenCredentialTrait,
+ EndpointTrait {
+ @Generated private static final String SDK_NAME = "name";
+
+ @Generated private static final String SDK_VERSION = "version";
+
+ @Generated
+ private static final Map PROPERTIES = CoreUtils.getProperties("azure-monitor-query.properties");
+
+ @Generated private final List pipelinePolicies;
+
+ /** Create an instance of the AzureMonitorMetricBatchBuilder. */
+ @Generated
+ public AzureMonitorMetricBatchBuilder() {
+ this.pipelinePolicies = new ArrayList<>();
+ }
+
+ /*
+ * The HTTP pipeline to send requests through.
+ */
+ @Generated private HttpPipeline pipeline;
+
+ /** {@inheritDoc}. */
+ @Generated
+ @Override
+ public AzureMonitorMetricBatchBuilder pipeline(HttpPipeline pipeline) {
+ this.pipeline = pipeline;
+ return this;
+ }
+
+ /*
+ * The HTTP client used to send the request.
+ */
+ @Generated private HttpClient httpClient;
+
+ /** {@inheritDoc}. */
+ @Generated
+ @Override
+ public AzureMonitorMetricBatchBuilder httpClient(HttpClient httpClient) {
+ this.httpClient = httpClient;
+ return this;
+ }
+
+ /*
+ * The logging configuration for HTTP requests and responses.
+ */
+ @Generated private HttpLogOptions httpLogOptions;
+
+ /** {@inheritDoc}. */
+ @Generated
+ @Override
+ public AzureMonitorMetricBatchBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
+ this.httpLogOptions = httpLogOptions;
+ return this;
+ }
+
+ /*
+ * The client options such as application ID and custom headers to set on a request.
+ */
+ @Generated private ClientOptions clientOptions;
+
+ /** {@inheritDoc}. */
+ @Generated
+ @Override
+ public AzureMonitorMetricBatchBuilder clientOptions(ClientOptions clientOptions) {
+ this.clientOptions = clientOptions;
+ return this;
+ }
+
+ /*
+ * The retry options to configure retry policy for failed requests.
+ */
+ @Generated private RetryOptions retryOptions;
+
+ /** {@inheritDoc}. */
+ @Generated
+ @Override
+ public AzureMonitorMetricBatchBuilder retryOptions(RetryOptions retryOptions) {
+ this.retryOptions = retryOptions;
+ return this;
+ }
+
+ /** {@inheritDoc}. */
+ @Generated
+ @Override
+ public AzureMonitorMetricBatchBuilder addPolicy(HttpPipelinePolicy customPolicy) {
+ Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null.");
+ pipelinePolicies.add(customPolicy);
+ return this;
+ }
+
+ /*
+ * The configuration store that is used during construction of the service client.
+ */
+ @Generated private Configuration configuration;
+
+ /** {@inheritDoc}. */
+ @Generated
+ @Override
+ public AzureMonitorMetricBatchBuilder configuration(Configuration configuration) {
+ this.configuration = configuration;
+ return this;
+ }
+
+ /*
+ * The TokenCredential used for authentication.
+ */
+ @Generated private TokenCredential tokenCredential;
+
+ /** {@inheritDoc}. */
+ @Generated
+ @Override
+ public AzureMonitorMetricBatchBuilder credential(TokenCredential tokenCredential) {
+ this.tokenCredential = tokenCredential;
+ return this;
+ }
+
+ /*
+ * The service endpoint
+ */
+ @Generated private String endpoint;
+
+ /** {@inheritDoc}. */
+ @Generated
+ @Override
+ public AzureMonitorMetricBatchBuilder endpoint(String endpoint) {
+ this.endpoint = endpoint;
+ return this;
+ }
+
+ /*
+ * Api Version
+ */
+ @Generated private String apiVersion;
+
+ /**
+ * Sets Api Version.
+ *
+ * @param apiVersion the apiVersion value.
+ * @return the AzureMonitorMetricBatchBuilder.
+ */
+ @Generated
+ public AzureMonitorMetricBatchBuilder apiVersion(String apiVersion) {
+ this.apiVersion = apiVersion;
+ return this;
+ }
+
+ /*
+ * The serializer to serialize an object into a string
+ */
+ @Generated private SerializerAdapter serializerAdapter;
+
+ /**
+ * Sets The serializer to serialize an object into a string.
+ *
+ * @param serializerAdapter the serializerAdapter value.
+ * @return the AzureMonitorMetricBatchBuilder.
+ */
+ @Generated
+ public AzureMonitorMetricBatchBuilder serializerAdapter(SerializerAdapter serializerAdapter) {
+ this.serializerAdapter = serializerAdapter;
+ return this;
+ }
+
+ /*
+ * The retry policy that will attempt to retry failed requests, if applicable.
+ */
+ @Generated private RetryPolicy retryPolicy;
+
+ /**
+ * Sets The retry policy that will attempt to retry failed requests, if applicable.
+ *
+ * @param retryPolicy the retryPolicy value.
+ * @return the AzureMonitorMetricBatchBuilder.
+ */
+ @Generated
+ public AzureMonitorMetricBatchBuilder retryPolicy(RetryPolicy retryPolicy) {
+ this.retryPolicy = retryPolicy;
+ return this;
+ }
+
+ /**
+ * Builds an instance of AzureMonitorMetricBatch with the provided parameters.
+ *
+ * @return an instance of AzureMonitorMetricBatch.
+ */
+ @Generated
+ public AzureMonitorMetricBatch buildClient() {
+ HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline();
+ String localApiVersion = (apiVersion != null) ? apiVersion : "2023-05-01-preview";
+ SerializerAdapter localSerializerAdapter =
+ (serializerAdapter != null) ? serializerAdapter : JacksonAdapter.createDefaultSerializerAdapter();
+ AzureMonitorMetricBatch client =
+ new AzureMonitorMetricBatch(localPipeline, localSerializerAdapter, endpoint, localApiVersion);
+ return client;
+ }
+
+ @Generated
+ private HttpPipeline createHttpPipeline() {
+ Configuration buildConfiguration =
+ (configuration == null) ? Configuration.getGlobalConfiguration() : configuration;
+ HttpLogOptions localHttpLogOptions = this.httpLogOptions == null ? new HttpLogOptions() : this.httpLogOptions;
+ ClientOptions localClientOptions = this.clientOptions == null ? new ClientOptions() : this.clientOptions;
+ List policies = new ArrayList<>();
+ String clientName = PROPERTIES.getOrDefault(SDK_NAME, "UnknownName");
+ String clientVersion = PROPERTIES.getOrDefault(SDK_VERSION, "UnknownVersion");
+ String applicationId = CoreUtils.getApplicationId(localClientOptions, localHttpLogOptions);
+ policies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration));
+ policies.add(new RequestIdPolicy());
+ policies.add(new AddHeadersFromContextPolicy());
+ HttpHeaders headers = new HttpHeaders();
+ localClientOptions.getHeaders().forEach(header -> headers.set(header.getName(), header.getValue()));
+ if (headers.getSize() > 0) {
+ policies.add(new AddHeadersPolicy(headers));
+ }
+ this.pipelinePolicies.stream()
+ .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_CALL)
+ .forEach(p -> policies.add(p));
+ HttpPolicyProviders.addBeforeRetryPolicies(policies);
+ policies.add(ClientBuilderUtil.validateAndGetRetryPolicy(retryPolicy, retryOptions, new RetryPolicy()));
+ policies.add(new AddDatePolicy());
+ policies.add(new CookiePolicy());
+ if (tokenCredential != null) {
+ policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, String.format("https://metrics.monitor.azure.com/.default", endpoint)));
+ }
+ this.pipelinePolicies.stream()
+ .filter(p -> p.getPipelinePosition() == HttpPipelinePosition.PER_RETRY)
+ .forEach(p -> policies.add(p));
+ HttpPolicyProviders.addAfterRetryPolicies(policies);
+ policies.add(new HttpLoggingPolicy(httpLogOptions));
+ HttpPipeline httpPipeline =
+ new HttpPipelineBuilder()
+ .policies(policies.toArray(new HttpPipelinePolicy[0]))
+ .httpClient(httpClient)
+ .clientOptions(localClientOptions)
+ .build();
+ return httpPipeline;
+ }
+}
diff --git a/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/Metrics.java b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/Metrics.java
new file mode 100644
index 0000000000000..78830e0ad96b1
--- /dev/null
+++ b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/Metrics.java
@@ -0,0 +1,473 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+// Code generated by Microsoft (R) AutoRest Code Generator.
+
+package com.azure.monitor.query.implementation.metricsbatch;
+
+import com.azure.core.annotation.BodyParam;
+import com.azure.core.annotation.ExpectedResponses;
+import com.azure.core.annotation.HeaderParam;
+import com.azure.core.annotation.Host;
+import com.azure.core.annotation.HostParam;
+import com.azure.core.annotation.PathParam;
+import com.azure.core.annotation.Post;
+import com.azure.core.annotation.QueryParam;
+import com.azure.core.annotation.ReturnType;
+import com.azure.core.annotation.ServiceInterface;
+import com.azure.core.annotation.ServiceMethod;
+import com.azure.core.annotation.UnexpectedResponseExceptionType;
+import com.azure.core.http.rest.Response;
+import com.azure.core.http.rest.RestProxy;
+import com.azure.core.util.Context;
+import com.azure.core.util.FluxUtil;
+import com.azure.monitor.query.implementation.metricsbatch.models.AdditionalInfoErrorResponseException;
+import com.azure.monitor.query.implementation.metricsbatch.models.MetricResultsResponse;
+import com.azure.monitor.query.implementation.metricsbatch.models.ResourceIdList;
+import java.time.Duration;
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Collectors;
+import reactor.core.publisher.Mono;
+
+/** An instance of this class provides access to all the operations defined in Metrics. */
+public final class Metrics {
+ /** The proxy service used to perform REST calls. */
+ private final MetricsService service;
+
+ /** The service client containing this operation class. */
+ private final AzureMonitorMetricBatch client;
+
+ /**
+ * Initializes an instance of Metrics.
+ *
+ * @param client the instance of the service client containing this operation class.
+ */
+ Metrics(AzureMonitorMetricBatch client) {
+ this.service = RestProxy.create(MetricsService.class, client.getHttpPipeline(), client.getSerializerAdapter());
+ this.client = client;
+ }
+
+ /**
+ * The interface defining all the services for AzureMonitorMetricBatchMetrics to be used by the proxy service to
+ * perform REST calls.
+ */
+ @Host("{endpoint}")
+ @ServiceInterface(name = "AzureMonitorMetricBa")
+ public interface MetricsService {
+ @Post("/subscriptions/{subscriptionId}/metrics:getBatch")
+ @ExpectedResponses({200})
+ @UnexpectedResponseExceptionType(AdditionalInfoErrorResponseException.class)
+ Mono> batch(
+ @HostParam("endpoint") String endpoint,
+ @PathParam("subscriptionId") String subscriptionId,
+ @QueryParam("starttime") String starttime,
+ @QueryParam("endtime") String endtime,
+ @QueryParam("interval") Duration interval,
+ @QueryParam("metricnamespace") String metricnamespace,
+ @QueryParam("metricnames") String metricnames,
+ @QueryParam("aggregation") String aggregation,
+ @QueryParam("top") Integer top,
+ @QueryParam("orderby") String orderBy,
+ @QueryParam("filter") String filter,
+ @QueryParam("api-version") String apiVersion,
+ @BodyParam("application/json") ResourceIdList resourceIds,
+ @HeaderParam("Accept") String accept,
+ Context context);
+
+ @Post("/subscriptions/{subscriptionId}/metrics:getBatch")
+ @ExpectedResponses({200})
+ @UnexpectedResponseExceptionType(AdditionalInfoErrorResponseException.class)
+ Response batchSync(
+ @HostParam("endpoint") String endpoint,
+ @PathParam("subscriptionId") String subscriptionId,
+ @QueryParam("starttime") String starttime,
+ @QueryParam("endtime") String endtime,
+ @QueryParam("interval") Duration interval,
+ @QueryParam("metricnamespace") String metricnamespace,
+ @QueryParam("metricnames") String metricnames,
+ @QueryParam("aggregation") String aggregation,
+ @QueryParam("top") Integer top,
+ @QueryParam("orderby") String orderBy,
+ @QueryParam("filter") String filter,
+ @QueryParam("api-version") String apiVersion,
+ @BodyParam("application/json") ResourceIdList resourceIds,
+ @HeaderParam("Accept") String accept,
+ Context context);
+ }
+
+ /**
+ * Lists the metric values for multiple resources.
+ *
+ * @param subscriptionId The subscription identifier for the resources in this batch.
+ * @param metricnamespace Metric namespace that contains the requested metric names.
+ * @param metricnames The names of the metrics (comma separated) to retrieve.
+ * @param resourceIds The comma separated list of resource IDs to query metrics for.
+ * @param starttime The start time of the query. It is a string in the format 'yyyy-MM-ddTHH:mm:ss.fffZ'. If you
+ * have specified the endtime parameter, then this parameter is required. If only starttime is specified, then
+ * endtime defaults to the current time. If no time interval is specified, the default is 1 hour.
+ * @param endtime The end time of the query. It is a string in the format 'yyyy-MM-ddTHH:mm:ss.fffZ'.
+ * @param interval The interval (i.e. timegrain) of the query. *Examples: PT15M, PT1H, P1D*.
+ * @param aggregation The list of aggregation types (comma separated) to retrieve. *Examples: average, minimum,
+ * maximum*.
+ * @param top The maximum number of records to retrieve per resource ID in the request. Valid only if filter is
+ * specified. Defaults to 10.
+ * @param orderBy The aggregation to use for sorting results and the direction of the sort. Only one order can be
+ * specified. *Examples: sum asc*.
+ * @param filter The filter is used to reduce the set of metric data returned.<br>Example:<br>Metric
+ * contains metadata A, B and C.<br>- Return all time series of C where A = a1 and B = b1 or
+ * b2<br>**filter=A eq ‘a1’ and B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**<br>- Invalid
+ * variant:<br>**filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**<br>This is invalid
+ * because the logical or operator cannot separate two different metadata names.<br>- Return all time
+ * series where A = a1, B = b1 and C = c1:<br>**filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘c1’**<br>-
+ * Return all time series where A = a1<br>**filter=A eq ‘a1’ and B eq ‘*’ and C eq ‘*’**.
+ * @throws IllegalArgumentException thrown if parameters fail the validation.
+ * @throws AdditionalInfoErrorResponseException thrown if the request is rejected by server.
+ * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
+ * @return the metrics result for a resource along with {@link Response} on successful completion of {@link Mono}.
+ */
+ @ServiceMethod(returns = ReturnType.SINGLE)
+ public Mono> batchWithResponseAsync(
+ String subscriptionId,
+ String metricnamespace,
+ List metricnames,
+ ResourceIdList resourceIds,
+ String starttime,
+ String endtime,
+ Duration interval,
+ String aggregation,
+ Integer top,
+ String orderBy,
+ String filter) {
+ final String accept = "application/json";
+ String metricnamesConverted =
+ metricnames.stream().map(value -> Objects.toString(value, "")).collect(Collectors.joining(","));
+ return FluxUtil.withContext(
+ context ->
+ service.batch(
+ this.client.getEndpoint(),
+ subscriptionId,
+ starttime,
+ endtime,
+ interval,
+ metricnamespace,
+ metricnamesConverted,
+ aggregation,
+ top,
+ orderBy,
+ filter,
+ this.client.getApiVersion(),
+ resourceIds,
+ accept,
+ context));
+ }
+
+ /**
+ * Lists the metric values for multiple resources.
+ *
+ * @param subscriptionId The subscription identifier for the resources in this batch.
+ * @param metricnamespace Metric namespace that contains the requested metric names.
+ * @param metricnames The names of the metrics (comma separated) to retrieve.
+ * @param resourceIds The comma separated list of resource IDs to query metrics for.
+ * @param starttime The start time of the query. It is a string in the format 'yyyy-MM-ddTHH:mm:ss.fffZ'. If you
+ * have specified the endtime parameter, then this parameter is required. If only starttime is specified, then
+ * endtime defaults to the current time. If no time interval is specified, the default is 1 hour.
+ * @param endtime The end time of the query. It is a string in the format 'yyyy-MM-ddTHH:mm:ss.fffZ'.
+ * @param interval The interval (i.e. timegrain) of the query. *Examples: PT15M, PT1H, P1D*.
+ * @param aggregation The list of aggregation types (comma separated) to retrieve. *Examples: average, minimum,
+ * maximum*.
+ * @param top The maximum number of records to retrieve per resource ID in the request. Valid only if filter is
+ * specified. Defaults to 10.
+ * @param orderBy The aggregation to use for sorting results and the direction of the sort. Only one order can be
+ * specified. *Examples: sum asc*.
+ * @param filter The filter is used to reduce the set of metric data returned.<br>Example:<br>Metric
+ * contains metadata A, B and C.<br>- Return all time series of C where A = a1 and B = b1 or
+ * b2<br>**filter=A eq ‘a1’ and B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**<br>- Invalid
+ * variant:<br>**filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**<br>This is invalid
+ * because the logical or operator cannot separate two different metadata names.<br>- Return all time
+ * series where A = a1, B = b1 and C = c1:<br>**filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘c1’**<br>-
+ * Return all time series where A = a1<br>**filter=A eq ‘a1’ and B eq ‘*’ and C eq ‘*’**.
+ * @param context The context to associate with this operation.
+ * @throws IllegalArgumentException thrown if parameters fail the validation.
+ * @throws AdditionalInfoErrorResponseException thrown if the request is rejected by server.
+ * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
+ * @return the metrics result for a resource along with {@link Response} on successful completion of {@link Mono}.
+ */
+ @ServiceMethod(returns = ReturnType.SINGLE)
+ public Mono> batchWithResponseAsync(
+ String subscriptionId,
+ String metricnamespace,
+ List metricnames,
+ ResourceIdList resourceIds,
+ String starttime,
+ String endtime,
+ Duration interval,
+ String aggregation,
+ Integer top,
+ String orderBy,
+ String filter,
+ Context context) {
+ final String accept = "application/json";
+ String metricnamesConverted =
+ metricnames.stream().map(value -> Objects.toString(value, "")).collect(Collectors.joining(","));
+ return service.batch(
+ this.client.getEndpoint(),
+ subscriptionId,
+ starttime,
+ endtime,
+ interval,
+ metricnamespace,
+ metricnamesConverted,
+ aggregation,
+ top,
+ orderBy,
+ filter,
+ this.client.getApiVersion(),
+ resourceIds,
+ accept,
+ context);
+ }
+
+ /**
+ * Lists the metric values for multiple resources.
+ *
+ * @param subscriptionId The subscription identifier for the resources in this batch.
+ * @param metricnamespace Metric namespace that contains the requested metric names.
+ * @param metricnames The names of the metrics (comma separated) to retrieve.
+ * @param resourceIds The comma separated list of resource IDs to query metrics for.
+ * @param starttime The start time of the query. It is a string in the format 'yyyy-MM-ddTHH:mm:ss.fffZ'. If you
+ * have specified the endtime parameter, then this parameter is required. If only starttime is specified, then
+ * endtime defaults to the current time. If no time interval is specified, the default is 1 hour.
+ * @param endtime The end time of the query. It is a string in the format 'yyyy-MM-ddTHH:mm:ss.fffZ'.
+ * @param interval The interval (i.e. timegrain) of the query. *Examples: PT15M, PT1H, P1D*.
+ * @param aggregation The list of aggregation types (comma separated) to retrieve. *Examples: average, minimum,
+ * maximum*.
+ * @param top The maximum number of records to retrieve per resource ID in the request. Valid only if filter is
+ * specified. Defaults to 10.
+ * @param orderBy The aggregation to use for sorting results and the direction of the sort. Only one order can be
+ * specified. *Examples: sum asc*.
+ * @param filter The filter is used to reduce the set of metric data returned.<br>Example:<br>Metric
+ * contains metadata A, B and C.<br>- Return all time series of C where A = a1 and B = b1 or
+ * b2<br>**filter=A eq ‘a1’ and B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**<br>- Invalid
+ * variant:<br>**filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**<br>This is invalid
+ * because the logical or operator cannot separate two different metadata names.<br>- Return all time
+ * series where A = a1, B = b1 and C = c1:<br>**filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘c1’**<br>-
+ * Return all time series where A = a1<br>**filter=A eq ‘a1’ and B eq ‘*’ and C eq ‘*’**.
+ * @throws IllegalArgumentException thrown if parameters fail the validation.
+ * @throws AdditionalInfoErrorResponseException thrown if the request is rejected by server.
+ * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
+ * @return the metrics result for a resource on successful completion of {@link Mono}.
+ */
+ @ServiceMethod(returns = ReturnType.SINGLE)
+ public Mono batchAsync(
+ String subscriptionId,
+ String metricnamespace,
+ List metricnames,
+ ResourceIdList resourceIds,
+ String starttime,
+ String endtime,
+ Duration interval,
+ String aggregation,
+ Integer top,
+ String orderBy,
+ String filter) {
+ return batchWithResponseAsync(
+ subscriptionId,
+ metricnamespace,
+ metricnames,
+ resourceIds,
+ starttime,
+ endtime,
+ interval,
+ aggregation,
+ top,
+ orderBy,
+ filter)
+ .flatMap(res -> Mono.justOrEmpty(res.getValue()));
+ }
+
+ /**
+ * Lists the metric values for multiple resources.
+ *
+ * @param subscriptionId The subscription identifier for the resources in this batch.
+ * @param metricnamespace Metric namespace that contains the requested metric names.
+ * @param metricnames The names of the metrics (comma separated) to retrieve.
+ * @param resourceIds The comma separated list of resource IDs to query metrics for.
+ * @param starttime The start time of the query. It is a string in the format 'yyyy-MM-ddTHH:mm:ss.fffZ'. If you
+ * have specified the endtime parameter, then this parameter is required. If only starttime is specified, then
+ * endtime defaults to the current time. If no time interval is specified, the default is 1 hour.
+ * @param endtime The end time of the query. It is a string in the format 'yyyy-MM-ddTHH:mm:ss.fffZ'.
+ * @param interval The interval (i.e. timegrain) of the query. *Examples: PT15M, PT1H, P1D*.
+ * @param aggregation The list of aggregation types (comma separated) to retrieve. *Examples: average, minimum,
+ * maximum*.
+ * @param top The maximum number of records to retrieve per resource ID in the request. Valid only if filter is
+ * specified. Defaults to 10.
+ * @param orderBy The aggregation to use for sorting results and the direction of the sort. Only one order can be
+ * specified. *Examples: sum asc*.
+ * @param filter The filter is used to reduce the set of metric data returned.<br>Example:<br>Metric
+ * contains metadata A, B and C.<br>- Return all time series of C where A = a1 and B = b1 or
+ * b2<br>**filter=A eq ‘a1’ and B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**<br>- Invalid
+ * variant:<br>**filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**<br>This is invalid
+ * because the logical or operator cannot separate two different metadata names.<br>- Return all time
+ * series where A = a1, B = b1 and C = c1:<br>**filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘c1’**<br>-
+ * Return all time series where A = a1<br>**filter=A eq ‘a1’ and B eq ‘*’ and C eq ‘*’**.
+ * @param context The context to associate with this operation.
+ * @throws IllegalArgumentException thrown if parameters fail the validation.
+ * @throws AdditionalInfoErrorResponseException thrown if the request is rejected by server.
+ * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
+ * @return the metrics result for a resource on successful completion of {@link Mono}.
+ */
+ @ServiceMethod(returns = ReturnType.SINGLE)
+ public Mono batchAsync(
+ String subscriptionId,
+ String metricnamespace,
+ List metricnames,
+ ResourceIdList resourceIds,
+ String starttime,
+ String endtime,
+ Duration interval,
+ String aggregation,
+ Integer top,
+ String orderBy,
+ String filter,
+ Context context) {
+ return batchWithResponseAsync(
+ subscriptionId,
+ metricnamespace,
+ metricnames,
+ resourceIds,
+ starttime,
+ endtime,
+ interval,
+ aggregation,
+ top,
+ orderBy,
+ filter,
+ context)
+ .flatMap(res -> Mono.justOrEmpty(res.getValue()));
+ }
+
+ /**
+ * Lists the metric values for multiple resources.
+ *
+ * @param subscriptionId The subscription identifier for the resources in this batch.
+ * @param metricnamespace Metric namespace that contains the requested metric names.
+ * @param metricnames The names of the metrics (comma separated) to retrieve.
+ * @param resourceIds The comma separated list of resource IDs to query metrics for.
+ * @param starttime The start time of the query. It is a string in the format 'yyyy-MM-ddTHH:mm:ss.fffZ'. If you
+ * have specified the endtime parameter, then this parameter is required. If only starttime is specified, then
+ * endtime defaults to the current time. If no time interval is specified, the default is 1 hour.
+ * @param endtime The end time of the query. It is a string in the format 'yyyy-MM-ddTHH:mm:ss.fffZ'.
+ * @param interval The interval (i.e. timegrain) of the query. *Examples: PT15M, PT1H, P1D*.
+ * @param aggregation The list of aggregation types (comma separated) to retrieve. *Examples: average, minimum,
+ * maximum*.
+ * @param top The maximum number of records to retrieve per resource ID in the request. Valid only if filter is
+ * specified. Defaults to 10.
+ * @param orderBy The aggregation to use for sorting results and the direction of the sort. Only one order can be
+ * specified. *Examples: sum asc*.
+ * @param filter The filter is used to reduce the set of metric data returned.<br>Example:<br>Metric
+ * contains metadata A, B and C.<br>- Return all time series of C where A = a1 and B = b1 or
+ * b2<br>**filter=A eq ‘a1’ and B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**<br>- Invalid
+ * variant:<br>**filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**<br>This is invalid
+ * because the logical or operator cannot separate two different metadata names.<br>- Return all time
+ * series where A = a1, B = b1 and C = c1:<br>**filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘c1’**<br>-
+ * Return all time series where A = a1<br>**filter=A eq ‘a1’ and B eq ‘*’ and C eq ‘*’**.
+ * @param context The context to associate with this operation.
+ * @throws IllegalArgumentException thrown if parameters fail the validation.
+ * @throws AdditionalInfoErrorResponseException thrown if the request is rejected by server.
+ * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
+ * @return the metrics result for a resource along with {@link Response}.
+ */
+ @ServiceMethod(returns = ReturnType.SINGLE)
+ public Response batchWithResponse(
+ String subscriptionId,
+ String metricnamespace,
+ List metricnames,
+ ResourceIdList resourceIds,
+ String starttime,
+ String endtime,
+ Duration interval,
+ String aggregation,
+ Integer top,
+ String orderBy,
+ String filter,
+ Context context) {
+ final String accept = "application/json";
+ String metricnamesConverted =
+ metricnames.stream().map(value -> Objects.toString(value, "")).collect(Collectors.joining(","));
+ return service.batchSync(
+ this.client.getEndpoint(),
+ subscriptionId,
+ starttime,
+ endtime,
+ interval,
+ metricnamespace,
+ metricnamesConverted,
+ aggregation,
+ top,
+ orderBy,
+ filter,
+ this.client.getApiVersion(),
+ resourceIds,
+ accept,
+ context);
+ }
+
+ /**
+ * Lists the metric values for multiple resources.
+ *
+ * @param subscriptionId The subscription identifier for the resources in this batch.
+ * @param metricnamespace Metric namespace that contains the requested metric names.
+ * @param metricnames The names of the metrics (comma separated) to retrieve.
+ * @param resourceIds The comma separated list of resource IDs to query metrics for.
+ * @param starttime The start time of the query. It is a string in the format 'yyyy-MM-ddTHH:mm:ss.fffZ'. If you
+ * have specified the endtime parameter, then this parameter is required. If only starttime is specified, then
+ * endtime defaults to the current time. If no time interval is specified, the default is 1 hour.
+ * @param endtime The end time of the query. It is a string in the format 'yyyy-MM-ddTHH:mm:ss.fffZ'.
+ * @param interval The interval (i.e. timegrain) of the query. *Examples: PT15M, PT1H, P1D*.
+ * @param aggregation The list of aggregation types (comma separated) to retrieve. *Examples: average, minimum,
+ * maximum*.
+ * @param top The maximum number of records to retrieve per resource ID in the request. Valid only if filter is
+ * specified. Defaults to 10.
+ * @param orderBy The aggregation to use for sorting results and the direction of the sort. Only one order can be
+ * specified. *Examples: sum asc*.
+ * @param filter The filter is used to reduce the set of metric data returned.<br>Example:<br>Metric
+ * contains metadata A, B and C.<br>- Return all time series of C where A = a1 and B = b1 or
+ * b2<br>**filter=A eq ‘a1’ and B eq ‘b1’ or B eq ‘b2’ and C eq ‘*’**<br>- Invalid
+ * variant:<br>**filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘*’ or B = ‘b2’**<br>This is invalid
+ * because the logical or operator cannot separate two different metadata names.<br>- Return all time
+ * series where A = a1, B = b1 and C = c1:<br>**filter=A eq ‘a1’ and B eq ‘b1’ and C eq ‘c1’**<br>-
+ * Return all time series where A = a1<br>**filter=A eq ‘a1’ and B eq ‘*’ and C eq ‘*’**.
+ * @throws IllegalArgumentException thrown if parameters fail the validation.
+ * @throws AdditionalInfoErrorResponseException thrown if the request is rejected by server.
+ * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
+ * @return the metrics result for a resource.
+ */
+ @ServiceMethod(returns = ReturnType.SINGLE)
+ public MetricResultsResponse batch(
+ String subscriptionId,
+ String metricnamespace,
+ List metricnames,
+ ResourceIdList resourceIds,
+ String starttime,
+ String endtime,
+ Duration interval,
+ String aggregation,
+ Integer top,
+ String orderBy,
+ String filter) {
+ return batchWithResponse(
+ subscriptionId,
+ metricnamespace,
+ metricnames,
+ resourceIds,
+ starttime,
+ endtime,
+ interval,
+ aggregation,
+ top,
+ orderBy,
+ filter,
+ Context.NONE)
+ .getValue();
+ }
+}
diff --git a/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/AdditionalInfoErrorResponse.java b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/AdditionalInfoErrorResponse.java
new file mode 100644
index 0000000000000..506b71bec788c
--- /dev/null
+++ b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/AdditionalInfoErrorResponse.java
@@ -0,0 +1,39 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+// Code generated by Microsoft (R) AutoRest Code Generator.
+
+package com.azure.monitor.query.implementation.metricsbatch.models;
+
+import com.azure.core.annotation.Immutable;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+/** The response to a metrics query that results in a bad request, with optional additional information. */
+@Immutable
+public final class AdditionalInfoErrorResponse {
+ /*
+ * Top level error object that contains all relevant information.
+ */
+ @JsonProperty(value = "error", required = true)
+ private AdditionalInfoErrorResponseError error;
+
+ /**
+ * Creates an instance of AdditionalInfoErrorResponse class.
+ *
+ * @param error the error value to set.
+ */
+ @JsonCreator
+ public AdditionalInfoErrorResponse(
+ @JsonProperty(value = "error", required = true) AdditionalInfoErrorResponseError error) {
+ this.error = error;
+ }
+
+ /**
+ * Get the error property: Top level error object that contains all relevant information.
+ *
+ * @return the error value.
+ */
+ public AdditionalInfoErrorResponseError getError() {
+ return this.error;
+ }
+}
diff --git a/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/AdditionalInfoErrorResponseError.java b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/AdditionalInfoErrorResponseError.java
new file mode 100644
index 0000000000000..1c7975f2ff968
--- /dev/null
+++ b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/AdditionalInfoErrorResponseError.java
@@ -0,0 +1,85 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+// Code generated by Microsoft (R) AutoRest Code Generator.
+
+package com.azure.monitor.query.implementation.metricsbatch.models;
+
+import com.azure.core.annotation.Fluent;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import java.util.List;
+
+/** Top level error object that contains all relevant information. */
+@Fluent
+public final class AdditionalInfoErrorResponseError {
+ /*
+ * Additional information about the error
+ */
+ @JsonProperty(value = "additionalInfo")
+ private List additionalInfo;
+
+ /*
+ * Error code
+ */
+ @JsonProperty(value = "code", required = true)
+ private String code;
+
+ /*
+ * Error message indicating why the operation failed.
+ */
+ @JsonProperty(value = "message", required = true)
+ private String message;
+
+ /**
+ * Creates an instance of AdditionalInfoErrorResponseError class.
+ *
+ * @param code the code value to set.
+ * @param message the message value to set.
+ */
+ @JsonCreator
+ public AdditionalInfoErrorResponseError(
+ @JsonProperty(value = "code", required = true) String code,
+ @JsonProperty(value = "message", required = true) String message) {
+ this.code = code;
+ this.message = message;
+ }
+
+ /**
+ * Get the additionalInfo property: Additional information about the error.
+ *
+ * @return the additionalInfo value.
+ */
+ public List getAdditionalInfo() {
+ return this.additionalInfo;
+ }
+
+ /**
+ * Set the additionalInfo property: Additional information about the error.
+ *
+ * @param additionalInfo the additionalInfo value to set.
+ * @return the AdditionalInfoErrorResponseError object itself.
+ */
+ public AdditionalInfoErrorResponseError setAdditionalInfo(
+ List additionalInfo) {
+ this.additionalInfo = additionalInfo;
+ return this;
+ }
+
+ /**
+ * Get the code property: Error code.
+ *
+ * @return the code value.
+ */
+ public String getCode() {
+ return this.code;
+ }
+
+ /**
+ * Get the message property: Error message indicating why the operation failed.
+ *
+ * @return the message value.
+ */
+ public String getMessage() {
+ return this.message;
+ }
+}
diff --git a/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/AdditionalInfoErrorResponseErrorAdditionalInfoItem.java b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/AdditionalInfoErrorResponseErrorAdditionalInfoItem.java
new file mode 100644
index 0000000000000..2ee78f181027c
--- /dev/null
+++ b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/AdditionalInfoErrorResponseErrorAdditionalInfoItem.java
@@ -0,0 +1,67 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+// Code generated by Microsoft (R) AutoRest Code Generator.
+
+package com.azure.monitor.query.implementation.metricsbatch.models;
+
+import com.azure.core.annotation.Fluent;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+/** The AdditionalInfoErrorResponseErrorAdditionalInfoItem model. */
+@Fluent
+public final class AdditionalInfoErrorResponseErrorAdditionalInfoItem {
+ /*
+ * The type of the info property (e.g. string).
+ */
+ @JsonProperty(value = "type")
+ private String type;
+
+ /*
+ * Additional information related to the error.
+ */
+ @JsonProperty(value = "info")
+ private String info;
+
+ /** Creates an instance of AdditionalInfoErrorResponseErrorAdditionalInfoItem class. */
+ public AdditionalInfoErrorResponseErrorAdditionalInfoItem() {}
+
+ /**
+ * Get the type property: The type of the info property (e.g. string).
+ *
+ * @return the type value.
+ */
+ public String getType() {
+ return this.type;
+ }
+
+ /**
+ * Set the type property: The type of the info property (e.g. string).
+ *
+ * @param type the type value to set.
+ * @return the AdditionalInfoErrorResponseErrorAdditionalInfoItem object itself.
+ */
+ public AdditionalInfoErrorResponseErrorAdditionalInfoItem setType(String type) {
+ this.type = type;
+ return this;
+ }
+
+ /**
+ * Get the info property: Additional information related to the error.
+ *
+ * @return the info value.
+ */
+ public String getInfo() {
+ return this.info;
+ }
+
+ /**
+ * Set the info property: Additional information related to the error.
+ *
+ * @param info the info value to set.
+ * @return the AdditionalInfoErrorResponseErrorAdditionalInfoItem object itself.
+ */
+ public AdditionalInfoErrorResponseErrorAdditionalInfoItem setInfo(String info) {
+ this.info = info;
+ return this;
+ }
+}
diff --git a/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/AdditionalInfoErrorResponseException.java b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/AdditionalInfoErrorResponseException.java
new file mode 100644
index 0000000000000..0f798e0e9875a
--- /dev/null
+++ b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/AdditionalInfoErrorResponseException.java
@@ -0,0 +1,39 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+// Code generated by Microsoft (R) AutoRest Code Generator.
+
+package com.azure.monitor.query.implementation.metricsbatch.models;
+
+import com.azure.core.exception.HttpResponseException;
+import com.azure.core.http.HttpResponse;
+
+/** Exception thrown for an invalid response with AdditionalInfoErrorResponse information. */
+public final class AdditionalInfoErrorResponseException extends HttpResponseException {
+ /**
+ * Initializes a new instance of the AdditionalInfoErrorResponseException class.
+ *
+ * @param message the exception message or the response content if a message is not available.
+ * @param response the HTTP response.
+ */
+ public AdditionalInfoErrorResponseException(String message, HttpResponse response) {
+ super(message, response);
+ }
+
+ /**
+ * Initializes a new instance of the AdditionalInfoErrorResponseException class.
+ *
+ * @param message the exception message or the response content if a message is not available.
+ * @param response the HTTP response.
+ * @param value the deserialized response value.
+ */
+ public AdditionalInfoErrorResponseException(
+ String message, HttpResponse response, AdditionalInfoErrorResponse value) {
+ super(message, response, value);
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ public AdditionalInfoErrorResponse getValue() {
+ return (AdditionalInfoErrorResponse) super.getValue();
+ }
+}
diff --git a/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/LocalizableString.java b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/LocalizableString.java
new file mode 100644
index 0000000000000..4c6d139eec4d5
--- /dev/null
+++ b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/LocalizableString.java
@@ -0,0 +1,64 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+// Code generated by Microsoft (R) AutoRest Code Generator.
+
+package com.azure.monitor.query.implementation.metricsbatch.models;
+
+import com.azure.core.annotation.Fluent;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+/** The localizable string class. */
+@Fluent
+public final class LocalizableString {
+ /*
+ * The invariant value.
+ */
+ @JsonProperty(value = "value", required = true)
+ private String value;
+
+ /*
+ * The display name.
+ */
+ @JsonProperty(value = "localizedValue")
+ private String localizedValue;
+
+ /**
+ * Creates an instance of LocalizableString class.
+ *
+ * @param value the value value to set.
+ */
+ @JsonCreator
+ public LocalizableString(@JsonProperty(value = "value", required = true) String value) {
+ this.value = value;
+ }
+
+ /**
+ * Get the value property: The invariant value.
+ *
+ * @return the value value.
+ */
+ public String getValue() {
+ return this.value;
+ }
+
+ /**
+ * Get the localizedValue property: The display name.
+ *
+ * @return the localizedValue value.
+ */
+ public String getLocalizedValue() {
+ return this.localizedValue;
+ }
+
+ /**
+ * Set the localizedValue property: The display name.
+ *
+ * @param localizedValue the localizedValue value to set.
+ * @return the LocalizableString object itself.
+ */
+ public LocalizableString setLocalizedValue(String localizedValue) {
+ this.localizedValue = localizedValue;
+ return this;
+ }
+}
diff --git a/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/MetadataValue.java b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/MetadataValue.java
new file mode 100644
index 0000000000000..fe9cdf2ffd848
--- /dev/null
+++ b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/MetadataValue.java
@@ -0,0 +1,67 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+// Code generated by Microsoft (R) AutoRest Code Generator.
+
+package com.azure.monitor.query.implementation.metricsbatch.models;
+
+import com.azure.core.annotation.Fluent;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+/** Represents a metric metadata value. */
+@Fluent
+public final class MetadataValue {
+ /*
+ * The name of the metadata.
+ */
+ @JsonProperty(value = "name")
+ private LocalizableString name;
+
+ /*
+ * The value of the metadata.
+ */
+ @JsonProperty(value = "value")
+ private String value;
+
+ /** Creates an instance of MetadataValue class. */
+ public MetadataValue() {}
+
+ /**
+ * Get the name property: The name of the metadata.
+ *
+ * @return the name value.
+ */
+ public LocalizableString getName() {
+ return this.name;
+ }
+
+ /**
+ * Set the name property: The name of the metadata.
+ *
+ * @param name the name value to set.
+ * @return the MetadataValue object itself.
+ */
+ public MetadataValue setName(LocalizableString name) {
+ this.name = name;
+ return this;
+ }
+
+ /**
+ * Get the value property: The value of the metadata.
+ *
+ * @return the value value.
+ */
+ public String getValue() {
+ return this.value;
+ }
+
+ /**
+ * Set the value property: The value of the metadata.
+ *
+ * @param value the value value to set.
+ * @return the MetadataValue object itself.
+ */
+ public MetadataValue setValue(String value) {
+ this.value = value;
+ return this;
+ }
+}
diff --git a/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/Metric.java b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/Metric.java
new file mode 100644
index 0000000000000..47300a029c20c
--- /dev/null
+++ b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/Metric.java
@@ -0,0 +1,182 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+// Code generated by Microsoft (R) AutoRest Code Generator.
+
+package com.azure.monitor.query.implementation.metricsbatch.models;
+
+import com.azure.core.annotation.Fluent;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import java.util.List;
+
+/** The result data of a query. */
+@Fluent
+public final class Metric {
+ /*
+ * The metric Id.
+ */
+ @JsonProperty(value = "id", required = true)
+ private String id;
+
+ /*
+ * The name and the display name of the metric, i.e. it is localizable string.
+ */
+ @JsonProperty(value = "name", required = true)
+ private LocalizableString name;
+
+ /*
+ * Description of this metric
+ */
+ @JsonProperty(value = "displayDescription")
+ private String displayDescription;
+
+ /*
+ * The resource type of the metric resource.
+ */
+ @JsonProperty(value = "type", required = true)
+ private String type;
+
+ /*
+ * The unit of the metric.
+ */
+ @JsonProperty(value = "unit", required = true)
+ private MetricUnit unit;
+
+ /*
+ * The time series returned when a data query is performed.
+ */
+ @JsonProperty(value = "timeseries", required = true)
+ private List timeseries;
+
+ /*
+ * 'Success' or the error details on query failures for this metric.
+ */
+ @JsonProperty(value = "errorCode")
+ private String errorCode;
+
+ /*
+ * Error message encountered querying this specific metric.
+ */
+ @JsonProperty(value = "errorMessage")
+ private String errorMessage;
+
+ /**
+ * Creates an instance of Metric class.
+ *
+ * @param id the id value to set.
+ * @param name the name value to set.
+ * @param displayDescription the displayDescription value to set.
+ * @param type the type value to set.
+ * @param unit the unit value to set.
+ * @param timeseries the timeseries value to set.
+ */
+ @JsonCreator
+ public Metric(
+ @JsonProperty(value = "id", required = true) String id,
+ @JsonProperty(value = "name", required = true) LocalizableString name,
+ @JsonProperty(value = "displayDescription") String displayDescription,
+ @JsonProperty(value = "type", required = true) String type,
+ @JsonProperty(value = "unit", required = true) MetricUnit unit,
+ @JsonProperty(value = "timeseries", required = true) List timeseries) {
+ this.id = id;
+ this.name = name;
+ this.displayDescription = displayDescription;
+ this.type = type;
+ this.unit = unit;
+ this.timeseries = timeseries;
+ }
+
+ /**
+ * Get the id property: The metric Id.
+ *
+ * @return the id value.
+ */
+ public String getId() {
+ return this.id;
+ }
+
+ /**
+ * Get the name property: The name and the display name of the metric, i.e. it is localizable string.
+ *
+ * @return the name value.
+ */
+ public LocalizableString getName() {
+ return this.name;
+ }
+
+ /**
+ * Get the displayDescription property: Description of this metric.
+ *
+ * @return the displayDescription value.
+ */
+ public String getDisplayDescription() {
+ return this.displayDescription;
+ }
+
+ /**
+ * Get the type property: The resource type of the metric resource.
+ *
+ * @return the type value.
+ */
+ public String getType() {
+ return this.type;
+ }
+
+ /**
+ * Get the unit property: The unit of the metric.
+ *
+ * @return the unit value.
+ */
+ public MetricUnit getUnit() {
+ return this.unit;
+ }
+
+ /**
+ * Get the timeseries property: The time series returned when a data query is performed.
+ *
+ * @return the timeseries value.
+ */
+ public List getTimeseries() {
+ return this.timeseries;
+ }
+
+ /**
+ * Get the errorCode property: 'Success' or the error details on query failures for this metric.
+ *
+ * @return the errorCode value.
+ */
+ public String getErrorCode() {
+ return this.errorCode;
+ }
+
+ /**
+ * Set the errorCode property: 'Success' or the error details on query failures for this metric.
+ *
+ * @param errorCode the errorCode value to set.
+ * @return the Metric object itself.
+ */
+ public Metric setErrorCode(String errorCode) {
+ this.errorCode = errorCode;
+ return this;
+ }
+
+ /**
+ * Get the errorMessage property: Error message encountered querying this specific metric.
+ *
+ * @return the errorMessage value.
+ */
+ public String getErrorMessage() {
+ return this.errorMessage;
+ }
+
+ /**
+ * Set the errorMessage property: Error message encountered querying this specific metric.
+ *
+ * @param errorMessage the errorMessage value to set.
+ * @return the Metric object itself.
+ */
+ public Metric setErrorMessage(String errorMessage) {
+ this.errorMessage = errorMessage;
+ return this;
+ }
+}
diff --git a/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/MetricResultsResponse.java b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/MetricResultsResponse.java
new file mode 100644
index 0000000000000..1fab1e984be93
--- /dev/null
+++ b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/MetricResultsResponse.java
@@ -0,0 +1,42 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+// Code generated by Microsoft (R) AutoRest Code Generator.
+
+package com.azure.monitor.query.implementation.metricsbatch.models;
+
+import com.azure.core.annotation.Fluent;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import java.util.List;
+
+/** The metrics result for a resource. */
+@Fluent
+public final class MetricResultsResponse {
+ /*
+ * The collection of metric data responses per resource, per metric.
+ */
+ @JsonProperty(value = "values")
+ private List values;
+
+ /** Creates an instance of MetricResultsResponse class. */
+ public MetricResultsResponse() {}
+
+ /**
+ * Get the values property: The collection of metric data responses per resource, per metric.
+ *
+ * @return the values value.
+ */
+ public List getValues() {
+ return this.values;
+ }
+
+ /**
+ * Set the values property: The collection of metric data responses per resource, per metric.
+ *
+ * @param values the values value to set.
+ * @return the MetricResultsResponse object itself.
+ */
+ public MetricResultsResponse setValues(List values) {
+ this.values = values;
+ return this;
+ }
+}
diff --git a/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/MetricResultsResponseValuesItem.java b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/MetricResultsResponseValuesItem.java
new file mode 100644
index 0000000000000..021e4318fe870
--- /dev/null
+++ b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/MetricResultsResponseValuesItem.java
@@ -0,0 +1,187 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+// Code generated by Microsoft (R) AutoRest Code Generator.
+
+package com.azure.monitor.query.implementation.metricsbatch.models;
+
+import com.azure.core.annotation.Fluent;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import java.time.Duration;
+import java.util.List;
+
+/** The MetricResultsResponseValuesItem model. */
+@Fluent
+public final class MetricResultsResponseValuesItem {
+ /*
+ * The start time, in datetime format, for which the data was retrieved.
+ */
+ @JsonProperty(value = "starttime", required = true)
+ private String starttime;
+
+ /*
+ * The end time, in datetime format, for which the data was retrieved.
+ */
+ @JsonProperty(value = "endtime", required = true)
+ private String endtime;
+
+ /*
+ * The interval (window size) for which the metric data was returned in. Follows the IS8601/RFC3339 duration format
+ * (e.g. 'P1D' for 1 day). This may be adjusted in the future and returned back from what was originally requested.
+ * This is not present if a metadata request was made.
+ */
+ @JsonProperty(value = "interval")
+ private Duration interval;
+
+ /*
+ * The namespace of the metrics been queried
+ */
+ @JsonProperty(value = "namespace")
+ private String namespace;
+
+ /*
+ * The region of the resource been queried for metrics.
+ */
+ @JsonProperty(value = "resourceregion")
+ private String resourceregion;
+
+ /*
+ * The resource that has been queried for metrics.
+ */
+ @JsonProperty(value = "resourceid")
+ private String resourceid;
+
+ /*
+ * The value of the collection.
+ */
+ @JsonProperty(value = "value", required = true)
+ private List value;
+
+ /**
+ * Creates an instance of MetricResultsResponseValuesItem class.
+ *
+ * @param starttime the starttime value to set.
+ * @param endtime the endtime value to set.
+ * @param value the value value to set.
+ */
+ @JsonCreator
+ public MetricResultsResponseValuesItem(
+ @JsonProperty(value = "starttime", required = true) String starttime,
+ @JsonProperty(value = "endtime", required = true) String endtime,
+ @JsonProperty(value = "value", required = true) List value) {
+ this.starttime = starttime;
+ this.endtime = endtime;
+ this.value = value;
+ }
+
+ /**
+ * Get the starttime property: The start time, in datetime format, for which the data was retrieved.
+ *
+ * @return the starttime value.
+ */
+ public String getStarttime() {
+ return this.starttime;
+ }
+
+ /**
+ * Get the endtime property: The end time, in datetime format, for which the data was retrieved.
+ *
+ * @return the endtime value.
+ */
+ public String getEndtime() {
+ return this.endtime;
+ }
+
+ /**
+ * Get the interval property: The interval (window size) for which the metric data was returned in. Follows the
+ * IS8601/RFC3339 duration format (e.g. 'P1D' for 1 day). This may be adjusted in the future and returned back from
+ * what was originally requested. This is not present if a metadata request was made.
+ *
+ * @return the interval value.
+ */
+ public Duration getInterval() {
+ return this.interval;
+ }
+
+ /**
+ * Set the interval property: The interval (window size) for which the metric data was returned in. Follows the
+ * IS8601/RFC3339 duration format (e.g. 'P1D' for 1 day). This may be adjusted in the future and returned back from
+ * what was originally requested. This is not present if a metadata request was made.
+ *
+ * @param interval the interval value to set.
+ * @return the MetricResultsResponseValuesItem object itself.
+ */
+ public MetricResultsResponseValuesItem setInterval(Duration interval) {
+ this.interval = interval;
+ return this;
+ }
+
+ /**
+ * Get the namespace property: The namespace of the metrics been queried.
+ *
+ * @return the namespace value.
+ */
+ public String getNamespace() {
+ return this.namespace;
+ }
+
+ /**
+ * Set the namespace property: The namespace of the metrics been queried.
+ *
+ * @param namespace the namespace value to set.
+ * @return the MetricResultsResponseValuesItem object itself.
+ */
+ public MetricResultsResponseValuesItem setNamespace(String namespace) {
+ this.namespace = namespace;
+ return this;
+ }
+
+ /**
+ * Get the resourceregion property: The region of the resource been queried for metrics.
+ *
+ * @return the resourceregion value.
+ */
+ public String getResourceregion() {
+ return this.resourceregion;
+ }
+
+ /**
+ * Set the resourceregion property: The region of the resource been queried for metrics.
+ *
+ * @param resourceregion the resourceregion value to set.
+ * @return the MetricResultsResponseValuesItem object itself.
+ */
+ public MetricResultsResponseValuesItem setResourceregion(String resourceregion) {
+ this.resourceregion = resourceregion;
+ return this;
+ }
+
+ /**
+ * Get the resourceid property: The resource that has been queried for metrics.
+ *
+ * @return the resourceid value.
+ */
+ public String getResourceid() {
+ return this.resourceid;
+ }
+
+ /**
+ * Set the resourceid property: The resource that has been queried for metrics.
+ *
+ * @param resourceid the resourceid value to set.
+ * @return the MetricResultsResponseValuesItem object itself.
+ */
+ public MetricResultsResponseValuesItem setResourceid(String resourceid) {
+ this.resourceid = resourceid;
+ return this;
+ }
+
+ /**
+ * Get the value property: The value of the collection.
+ *
+ * @return the value value.
+ */
+ public List getValue() {
+ return this.value;
+ }
+}
diff --git a/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/MetricUnit.java b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/MetricUnit.java
new file mode 100644
index 0000000000000..8948d315b896a
--- /dev/null
+++ b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/MetricUnit.java
@@ -0,0 +1,87 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+// Code generated by Microsoft (R) AutoRest Code Generator.
+
+package com.azure.monitor.query.implementation.metricsbatch.models;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonValue;
+
+/** The unit of the metric. */
+public enum MetricUnit {
+ /** Unit of raw quantity. */
+ COUNT("Count"),
+
+ /** Unit of memory in bytes. */
+ BYTES("Bytes"),
+
+ /** Unit of time in seconds. */
+ SECONDS("Seconds"),
+
+ /** Rate unit of raw quantity per second. */
+ COUNT_PER_SECOND("CountPerSecond"),
+
+ /** Rate unit of memory in bytes per second. */
+ BYTES_PER_SECOND("BytesPerSecond"),
+
+ /** Percentage unit. */
+ PERCENT("Percent"),
+
+ /** Unit of time in 1/1000th of a second. */
+ MILLI_SECONDS("MilliSeconds"),
+
+ /**
+ * Unit of data transfer or storage. It is the size of the data in bytes multiplied by the time it takes to transfer
+ * or store the data in seconds.
+ */
+ BYTE_SECONDS("ByteSeconds"),
+
+ /** No specified unit. */
+ UNSPECIFIED("Unspecified"),
+
+ /** Unit of processing power. */
+ CORES("Cores"),
+
+ /** Unit of processing power in 1/1000th of a CPU core. */
+ MILLI_CORES("MilliCores"),
+
+ /** Unit of processing power in one billionth of a CPU core. */
+ NANO_CORES("NanoCores"),
+
+ /** Rate unit of binary digits per second. */
+ BITS_PER_SECOND("BitsPerSecond");
+
+ /** The actual serialized value for a MetricUnit instance. */
+ private final String value;
+
+ MetricUnit(String value) {
+ this.value = value;
+ }
+
+ /**
+ * Parses a serialized value to a MetricUnit instance.
+ *
+ * @param value the serialized value to parse.
+ * @return the parsed MetricUnit object, or null if unable to parse.
+ */
+ @JsonCreator
+ public static MetricUnit fromString(String value) {
+ if (value == null) {
+ return null;
+ }
+ MetricUnit[] items = MetricUnit.values();
+ for (MetricUnit item : items) {
+ if (item.toString().equalsIgnoreCase(value)) {
+ return item;
+ }
+ }
+ return null;
+ }
+
+ /** {@inheritDoc} */
+ @JsonValue
+ @Override
+ public String toString() {
+ return this.value;
+ }
+}
diff --git a/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/MetricValue.java b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/MetricValue.java
new file mode 100644
index 0000000000000..48fceae0c8a2b
--- /dev/null
+++ b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/MetricValue.java
@@ -0,0 +1,172 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+// Code generated by Microsoft (R) AutoRest Code Generator.
+
+package com.azure.monitor.query.implementation.metricsbatch.models;
+
+import com.azure.core.annotation.Fluent;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import java.time.OffsetDateTime;
+
+/** Represents a metric value. */
+@Fluent
+public final class MetricValue {
+ /*
+ * The timestamp for the metric value in ISO 8601 format.
+ */
+ @JsonProperty(value = "timeStamp", required = true)
+ private OffsetDateTime timeStamp;
+
+ /*
+ * The average value in the time range.
+ */
+ @JsonProperty(value = "average")
+ private Double average;
+
+ /*
+ * The least value in the time range.
+ */
+ @JsonProperty(value = "minimum")
+ private Double minimum;
+
+ /*
+ * The greatest value in the time range.
+ */
+ @JsonProperty(value = "maximum")
+ private Double maximum;
+
+ /*
+ * The sum of all of the values in the time range.
+ */
+ @JsonProperty(value = "total")
+ private Double total;
+
+ /*
+ * The number of samples in the time range. Can be used to determine the number of values that contributed to the
+ * average value.
+ */
+ @JsonProperty(value = "count")
+ private Double count;
+
+ /**
+ * Creates an instance of MetricValue class.
+ *
+ * @param timeStamp the timeStamp value to set.
+ */
+ @JsonCreator
+ public MetricValue(@JsonProperty(value = "timeStamp", required = true) OffsetDateTime timeStamp) {
+ this.timeStamp = timeStamp;
+ }
+
+ /**
+ * Get the timeStamp property: The timestamp for the metric value in ISO 8601 format.
+ *
+ * @return the timeStamp value.
+ */
+ public OffsetDateTime getTimeStamp() {
+ return this.timeStamp;
+ }
+
+ /**
+ * Get the average property: The average value in the time range.
+ *
+ * @return the average value.
+ */
+ public Double getAverage() {
+ return this.average;
+ }
+
+ /**
+ * Set the average property: The average value in the time range.
+ *
+ * @param average the average value to set.
+ * @return the MetricValue object itself.
+ */
+ public MetricValue setAverage(Double average) {
+ this.average = average;
+ return this;
+ }
+
+ /**
+ * Get the minimum property: The least value in the time range.
+ *
+ * @return the minimum value.
+ */
+ public Double getMinimum() {
+ return this.minimum;
+ }
+
+ /**
+ * Set the minimum property: The least value in the time range.
+ *
+ * @param minimum the minimum value to set.
+ * @return the MetricValue object itself.
+ */
+ public MetricValue setMinimum(Double minimum) {
+ this.minimum = minimum;
+ return this;
+ }
+
+ /**
+ * Get the maximum property: The greatest value in the time range.
+ *
+ * @return the maximum value.
+ */
+ public Double getMaximum() {
+ return this.maximum;
+ }
+
+ /**
+ * Set the maximum property: The greatest value in the time range.
+ *
+ * @param maximum the maximum value to set.
+ * @return the MetricValue object itself.
+ */
+ public MetricValue setMaximum(Double maximum) {
+ this.maximum = maximum;
+ return this;
+ }
+
+ /**
+ * Get the total property: The sum of all of the values in the time range.
+ *
+ * @return the total value.
+ */
+ public Double getTotal() {
+ return this.total;
+ }
+
+ /**
+ * Set the total property: The sum of all of the values in the time range.
+ *
+ * @param total the total value to set.
+ * @return the MetricValue object itself.
+ */
+ public MetricValue setTotal(Double total) {
+ this.total = total;
+ return this;
+ }
+
+ /**
+ * Get the count property: The number of samples in the time range. Can be used to determine the number of values
+ * that contributed to the average value.
+ *
+ * @return the count value.
+ */
+ public Double getCount() {
+ return this.count;
+ }
+
+ /**
+ * Set the count property: The number of samples in the time range. Can be used to determine the number of values
+ * that contributed to the average value.
+ *
+ * @param count the count value to set.
+ * @return the MetricValue object itself.
+ */
+ public MetricValue setCount(Double count) {
+ this.count = count;
+ return this;
+ }
+}
diff --git a/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/ResourceIdList.java b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/ResourceIdList.java
new file mode 100644
index 0000000000000..9aedee633604c
--- /dev/null
+++ b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/ResourceIdList.java
@@ -0,0 +1,42 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+// Code generated by Microsoft (R) AutoRest Code Generator.
+
+package com.azure.monitor.query.implementation.metricsbatch.models;
+
+import com.azure.core.annotation.Fluent;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import java.util.List;
+
+/** The comma separated list of resource IDs to query metrics for. */
+@Fluent
+public final class ResourceIdList {
+ /*
+ * The list of resource IDs to query metrics for.
+ */
+ @JsonProperty(value = "resourceids")
+ private List resourceids;
+
+ /** Creates an instance of ResourceIdList class. */
+ public ResourceIdList() {}
+
+ /**
+ * Get the resourceids property: The list of resource IDs to query metrics for.
+ *
+ * @return the resourceids value.
+ */
+ public List getResourceids() {
+ return this.resourceids;
+ }
+
+ /**
+ * Set the resourceids property: The list of resource IDs to query metrics for.
+ *
+ * @param resourceids the resourceids value to set.
+ * @return the ResourceIdList object itself.
+ */
+ public ResourceIdList setResourceids(List resourceids) {
+ this.resourceids = resourceids;
+ return this;
+ }
+}
diff --git a/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/TimeSeriesElement.java b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/TimeSeriesElement.java
new file mode 100644
index 0000000000000..68dbec639a794
--- /dev/null
+++ b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/TimeSeriesElement.java
@@ -0,0 +1,71 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+// Code generated by Microsoft (R) AutoRest Code Generator.
+
+package com.azure.monitor.query.implementation.metricsbatch.models;
+
+import com.azure.core.annotation.Fluent;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import java.util.List;
+
+/** A time series result type. The discriminator value is always TimeSeries in this case. */
+@Fluent
+public final class TimeSeriesElement {
+ /*
+ * The metadata values returned if filter was specified in the call.
+ */
+ @JsonProperty(value = "metadatavalues")
+ private List metadatavalues;
+
+ /*
+ * An array of data points representing the metric values. This is only returned if a result type of data is
+ * specified.
+ */
+ @JsonProperty(value = "data")
+ private List data;
+
+ /** Creates an instance of TimeSeriesElement class. */
+ public TimeSeriesElement() {}
+
+ /**
+ * Get the metadatavalues property: The metadata values returned if filter was specified in the call.
+ *
+ * @return the metadatavalues value.
+ */
+ public List getMetadatavalues() {
+ return this.metadatavalues;
+ }
+
+ /**
+ * Set the metadatavalues property: The metadata values returned if filter was specified in the call.
+ *
+ * @param metadatavalues the metadatavalues value to set.
+ * @return the TimeSeriesElement object itself.
+ */
+ public TimeSeriesElement setMetadatavalues(List metadatavalues) {
+ this.metadatavalues = metadatavalues;
+ return this;
+ }
+
+ /**
+ * Get the data property: An array of data points representing the metric values. This is only returned if a result
+ * type of data is specified.
+ *
+ * @return the data value.
+ */
+ public List getData() {
+ return this.data;
+ }
+
+ /**
+ * Set the data property: An array of data points representing the metric values. This is only returned if a result
+ * type of data is specified.
+ *
+ * @param data the data value to set.
+ * @return the TimeSeriesElement object itself.
+ */
+ public TimeSeriesElement setData(List data) {
+ this.data = data;
+ return this;
+ }
+}
diff --git a/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/package-info.java b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/package-info.java
new file mode 100644
index 0000000000000..30e7e4efcc0a1
--- /dev/null
+++ b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/models/package-info.java
@@ -0,0 +1,6 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+// Code generated by Microsoft (R) AutoRest Code Generator.
+
+/** Package containing the data models for AzureMonitorMetricBatch. null. */
+package com.azure.monitor.query.implementation.metricsbatch.models;
diff --git a/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/package-info.java b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/package-info.java
new file mode 100644
index 0000000000000..52fa40beb002b
--- /dev/null
+++ b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/implementation/metricsbatch/package-info.java
@@ -0,0 +1,6 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+// Code generated by Microsoft (R) AutoRest Code Generator.
+
+/** Package containing the classes for AzureMonitorMetricBatch. null. */
+package com.azure.monitor.query.implementation.metricsbatch;
diff --git a/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/models/MetricsBatchResult.java b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/models/MetricsBatchResult.java
new file mode 100644
index 0000000000000..edb6204b78614
--- /dev/null
+++ b/sdk/monitor/azure-monitor-query/src/main/java/com/azure/monitor/query/models/MetricsBatchResult.java
@@ -0,0 +1,29 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+package com.azure.monitor.query.models;
+
+import java.util.List;
+
+/**
+ * The result of a metrics query batch. It contains the results of individual queries.
+ */
+public final class MetricsBatchResult {
+ private final List metricsQueryResults;
+
+ /**
+ * Creates an instance of MetricsBatchResult.
+ * @param metricsQueryResults the metrics results for individual queries
+ */
+ public MetricsBatchResult(List metricsQueryResults) {
+ this.metricsQueryResults = metricsQueryResults;
+ }
+
+ /**
+ * Get the metrics results for individual queries.
+ * @return returns the metrics results for individual queries
+ */
+ public List getMetricsQueryResults() {
+ return metricsQueryResults;
+ }
+}
diff --git a/sdk/monitor/azure-monitor-query/src/main/java/module-info.java b/sdk/monitor/azure-monitor-query/src/main/java/module-info.java
index f5209e0c3d9eb..28d84fc30394e 100644
--- a/sdk/monitor/azure-monitor-query/src/main/java/module-info.java
+++ b/sdk/monitor/azure-monitor-query/src/main/java/module-info.java
@@ -13,4 +13,5 @@
opens com.azure.monitor.query.implementation.metrics.models to com.fasterxml.jackson.databind, com.azure.core;
opens com.azure.monitor.query.implementation.metricsdefinitions.models to com.fasterxml.jackson.databind, com.azure.core;
opens com.azure.monitor.query.implementation.metricsnamespaces.models to com.fasterxml.jackson.databind, com.azure.core;
+ opens com.azure.monitor.query.implementation.metricsbatch.models to com.fasterxml.jackson.databind, com.azure.core;
}
diff --git a/sdk/monitor/azure-monitor-query/src/samples/java/com/azure/monitor/query/MetricsBatchQuerySample.java b/sdk/monitor/azure-monitor-query/src/samples/java/com/azure/monitor/query/MetricsBatchQuerySample.java
new file mode 100644
index 0000000000000..cb0d4425c941f
--- /dev/null
+++ b/sdk/monitor/azure-monitor-query/src/samples/java/com/azure/monitor/query/MetricsBatchQuerySample.java
@@ -0,0 +1,53 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+package com.azure.monitor.query;
+
+import com.azure.identity.DefaultAzureCredentialBuilder;
+import com.azure.monitor.query.models.MetricResult;
+import com.azure.monitor.query.models.MetricsBatchResult;
+import com.azure.monitor.query.models.MetricsQueryResult;
+
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * Sample demonstrates how to synchronously query metrics for multiple resources.
+ */
+public class MetricsBatchQuerySample {
+ /**
+ * The main method to execute the sample.
+ *
+ * @param args Unused. Arguments to the program.
+ */
+ public static void main(String[] args) {
+ MetricsBatchQueryClient metricsBatchQueryClient = new MetricsBatchQueryClientBuilder()
+ .credential(new DefaultAzureCredentialBuilder().build())
+ .endpoint("https://westus2.monitoring.azure.com")
+ .buildClient();
+
+ MetricsBatchResult metricsBatchResult = metricsBatchQueryClient.queryBatch(
+ Arrays.asList("{resourceId1}", "{resourceId2}"),
+ Arrays.asList("{metric1}", "{metric2}"),
+ "{metricNamespace}");
+
+ for (MetricsQueryResult metricsQueryResult : metricsBatchResult.getMetricsQueryResults()) {
+ // Each MetricsQueryResult corresponds to one of the resourceIds in the batch request.
+ List metrics = metricsQueryResult.getMetrics();
+ metrics.forEach(metric -> {
+ System.out.println(metric.getMetricName());
+ System.out.println(metric.getId());
+ System.out.println(metric.getResourceType());
+ System.out.println(metric.getUnit());
+ System.out.println(metric.getTimeSeries().size());
+ System.out.println(metric.getTimeSeries().get(0).getValues().size());
+ metric.getTimeSeries()
+ .stream()
+ .flatMap(ts -> ts.getValues().stream())
+ .forEach(mv -> System.out.println(mv.getTimeStamp().toString()
+ + "; Count = " + mv.getCount()
+ + "; Average = " + mv.getAverage()));
+ });
+ }
+ }
+}
diff --git a/sdk/monitor/azure-monitor-query/src/samples/java/com/azure/monitor/query/ReadmeSamples.java b/sdk/monitor/azure-monitor-query/src/samples/java/com/azure/monitor/query/ReadmeSamples.java
index a7802803a3033..5ad5cc2d4a19f 100644
--- a/sdk/monitor/azure-monitor-query/src/samples/java/com/azure/monitor/query/ReadmeSamples.java
+++ b/sdk/monitor/azure-monitor-query/src/samples/java/com/azure/monitor/query/ReadmeSamples.java
@@ -21,6 +21,7 @@
import com.azure.monitor.query.models.LogsTableRow;
import com.azure.monitor.query.models.MetricResult;
import com.azure.monitor.query.models.MetricValue;
+import com.azure.monitor.query.models.MetricsBatchResult;
import com.azure.monitor.query.models.MetricsQueryOptions;
import com.azure.monitor.query.models.MetricsQueryResult;
import com.azure.monitor.query.models.QueryTimeInterval;
@@ -71,17 +72,33 @@ public void createMetricsClients() {
// END: readme-sample-createMetricsQueryAsyncClient
}
+ public void createMetricsBatchClients() {
+ // BEGIN: readme-sample-createMetricsBatchQueryClient
+ MetricsBatchQueryClient metricsBatchQueryClient = new MetricsBatchQueryClientBuilder()
+ .credential(new DefaultAzureCredentialBuilder().build())
+ .endpoint("{endpoint}")
+ .buildClient();
+ // END: readme-sample-createMetricsBatchQueryClient
+
+ // BEGIN: readme-sample-createMetricsBatchQueryAsyncClient
+ MetricsBatchQueryAsyncClient metricsBatchQueryAsyncClient = new MetricsBatchQueryClientBuilder()
+ .credential(new DefaultAzureCredentialBuilder().build())
+ .endpoint("{endpoint}")
+ .buildAsyncClient();
+ // END: readme-sample-createMetricsBatchQueryAsyncClient
+ }
+
/**
* Sample to query logs using a single Kusto query.
*/
public void queryLogs() {
// BEGIN: readme-sample-logsquery
LogsQueryClient logsQueryClient = new LogsQueryClientBuilder()
- .credential(new DefaultAzureCredentialBuilder().build())
- .buildClient();
+ .credential(new DefaultAzureCredentialBuilder().build())
+ .buildClient();
LogsQueryResult queryResults = logsQueryClient.queryWorkspace("{workspace-id}", "{kusto-query}",
- new QueryTimeInterval(Duration.ofDays(2)));
+ new QueryTimeInterval(Duration.ofDays(2)));
for (LogsTableRow row : queryResults.getTable().getRows()) {
System.out.println(row.getColumnValue("OperationName") + " " + row.getColumnValue("ResourceGroup"));
@@ -131,11 +148,11 @@ public String getOperationName() {
public void queryLogsAsModel() {
// BEGIN: readme-sample-logsquerycustommodel
LogsQueryClient logsQueryClient = new LogsQueryClientBuilder()
- .credential(new DefaultAzureCredentialBuilder().build())
- .buildClient();
+ .credential(new DefaultAzureCredentialBuilder().build())
+ .buildClient();
List customLogModels = logsQueryClient.queryWorkspace("{workspace-id}", "{kusto-query}",
- new QueryTimeInterval(Duration.ofDays(2)), CustomLogModel.class);
+ new QueryTimeInterval(Duration.ofDays(2)), CustomLogModel.class);
for (CustomLogModel customLogModel : customLogModels) {
System.out.println(customLogModel.getOperationName() + " " + customLogModel.getResourceGroup());
@@ -149,8 +166,8 @@ public void queryLogsAsModel() {
public void queryBatch() {
// BEGIN: readme-sample-batchlogsquery
LogsQueryClient logsQueryClient = new LogsQueryClientBuilder()
- .credential(new DefaultAzureCredentialBuilder().build())
- .buildClient();
+ .credential(new DefaultAzureCredentialBuilder().build())
+ .buildClient();
LogsBatchQuery logsBatchQuery = new LogsBatchQuery();
String query1 = logsBatchQuery.addWorkspaceQuery("{workspace-id}", "{query-1}", new QueryTimeInterval(Duration.ofDays(2)));
@@ -158,7 +175,7 @@ public void queryBatch() {
String query3 = logsBatchQuery.addWorkspaceQuery("{workspace-id}", "{query-3}", new QueryTimeInterval(Duration.ofDays(10)));
LogsBatchQueryResultCollection batchResults = logsQueryClient
- .queryBatchWithResponse(logsBatchQuery, Context.NONE).getValue();
+ .queryBatchWithResponse(logsBatchQuery, Context.NONE).getValue();
LogsBatchQueryResult query1Result = batchResults.getResult(query1);
for (LogsTableRow row : query1Result.getTable().getRows()) {
@@ -192,7 +209,7 @@ public void getLogsWithServerTimeout() {
.setServerTimeout(Duration.ofMinutes(10));
Response response = logsQueryClient.queryWorkspaceWithResponse("{workspace-id}",
- "{kusto-query}", new QueryTimeInterval(Duration.ofDays(2)), options, Context.NONE);
+ "{kusto-query}", new QueryTimeInterval(Duration.ofDays(2)), options, Context.NONE);
// END: readme-sample-logsquerytimeout
}
@@ -202,13 +219,13 @@ public void getLogsWithServerTimeout() {
public void getLogsQueryFromMultipleWorkspaces() {
// BEGIN: readme-sample-logsquerymultipleworkspaces
LogsQueryClient logsQueryClient = new LogsQueryClientBuilder()
- .credential(new DefaultAzureCredentialBuilder().build())
- .buildClient();
+ .credential(new DefaultAzureCredentialBuilder().build())
+ .buildClient();
Response response = logsQueryClient.queryWorkspaceWithResponse("{workspace-id}", "{kusto-query}",
- new QueryTimeInterval(Duration.ofDays(2)), new LogsQueryOptions()
- .setAdditionalWorkspaces(Arrays.asList("{additional-workspace-identifiers}")),
- Context.NONE);
+ new QueryTimeInterval(Duration.ofDays(2)), new LogsQueryOptions()
+ .setAdditionalWorkspaces(Arrays.asList("{additional-workspace-identifiers}")),
+ Context.NONE);
LogsQueryResult result = response.getValue();
// END: readme-sample-logsquerymultipleworkspaces
}
@@ -220,11 +237,11 @@ public void getLogsQueryFromMultipleWorkspaces() {
public void getMetrics() {
// BEGIN: readme-sample-metricsquery
MetricsQueryClient metricsQueryClient = new MetricsQueryClientBuilder()
- .credential(new DefaultAzureCredentialBuilder().build())
- .buildClient();
+ .credential(new DefaultAzureCredentialBuilder().build())
+ .buildClient();
MetricsQueryResult metricsQueryResult = metricsQueryClient.queryResource("{resource-uri}",
- Arrays.asList("SuccessfulCalls", "TotalCalls"));
+ Arrays.asList("SuccessfulCalls", "TotalCalls"));
for (MetricResult metric : metricsQueryResult.getMetrics()) {
System.out.println("Metric name " + metric.getMetricName());
@@ -276,14 +293,14 @@ public void tsgEnableHttpLogging() {
// BEGIN: readme-sample-enablehttplogging
LogsQueryClient logsQueryClient = new LogsQueryClientBuilder()
- .credential(credential)
- .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
- .buildClient();
+ .credential(credential)
+ .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
+ .buildClient();
// or
MetricsQueryClient metricsQueryClient = new MetricsQueryClientBuilder()
- .credential(credential)
- .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
- .buildClient();
+ .credential(credential)
+ .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
+ .buildClient();
// END: readme-sample-enablehttplogging
}
@@ -295,9 +312,9 @@ public void tsgHttpResponseTimeout() {
// BEGIN: readme-sample-responsetimeout
LogsQueryClient client = new LogsQueryClientBuilder()
- .credential(credential)
- .clientOptions(new HttpClientOptions().setResponseTimeout(Duration.ofSeconds(120)))
- .buildClient();
+ .credential(credential)
+ .clientOptions(new HttpClientOptions().setResponseTimeout(Duration.ofSeconds(120)))
+ .buildClient();
// END: readme-sample-responsetimeout
}
@@ -308,11 +325,11 @@ public void tsgSetServerTimeout() {
DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build();
// BEGIN: readme-sample-servertimeout
LogsQueryClient client = new LogsQueryClientBuilder()
- .credential(credential)
- .buildClient();
+ .credential(credential)
+ .buildClient();
client.queryWorkspaceWithResponse("{workspaceId}", "{kusto-query-string}", QueryTimeInterval.LAST_DAY,
- new LogsQueryOptions().setServerTimeout(Duration.ofMinutes(10)), Context.NONE);
+ new LogsQueryOptions().setServerTimeout(Duration.ofMinutes(10)), Context.NONE);
// END: readme-sample-servertimeout
}
@@ -323,12 +340,12 @@ public void tsgAllowPartialErrors() {
DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build();
LogsQueryClient client = new LogsQueryClientBuilder()
- .credential(credential)
- .buildClient();
+ .credential(credential)
+ .buildClient();
// BEGIN: readme-sample-allowpartialerrors
client.queryWorkspaceWithResponse("{workspaceId}", "{kusto-query-string}", QueryTimeInterval.LAST_DAY,
- new LogsQueryOptions().setAllowPartialErrors(true), Context.NONE);
+ new LogsQueryOptions().setAllowPartialErrors(true), Context.NONE);
// END: readme-sample-allowpartialerrors
}
@@ -340,27 +357,28 @@ public void tsgOkHttpResponseTimeout() {
// BEGIN: readme-sample-okhttpresponsetimeout
LogsQueryClient client = new LogsQueryClientBuilder()
- .credential(credential)
- .clientOptions(new HttpClientOptions().setResponseTimeout(Duration.ofSeconds(120)))
- .buildClient();
+ .credential(credential)
+ .clientOptions(new HttpClientOptions().setResponseTimeout(Duration.ofSeconds(120)))
+ .buildClient();
// END: readme-sample-okhttpresponsetimeout
}
/**
* Sample to show how to request for query execution statistics and consume the response.
+ *
* @throws IOException if parsing the statistics JSON fails.
*/
public void includeStatistics() throws IOException {
DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build();
// BEGIN: readme-sample-includestatistics
LogsQueryClient client = new LogsQueryClientBuilder()
- .credential(credential)
- .buildClient();
+ .credential(credential)
+ .buildClient();
LogsQueryOptions options = new LogsQueryOptions()
- .setIncludeStatistics(true);
+ .setIncludeStatistics(true);
Response response = client.queryWorkspaceWithResponse("{workspace-id}",
- "AzureActivity | top 10 by TimeGenerated", QueryTimeInterval.LAST_1_HOUR, options, Context.NONE);
+ "AzureActivity | top 10 by TimeGenerated", QueryTimeInterval.LAST_1_HOUR, options, Context.NONE);
LogsQueryResult result = response.getValue();
BinaryData statistics = result.getStatistics();
@@ -373,24 +391,25 @@ public void includeStatistics() throws IOException {
/**
* Sample to show how to request for visualization data and consume the response.
+ *
* @throws IOException if parsing the visualization JSON fails.
*/
public void includeVisualization() throws IOException {
DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build();
// BEGIN: readme-sample-includevisualization
LogsQueryClient client = new LogsQueryClientBuilder()
- .credential(credential)
- .buildClient();
+ .credential(credential)
+ .buildClient();
String visualizationQuery = "StormEvents"
- + "| summarize event_count = count() by State"
- + "| where event_count > 10"
- + "| project State, event_count"
- + "| render columnchart";
+ + "| summarize event_count = count() by State"
+ + "| where event_count > 10"
+ + "| project State, event_count"
+ + "| render columnchart";
LogsQueryOptions options = new LogsQueryOptions()
- .setIncludeVisualization(true);
+ .setIncludeVisualization(true);
Response response = client.queryWorkspaceWithResponse("{workspace-id}", visualizationQuery,
- QueryTimeInterval.LAST_7_DAYS, options, Context.NONE);
+ QueryTimeInterval.LAST_7_DAYS, options, Context.NONE);
LogsQueryResult result = response.getValue();
BinaryData visualization = result.getVisualization();
@@ -423,4 +442,40 @@ public void createMetricsClientWithSovereignCloud() {
.buildClient();
// END: readme-sample-createMetricsQueryClientWithSovereignCloud
}
+
+ /**
+ * Sample to demonstrate querying Azure Monitor for metrics.
+ */
+ public void getMetricsBatch() {
+ // BEGIN: readme-sample-metricsquerybatch
+ MetricsBatchQueryClient metricsBatchQueryClient = new MetricsBatchQueryClientBuilder()
+ .credential(new DefaultAzureCredentialBuilder().build())
+ .endpoint("{endpoint}")
+ .buildClient();
+
+ MetricsBatchResult metricsBatchResult = metricsBatchQueryClient.queryBatch(
+ Arrays.asList("{resourceId1}", "{resourceId2}"),
+ Arrays.asList("{metric1}", "{metric2}"),
+ "{metricNamespace}");
+
+ for (MetricsQueryResult metricsQueryResult : metricsBatchResult.getMetricsQueryResults()) {
+ // Each MetricsQueryResult corresponds to one of the resourceIds in the batch request.
+ List metrics = metricsQueryResult.getMetrics();
+ metrics.forEach(metric -> {
+ System.out.println(metric.getMetricName());
+ System.out.println(metric.getId());
+ System.out.println(metric.getResourceType());
+ System.out.println(metric.getUnit());
+ System.out.println(metric.getTimeSeries().size());
+ System.out.println(metric.getTimeSeries().get(0).getValues().size());
+ metric.getTimeSeries()
+ .stream()
+ .flatMap(ts -> ts.getValues().stream())
+ .forEach(mv -> System.out.println(mv.getTimeStamp().toString()
+ + "; Count = " + mv.getCount()
+ + "; Average = " + mv.getAverage()));
+ });
+ }
+ // END: readme-sample-metricsquerybatch
+ }
}
diff --git a/sdk/monitor/azure-monitor-query/src/samples/java/com/azure/monitor/query/codesnippets/MetricsBatchQueryClientJavaDocCodeSnippets.java b/sdk/monitor/azure-monitor-query/src/samples/java/com/azure/monitor/query/codesnippets/MetricsBatchQueryClientJavaDocCodeSnippets.java
new file mode 100644
index 0000000000000..1d93160104e5e
--- /dev/null
+++ b/sdk/monitor/azure-monitor-query/src/samples/java/com/azure/monitor/query/codesnippets/MetricsBatchQueryClientJavaDocCodeSnippets.java
@@ -0,0 +1,110 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+package com.azure.monitor.query.codesnippets;
+
+import com.azure.identity.DefaultAzureCredentialBuilder;
+import com.azure.monitor.query.MetricsBatchQueryAsyncClient;
+import com.azure.monitor.query.MetricsBatchQueryClient;
+import com.azure.monitor.query.MetricsBatchQueryClientBuilder;
+import com.azure.monitor.query.models.MetricResult;
+import com.azure.monitor.query.models.MetricsBatchResult;
+import com.azure.monitor.query.models.MetricsQueryResult;
+
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * This class contains code samples for generating javadocs through doclets
+ * for {@link com.azure.monitor.query.MetricsBatchQueryClient}
+ */
+public class MetricsBatchQueryClientJavaDocCodeSnippets {
+ /**
+ * Generates code sample for creating a {@link MetricsBatchQueryClient}.
+ */
+ public void createClient() {
+ // BEGIN: com.azure.monitor.query.MetricsBatchQueryClient.instantiation
+ MetricsBatchQueryClient metricsBatchQueryClient = new MetricsBatchQueryClientBuilder()
+ .endpoint("{endpoint}")
+ .credential(new DefaultAzureCredentialBuilder().build())
+ .buildClient();
+ // END: com.azure.monitor.query.MetricsBatchQueryClient.instantiation
+ }
+
+ public void createAsyncClient() {
+ // BEGIN: com.azure.monitor.query.MetricsBatchQueryAsyncClient.instantiation
+ MetricsBatchQueryAsyncClient metricsBatchQueryAsyncClient = new MetricsBatchQueryClientBuilder()
+ .endpoint("{endpoint}")
+ .credential(new DefaultAzureCredentialBuilder().build())
+ .buildAsyncClient();
+ // END: com.azure.monitor.query.MetricsBatchQueryAsyncClient.instantiation
+ }
+
+ /**
+ * Generates a code sample for using {@link MetricsBatchQueryClient#queryBatch(List, List, String)}.
+ */
+ public void queryBatch() {
+ MetricsBatchQueryClient metricsBatchQueryClient = new MetricsBatchQueryClientBuilder()
+ .endpoint("{endpoint}")
+ .credential(new DefaultAzureCredentialBuilder().build())
+ .buildClient();
+
+ // BEGIN: com.azure.monitor.query.MetricsBatchQueryClient.queryBatch#List-List-String
+ MetricsBatchResult metricsBatchResult = metricsBatchQueryClient.queryBatch(
+ Arrays.asList("{resourceId1}", "{resourceId2}"),
+ Arrays.asList("{metricId}"), "{metricNamespace}");
+
+ for (MetricsQueryResult metricsQueryResult : metricsBatchResult.getMetricsQueryResults()) {
+ // Each MetricsQueryResult corresponds to one of the resourceIds in the batch request.
+ List metrics = metricsQueryResult.getMetrics();
+ metrics.forEach(metric -> {
+ System.out.println(metric.getMetricName());
+ System.out.println(metric.getId());
+ System.out.println(metric.getResourceType());
+ System.out.println(metric.getUnit());
+ System.out.println(metric.getTimeSeries().size());
+ System.out.println(metric.getTimeSeries().get(0).getValues().size());
+ metric.getTimeSeries()
+ .stream()
+ .flatMap(ts -> ts.getValues().stream())
+ .forEach(mv -> System.out.println(mv.getTimeStamp().toString()
+ + "; Count = " + mv.getCount()
+ + "; Average = " + mv.getAverage()));
+ });
+ }
+ // END: com.azure.monitor.query.MetricsBatchQueryClient.queryBatch#List-List-String
+ }
+
+ public void queryBatchAsync() {
+ MetricsBatchQueryAsyncClient metricsBatchQueryAsyncClient = new MetricsBatchQueryClientBuilder()
+ .endpoint("{endpoint}")
+ .credential(new DefaultAzureCredentialBuilder().build())
+ .buildAsyncClient();
+
+ // BEGIN: com.azure.monitor.query.MetricsBatchQueryAsyncClient.queryBatch#List-List-String
+ metricsBatchQueryAsyncClient.queryBatch(
+ Arrays.asList("{resourceId1}", "{resourceId2}"),
+ Arrays.asList("{metricId}"), "{metricNamespace}")
+ .subscribe(metricsBatchResult -> {
+ for (MetricsQueryResult metricsQueryResult : metricsBatchResult.getMetricsQueryResults()) {
+ // Each MetricsQueryResult corresponds to one of the resourceIds in the batch request.
+ List metrics = metricsQueryResult.getMetrics();
+ metrics.forEach(metric -> {
+ System.out.println(metric.getMetricName());
+ System.out.println(metric.getId());
+ System.out.println(metric.getResourceType());
+ System.out.println(metric.getUnit());
+ System.out.println(metric.getTimeSeries().size());
+ System.out.println(metric.getTimeSeries().get(0).getValues().size());
+ metric.getTimeSeries()
+ .stream()
+ .flatMap(ts -> ts.getValues().stream())
+ .forEach(mv -> System.out.println(mv.getTimeStamp().toString()
+ + "; Count = " + mv.getCount()
+ + "; Average = " + mv.getAverage()));
+ });
+ }
+ });
+ // END: com.azure.monitor.query.MetricsBatchQueryAsyncClient.queryBatch#List-List-String
+ }
+}
diff --git a/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/MetricsBatchQueryClientTest.java b/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/MetricsBatchQueryClientTest.java
new file mode 100644
index 0000000000000..446666dbed627
--- /dev/null
+++ b/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/MetricsBatchQueryClientTest.java
@@ -0,0 +1,36 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+package com.azure.monitor.query;
+
+import com.azure.core.http.policy.HttpLogDetailLevel;
+import com.azure.core.http.policy.HttpLogOptions;
+import com.azure.core.test.annotation.RecordWithoutRequestBody;
+import com.azure.core.util.Configuration;
+import com.azure.monitor.query.models.MetricsBatchResult;
+import org.junit.jupiter.api.Test;
+
+import java.util.Arrays;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * Unit tests for {@link MetricsBatchQueryClient}.
+ */
+public class MetricsBatchQueryClientTest extends MetricsBatchQueryTestBase {
+
+ @Test
+ @RecordWithoutRequestBody
+ public void testMetricsBatchQuery() {
+ MetricsBatchQueryClient metricsBatchQueryClient = clientBuilder
+ .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
+ .buildClient();
+ String resourceId = Configuration.getGlobalConfiguration().get("AZURE_MONITOR_METRICS_RESOURCE_URI", FAKE_RESOURCE_ID);
+ resourceId = resourceId.substring(resourceId.indexOf("/subscriptions"));
+
+ MetricsBatchResult metricsQueryResults = metricsBatchQueryClient.queryBatch(
+ Arrays.asList(resourceId),
+ Arrays.asList("Successful Requests"), " Microsoft.Eventhub/Namespaces");
+ assertEquals(1, metricsQueryResults.getMetricsQueryResults().size());
+ }
+}
diff --git a/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/MetricsBatchQueryTestBase.java b/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/MetricsBatchQueryTestBase.java
new file mode 100644
index 0000000000000..aec658e75a6d6
--- /dev/null
+++ b/sdk/monitor/azure-monitor-query/src/test/java/com/azure/monitor/query/MetricsBatchQueryTestBase.java
@@ -0,0 +1,36 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+package com.azure.monitor.query;
+
+import com.azure.core.test.TestMode;
+import com.azure.core.test.TestProxyTestBase;
+import com.azure.core.test.utils.MockTokenCredential;
+import com.azure.core.util.Configuration;
+import com.azure.identity.DefaultAzureCredentialBuilder;
+
+public class MetricsBatchQueryTestBase extends TestProxyTestBase {
+
+ static final String FAKE_RESOURCE_ID = "/subscriptions/faa080af-c1d8-40ad-9cce-e1a450ca5b57/resourceGroups/rg/providers/Microsoft.Compute/virtualMachines/vm";
+ protected String metricEndpoint;
+ protected MetricsBatchQueryClientBuilder clientBuilder;
+
+ @Override
+ public void beforeTest() {
+ metricEndpoint = Configuration.getGlobalConfiguration().get("AZURE_MONITOR_METRICS_ENDPOINT", "https://westus.metrics.monitor.azure.com");
+
+ MetricsBatchQueryClientBuilder clientBuilder = new MetricsBatchQueryClientBuilder();
+ if (getTestMode() == TestMode.PLAYBACK) {
+ clientBuilder
+ .credential(new MockTokenCredential())
+ .httpClient(interceptorManager.getPlaybackClient());
+ } else if (getTestMode() == TestMode.RECORD) {
+ clientBuilder
+ .addPolicy(interceptorManager.getRecordPolicy())
+ .credential(new DefaultAzureCredentialBuilder().build());
+ } else if (getTestMode() == TestMode.LIVE) {
+ clientBuilder.credential(new DefaultAzureCredentialBuilder().build());
+ }
+ this.clientBuilder = clientBuilder.endpoint(metricEndpoint);
+ }
+}
diff --git a/sdk/monitor/azure-monitor-query/swagger/README.md b/sdk/monitor/azure-monitor-query/swagger/README.md
index fafd295739a07..16fbf91fa0a59 100644
--- a/sdk/monitor/azure-monitor-query/swagger/README.md
+++ b/sdk/monitor/azure-monitor-query/swagger/README.md
@@ -20,7 +20,6 @@ required-parameter-client-methods: false
required-fields-as-ctor-args: true
model-override-setter-from-superclass: true
credential-types: tokencredential
-client-side-validations: true
artifact-id: azure-monitor-query
customization-class: src/main/java/LogsCustomization.java
enable-sync-stack: true
@@ -45,7 +44,6 @@ required-parameter-client-methods: false
required-fields-as-ctor-args: true
model-override-setter-from-superclass: true
credential-types: tokencredential
-client-side-validations: true
artifact-id: azure-monitor-query
customization-class: src/main/java/MetricsCustomization.java
enable-sync-stack: true
@@ -75,7 +73,6 @@ required-parameter-client-methods: false
required-fields-as-ctor-args: true
model-override-setter-from-superclass: true
credential-types: tokencredential
-client-side-validations: true
artifact-id: azure-monitor-query
customization-class: src/main/java/MetricsNamespacesCustomization.java
enable-sync-stack: true
@@ -101,8 +98,32 @@ required-parameter-client-methods: false
required-fields-as-ctor-args: true
model-override-setter-from-superclass: true
credential-types: tokencredential
-client-side-validations: true
artifact-id: azure-monitor-query
customization-class: src/main/java/MetricsDefinitionsCustomization.java
enable-sync-stack: true
```
+
+
+## Metrics Batch Query
+These settings apply only when `--tag=package-metrics-batch` is specified on the command line.
+
+``` yaml $(tag) == 'package-metrics-batch'
+use: '@autorest/java@4.1.17'
+input-file: https://raw.githubusercontent.com/srnagar/azure-rest-api-specs/154cb5c6d5bdd2b183ea8d9d1b7e5bbd0caa625b/specification/monitor/data-plane/Microsoft.Insights/preview/2023-05-01-preview/metricBatch.json
+service-name: MetricsDefinitions
+java: true
+output-folder: ../
+namespace: com.azure.monitor.query.implementation.metricsbatch
+generate-client-interfaces: false
+service-interface-as-public: true
+sync-methods: all
+license-header: MICROSOFT_MIT_SMALL
+add-context-parameter: true
+context-client-method-parameter: true
+required-parameter-client-methods: false
+required-fields-as-ctor-args: true
+model-override-setter-from-superclass: true
+credential-types: tokencredential
+artifact-id: azure-monitor-query
+enable-sync-stack: true
+```
diff --git a/sdk/monitor/test-resources.json b/sdk/monitor/test-resources.json
index fbe96e7a3a680..bec67eaaac5d3 100644
--- a/sdk/monitor/test-resources.json
+++ b/sdk/monitor/test-resources.json
@@ -64,33 +64,12 @@
"description": "The tenant id to which the application and resources belong."
}
},
- "dataCollectionEndpointName": {
- "type": "string",
- "defaultValue": "azmonitordce",
- "metadata": {
- "description": "Specifies the name of the Data Collection Endpoint to create."
- }
- },
"location": {
"type": "string",
"defaultValue": "[resourceGroup().location]",
"metadata": {
"description": "Specifies the location in which to create the Data Collection Endpoint."
}
- },
- "dataCollectionRuleName": {
- "type": "string",
- "defaultValue": "azmonitordcr",
- "metadata": {
- "description": "Specifies the name of the Data Collection Rule to create."
- }
- },
- "workspaceName": {
- "type": "String",
- "defaultValue": "azmonitorlogsws",
- "metadata": {
- "description": "Specifies the Log Analytics workspace name to use."
- }
}
},
"variables": {
@@ -106,7 +85,10 @@
"eventHubsNamespaceKeyName": "RootManageSharedAccessKey",
"eventHubsNamespaceName": "[concat('eventhub', parameters('baseName'))]",
"dcrRoleId": "[concat('/subscriptions/', subscription().subscriptionId, '/providers/Microsoft.Authorization/roleDefinitions/3913510d-42f4-4e42-8a64-420c390055eb')]",
- "dcrRoleName": "[concat('dcrrole', parameters('baseName'))]"
+ "dcrRoleName": "[concat('dcrrole', parameters('baseName'))]",
+ "dataCollectionRuleName": "[concat(parameters('baseName'), '-', 'azmonitordcr')]",
+ "dataCollectionEndpointName": "[concat(parameters('baseName'), '-', 'azmonitordce')]",
+ "workspaceName": "[concat(parameters('baseName'), '-', 'azmonitorlogsws')]"
},
"resources": [
{
@@ -203,7 +185,7 @@
"apiVersion": "[variables('authorizationApiVersion')]",
"name": "[guid(concat('dcrRoleId', variables('dcrRoleName')))]",
"dependsOn": [
- "[resourceId('Microsoft.Insights/dataCollectionRules', parameters('dataCollectionRuleName'))]"
+ "[resourceId('Microsoft.Insights/dataCollectionRules', variables('dataCollectionRuleName'))]"
],
"properties": {
"roleDefinitionId": "[variables('dcrRoleId')]",
@@ -212,7 +194,7 @@
},
{
"type": "Microsoft.Insights/dataCollectionEndpoints",
- "name": "[parameters('dataCollectionEndpointName')]",
+ "name": "[variables('dataCollectionEndpointName')]",
"location": "[parameters('location')]",
"apiVersion": "2021-04-01",
"properties": {
@@ -223,16 +205,16 @@
},
{
"type": "Microsoft.Insights/dataCollectionRules",
- "name": "[parameters('dataCollectionRuleName')]",
+ "name": "[variables('dataCollectionRuleName')]",
"location": "[parameters('location')]",
"apiVersion": "2021-09-01-preview",
"dependsOn": [
- "[resourceId('Microsoft.Insights/dataCollectionEndpoints', parameters('dataCollectionEndpointName'))]",
- "[resourceId('microsoft.operationalinsights/workspaces', parameters('workspaceName'))]",
- "[resourceId('Microsoft.OperationalInsights/workspaces/tables', parameters('workspaceName'), 'MyTable_CL')]"
+ "[resourceId('Microsoft.Insights/dataCollectionEndpoints', variables('dataCollectionEndpointName'))]",
+ "[resourceId('microsoft.operationalinsights/workspaces', variables('workspaceName'))]",
+ "[resourceId('Microsoft.OperationalInsights/workspaces/tables', variables('workspaceName'), 'MyTable_CL')]"
],
"properties": {
- "dataCollectionEndpointId": "[resourceId('Microsoft.Insights/dataCollectionEndpoints', parameters('dataCollectionEndpointName'))]",
+ "dataCollectionEndpointId": "[resourceId('Microsoft.Insights/dataCollectionEndpoints', variables('dataCollectionEndpointName'))]",
"streamDeclarations": {
"Custom-MyTableRawData": {
"columns": [
@@ -254,7 +236,7 @@
"destinations": {
"logAnalytics": [
{
- "workspaceResourceId": "[resourceId('microsoft.operationalinsights/workspaces', parameters('workspaceName'))]",
+ "workspaceResourceId": "[resourceId('microsoft.operationalinsights/workspaces', variables('workspaceName'))]",
"name": "clv2ws1"
}
]
@@ -276,7 +258,7 @@
{
"type": "microsoft.operationalinsights/workspaces",
"apiVersion": "2021-12-01-preview",
- "name": "[parameters('workspaceName')]",
+ "name": "[variables('workspaceName')]",
"location": "[variables('location')]",
"properties": {
"sku": {
@@ -296,9 +278,9 @@
{
"type": "Microsoft.OperationalInsights/workspaces/tables",
"apiVersion": "2021-12-01-preview",
- "name": "[concat(parameters('workspaceName'), '/', 'MyTable_CL')]",
+ "name": "[concat(variables('workspaceName'), '/', 'MyTable_CL')]",
"dependsOn": [
- "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaceName'))]"
+ "[resourceId('Microsoft.OperationalInsights/workspaces', variables('workspaceName'))]"
],
"properties": {
"totalRetentionInDays": 30,
@@ -366,19 +348,19 @@
},
"AZURE_MONITOR_DCE": {
"type": "string",
- "value": "[reference(resourceId('Microsoft.Insights/dataCollectionEndpoints', parameters('dataCollectionEndpointName')), '2021-04-01').logsIngestion.endpoint]"
+ "value": "[reference(resourceId('Microsoft.Insights/dataCollectionEndpoints', variables('dataCollectionEndpointName')), '2021-04-01').logsIngestion.endpoint]"
},
"AZURE_MONITOR_DCR_ID": {
"type": "string",
- "value": "[reference(resourceId('Microsoft.Insights/dataCollectionRules', parameters('dataCollectionRuleName')), '2021-04-01').immutableId]"
+ "value": "[reference(resourceId('Microsoft.Insights/dataCollectionRules', variables('dataCollectionRuleName')), '2021-04-01').immutableId]"
},
"AZURE_MONITOR_LOGS_WORKSPACE_ID": {
"type": "string",
- "value": "[reference(resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaceName'))).customerId]"
+ "value": "[reference(resourceId('Microsoft.OperationalInsights/workspaces', variables('workspaceName'))).customerId]"
},
"AZURE_MONITOR_LOGS_RESOURCE_ID": {
"type": "string",
- "value": "[resourceId('Microsoft.OperationalInsights/workspaces', parameters('workspaceName'))]"
+ "value": "[resourceId('Microsoft.OperationalInsights/workspaces', variables('workspaceName'))]"
},
"AZURE_MONITOR_METRICS_RESOURCE_URI": {
"type": "string",