All Downloads are FREE. Search and download functionalities are using the official Maven repository.

software.amazon.awssdk.services.timestreamquery.DefaultTimestreamQueryClient Maven / Gradle / Ivy

/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
 * the License. A copy of the License is located at
 * 
 * http://aws.amazon.com/apache2.0
 * 
 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
 * and limitations under the License.
 */

package software.amazon.awssdk.services.timestreamquery;

import java.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
import software.amazon.awssdk.annotations.Generated;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
import software.amazon.awssdk.awscore.client.config.AwsClientOption;
import software.amazon.awssdk.awscore.client.handler.AwsSyncClientHandler;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.core.ApiName;
import software.amazon.awssdk.core.RequestOverrideConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientOption;
import software.amazon.awssdk.core.client.handler.ClientExecutionParams;
import software.amazon.awssdk.core.client.handler.SyncClientHandler;
import software.amazon.awssdk.core.endpointdiscovery.EndpointDiscoveryRefreshCache;
import software.amazon.awssdk.core.endpointdiscovery.EndpointDiscoveryRequest;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.http.HttpResponseHandler;
import software.amazon.awssdk.core.metrics.CoreMetric;
import software.amazon.awssdk.core.util.VersionInfo;
import software.amazon.awssdk.metrics.MetricCollector;
import software.amazon.awssdk.metrics.MetricPublisher;
import software.amazon.awssdk.metrics.NoOpMetricCollector;
import software.amazon.awssdk.protocols.core.ExceptionMetadata;
import software.amazon.awssdk.protocols.json.AwsJsonProtocol;
import software.amazon.awssdk.protocols.json.AwsJsonProtocolFactory;
import software.amazon.awssdk.protocols.json.BaseAwsJsonProtocolFactory;
import software.amazon.awssdk.protocols.json.JsonOperationMetadata;
import software.amazon.awssdk.services.timestreamquery.model.AccessDeniedException;
import software.amazon.awssdk.services.timestreamquery.model.CancelQueryRequest;
import software.amazon.awssdk.services.timestreamquery.model.CancelQueryResponse;
import software.amazon.awssdk.services.timestreamquery.model.ConflictException;
import software.amazon.awssdk.services.timestreamquery.model.DescribeEndpointsRequest;
import software.amazon.awssdk.services.timestreamquery.model.DescribeEndpointsResponse;
import software.amazon.awssdk.services.timestreamquery.model.InternalServerException;
import software.amazon.awssdk.services.timestreamquery.model.InvalidEndpointException;
import software.amazon.awssdk.services.timestreamquery.model.QueryExecutionException;
import software.amazon.awssdk.services.timestreamquery.model.QueryRequest;
import software.amazon.awssdk.services.timestreamquery.model.QueryResponse;
import software.amazon.awssdk.services.timestreamquery.model.ThrottlingException;
import software.amazon.awssdk.services.timestreamquery.model.TimestreamQueryException;
import software.amazon.awssdk.services.timestreamquery.model.TimestreamQueryRequest;
import software.amazon.awssdk.services.timestreamquery.model.ValidationException;
import software.amazon.awssdk.services.timestreamquery.paginators.QueryIterable;
import software.amazon.awssdk.services.timestreamquery.transform.CancelQueryRequestMarshaller;
import software.amazon.awssdk.services.timestreamquery.transform.DescribeEndpointsRequestMarshaller;
import software.amazon.awssdk.services.timestreamquery.transform.QueryRequestMarshaller;
import software.amazon.awssdk.utils.Logger;

/**
 * Internal implementation of {@link TimestreamQueryClient}.
 *
 * @see TimestreamQueryClient#builder()
 */
@Generated("software.amazon.awssdk:codegen")
@SdkInternalApi
final class DefaultTimestreamQueryClient implements TimestreamQueryClient {
    private static final Logger log = Logger.loggerFor(DefaultTimestreamQueryClient.class);

    private final SyncClientHandler clientHandler;

    private final AwsJsonProtocolFactory protocolFactory;

    private final SdkClientConfiguration clientConfiguration;

    private EndpointDiscoveryRefreshCache endpointDiscoveryCache;

    protected DefaultTimestreamQueryClient(SdkClientConfiguration clientConfiguration) {
        this.clientHandler = new AwsSyncClientHandler(clientConfiguration);
        this.clientConfiguration = clientConfiguration;
        this.protocolFactory = init(AwsJsonProtocolFactory.builder()).build();
        if (clientConfiguration.option(SdkClientOption.ENDPOINT_DISCOVERY_ENABLED)) {
            this.endpointDiscoveryCache = EndpointDiscoveryRefreshCache.create(TimestreamQueryEndpointDiscoveryCacheLoader
                    .create(this));
            if (clientConfiguration.option(SdkClientOption.ENDPOINT_OVERRIDDEN) == Boolean.TRUE) {
                log.warn(() -> "Endpoint discovery is enabled for this client, and an endpoint override was also specified. This will disable endpoint discovery for methods that require it, instead using the specified endpoint override. This may or may not be what you intended.");
            }
        }
    }

    @Override
    public final String serviceName() {
        return SERVICE_NAME;
    }

    /**
     * 

* Cancels a query that has been issued. Cancellation is guaranteed only if the query has not completed execution * before the cancellation request was issued. Because cancellation is an idempotent operation, subsequent * cancellation requests will return a CancellationMessage, indicating that the query has already been * canceled. *

* * @param cancelQueryRequest * @return Result of the CancelQuery operation returned by the service. * @throws AccessDeniedException * You are not authorized to perform this action. * @throws InternalServerException * Timestream was unable to fully process this request because of an internal server error. * @throws ThrottlingException * The request was denied due to request throttling. * @throws ValidationException * Invalid or malformed request. * @throws InvalidEndpointException * The requested endpoint was invalid. * @throws SdkException * Base class for all exceptions that can be thrown by the SDK (both service and client). Can be used for * catch all scenarios. * @throws SdkClientException * If any client side error occurs such as an IO related failure, failure to get credentials, etc. * @throws TimestreamQueryException * Base class for all service exceptions. Unknown exceptions will be thrown as an instance of this type. * @sample TimestreamQueryClient.CancelQuery * @see AWS * API Documentation */ @Override public CancelQueryResponse cancelQuery(CancelQueryRequest cancelQueryRequest) throws AccessDeniedException, InternalServerException, ThrottlingException, ValidationException, InvalidEndpointException, AwsServiceException, SdkClientException, TimestreamQueryException { JsonOperationMetadata operationMetadata = JsonOperationMetadata.builder().hasStreamingSuccessResponse(false) .isPayloadJson(true).build(); HttpResponseHandler responseHandler = protocolFactory.createResponseHandler(operationMetadata, CancelQueryResponse::builder); HttpResponseHandler errorResponseHandler = createErrorResponseHandler(protocolFactory, operationMetadata); boolean endpointDiscoveryEnabled = clientConfiguration.option(SdkClientOption.ENDPOINT_DISCOVERY_ENABLED); boolean endpointOverridden = clientConfiguration.option(SdkClientOption.ENDPOINT_OVERRIDDEN) == Boolean.TRUE; if (endpointOverridden) { endpointDiscoveryEnabled = false; } else if (!endpointDiscoveryEnabled) { throw new IllegalStateException( "This operation requires endpoint discovery to be enabled, or for you to specify an endpoint override when the client is created."); } URI cachedEndpoint = null; if (endpointDiscoveryEnabled) { String key = clientConfiguration.option(AwsClientOption.CREDENTIALS_PROVIDER).resolveCredentials().accessKeyId(); EndpointDiscoveryRequest endpointDiscoveryRequest = EndpointDiscoveryRequest.builder().required(true) .defaultEndpoint(clientConfiguration.option(SdkClientOption.ENDPOINT)).build(); cachedEndpoint = endpointDiscoveryCache.get(key, endpointDiscoveryRequest); } List metricPublishers = resolveMetricPublishers(clientConfiguration, cancelQueryRequest .overrideConfiguration().orElse(null)); MetricCollector apiCallMetricCollector = metricPublishers.isEmpty() ? NoOpMetricCollector.create() : MetricCollector .create("ApiCall"); try { apiCallMetricCollector.reportMetric(CoreMetric.SERVICE_ID, "Timestream Query"); apiCallMetricCollector.reportMetric(CoreMetric.OPERATION_NAME, "CancelQuery"); return clientHandler.execute(new ClientExecutionParams() .withOperationName("CancelQuery").withResponseHandler(responseHandler) .withErrorResponseHandler(errorResponseHandler).discoveredEndpoint(cachedEndpoint) .withInput(cancelQueryRequest).withMetricCollector(apiCallMetricCollector) .withMarshaller(new CancelQueryRequestMarshaller(protocolFactory))); } finally { metricPublishers.forEach(p -> p.publish(apiCallMetricCollector.collect())); } } /** *

* DescribeEndpoints returns a list of available endpoints to make Timestream API calls against. This API is * available through both Write and Query. *

*

* Because Timestream’s SDKs are designed to transparently work with the service’s architecture, including the * management and mapping of the service endpoints, it is not recommended that you use this API unless: *

*
    *
  • *

    * Your application uses a programming language that does not yet have SDK support *

    *
  • *
  • *

    * You require better control over the client-side implementation *

    *
  • *
*

* For detailed information on how to use DescribeEndpoints, see The * Endpoint Discovery Pattern and REST APIs. *

* * @param describeEndpointsRequest * @return Result of the DescribeEndpoints operation returned by the service. * @throws InternalServerException * Timestream was unable to fully process this request because of an internal server error. * @throws ValidationException * Invalid or malformed request. * @throws ThrottlingException * The request was denied due to request throttling. * @throws SdkException * Base class for all exceptions that can be thrown by the SDK (both service and client). Can be used for * catch all scenarios. * @throws SdkClientException * If any client side error occurs such as an IO related failure, failure to get credentials, etc. * @throws TimestreamQueryException * Base class for all service exceptions. Unknown exceptions will be thrown as an instance of this type. * @sample TimestreamQueryClient.DescribeEndpoints * @see AWS API Documentation */ @Override public DescribeEndpointsResponse describeEndpoints(DescribeEndpointsRequest describeEndpointsRequest) throws InternalServerException, ValidationException, ThrottlingException, AwsServiceException, SdkClientException, TimestreamQueryException { JsonOperationMetadata operationMetadata = JsonOperationMetadata.builder().hasStreamingSuccessResponse(false) .isPayloadJson(true).build(); HttpResponseHandler responseHandler = protocolFactory.createResponseHandler(operationMetadata, DescribeEndpointsResponse::builder); HttpResponseHandler errorResponseHandler = createErrorResponseHandler(protocolFactory, operationMetadata); List metricPublishers = resolveMetricPublishers(clientConfiguration, describeEndpointsRequest .overrideConfiguration().orElse(null)); MetricCollector apiCallMetricCollector = metricPublishers.isEmpty() ? NoOpMetricCollector.create() : MetricCollector .create("ApiCall"); try { apiCallMetricCollector.reportMetric(CoreMetric.SERVICE_ID, "Timestream Query"); apiCallMetricCollector.reportMetric(CoreMetric.OPERATION_NAME, "DescribeEndpoints"); return clientHandler.execute(new ClientExecutionParams() .withOperationName("DescribeEndpoints").withResponseHandler(responseHandler) .withErrorResponseHandler(errorResponseHandler).withInput(describeEndpointsRequest) .withMetricCollector(apiCallMetricCollector) .withMarshaller(new DescribeEndpointsRequestMarshaller(protocolFactory))); } finally { metricPublishers.forEach(p -> p.publish(apiCallMetricCollector.collect())); } } /** *

* Query is a synchronous operation that enables you to execute a query. Query will timeout after 60 seconds. You * must update the default timeout in the SDK to support a timeout of 60 seconds. The result set will be truncated * to 1MB. Service quotas apply. For more information, see Quotas in the Timestream Developer Guide. *

* * @param queryRequest * @return Result of the Query operation returned by the service. * @throws AccessDeniedException * You are not authorized to perform this action. * @throws ConflictException * Unable to poll results for a cancelled query. * @throws InternalServerException * Timestream was unable to fully process this request because of an internal server error. * @throws QueryExecutionException * Timestream was unable to run the query successfully. * @throws ThrottlingException * The request was denied due to request throttling. * @throws ValidationException * Invalid or malformed request. * @throws InvalidEndpointException * The requested endpoint was invalid. * @throws SdkException * Base class for all exceptions that can be thrown by the SDK (both service and client). Can be used for * catch all scenarios. * @throws SdkClientException * If any client side error occurs such as an IO related failure, failure to get credentials, etc. * @throws TimestreamQueryException * Base class for all service exceptions. Unknown exceptions will be thrown as an instance of this type. * @sample TimestreamQueryClient.Query * @see AWS API * Documentation */ @Override public QueryResponse query(QueryRequest queryRequest) throws AccessDeniedException, ConflictException, InternalServerException, QueryExecutionException, ThrottlingException, ValidationException, InvalidEndpointException, AwsServiceException, SdkClientException, TimestreamQueryException { JsonOperationMetadata operationMetadata = JsonOperationMetadata.builder().hasStreamingSuccessResponse(false) .isPayloadJson(true).build(); HttpResponseHandler responseHandler = protocolFactory.createResponseHandler(operationMetadata, QueryResponse::builder); HttpResponseHandler errorResponseHandler = createErrorResponseHandler(protocolFactory, operationMetadata); boolean endpointDiscoveryEnabled = clientConfiguration.option(SdkClientOption.ENDPOINT_DISCOVERY_ENABLED); boolean endpointOverridden = clientConfiguration.option(SdkClientOption.ENDPOINT_OVERRIDDEN) == Boolean.TRUE; if (endpointOverridden) { endpointDiscoveryEnabled = false; } else if (!endpointDiscoveryEnabled) { throw new IllegalStateException( "This operation requires endpoint discovery to be enabled, or for you to specify an endpoint override when the client is created."); } URI cachedEndpoint = null; if (endpointDiscoveryEnabled) { String key = clientConfiguration.option(AwsClientOption.CREDENTIALS_PROVIDER).resolveCredentials().accessKeyId(); EndpointDiscoveryRequest endpointDiscoveryRequest = EndpointDiscoveryRequest.builder().required(true) .defaultEndpoint(clientConfiguration.option(SdkClientOption.ENDPOINT)).build(); cachedEndpoint = endpointDiscoveryCache.get(key, endpointDiscoveryRequest); } List metricPublishers = resolveMetricPublishers(clientConfiguration, queryRequest .overrideConfiguration().orElse(null)); MetricCollector apiCallMetricCollector = metricPublishers.isEmpty() ? NoOpMetricCollector.create() : MetricCollector .create("ApiCall"); try { apiCallMetricCollector.reportMetric(CoreMetric.SERVICE_ID, "Timestream Query"); apiCallMetricCollector.reportMetric(CoreMetric.OPERATION_NAME, "Query"); return clientHandler.execute(new ClientExecutionParams().withOperationName("Query") .withResponseHandler(responseHandler).withErrorResponseHandler(errorResponseHandler) .discoveredEndpoint(cachedEndpoint).withInput(queryRequest).withMetricCollector(apiCallMetricCollector) .withMarshaller(new QueryRequestMarshaller(protocolFactory))); } finally { metricPublishers.forEach(p -> p.publish(apiCallMetricCollector.collect())); } } /** *

* Query is a synchronous operation that enables you to execute a query. Query will timeout after 60 seconds. You * must update the default timeout in the SDK to support a timeout of 60 seconds. The result set will be truncated * to 1MB. Service quotas apply. For more information, see Quotas in the Timestream Developer Guide. *

*
*

* This is a variant of {@link #query(software.amazon.awssdk.services.timestreamquery.model.QueryRequest)} * operation. The return type is a custom iterable that can be used to iterate through all the pages. SDK will * internally handle making service calls for you. *

*

* When this operation is called, a custom iterable is returned but no service calls are made yet. So there is no * guarantee that the request is valid. As you iterate through the iterable, SDK will start lazily loading response * pages by making service calls until there are no pages left or your iteration stops. If there are errors in your * request, you will see the failures only after you start iterating through the iterable. *

* *

* The following are few ways to iterate through the response pages: *

* 1) Using a Stream * *
     * {@code
     * software.amazon.awssdk.services.timestreamquery.paginators.QueryIterable responses = client.queryPaginator(request);
     * responses.stream().forEach(....);
     * }
     * 
* * 2) Using For loop * *
     * {
     *     @code
     *     software.amazon.awssdk.services.timestreamquery.paginators.QueryIterable responses = client.queryPaginator(request);
     *     for (software.amazon.awssdk.services.timestreamquery.model.QueryResponse response : responses) {
     *         // do something;
     *     }
     * }
     * 
* * 3) Use iterator directly * *
     * {@code
     * software.amazon.awssdk.services.timestreamquery.paginators.QueryIterable responses = client.queryPaginator(request);
     * responses.iterator().forEachRemaining(....);
     * }
     * 
*

* Please notice that the configuration of MaxRows won't limit the number of results you get with the paginator. * It only limits the number of results in each page. *

*

* Note: If you prefer to have control on service calls, use the * {@link #query(software.amazon.awssdk.services.timestreamquery.model.QueryRequest)} operation. *

* * @param queryRequest * @return A custom iterable that can be used to iterate through all the response pages. * @throws AccessDeniedException * You are not authorized to perform this action. * @throws ConflictException * Unable to poll results for a cancelled query. * @throws InternalServerException * Timestream was unable to fully process this request because of an internal server error. * @throws QueryExecutionException * Timestream was unable to run the query successfully. * @throws ThrottlingException * The request was denied due to request throttling. * @throws ValidationException * Invalid or malformed request. * @throws InvalidEndpointException * The requested endpoint was invalid. * @throws SdkException * Base class for all exceptions that can be thrown by the SDK (both service and client). Can be used for * catch all scenarios. * @throws SdkClientException * If any client side error occurs such as an IO related failure, failure to get credentials, etc. * @throws TimestreamQueryException * Base class for all service exceptions. Unknown exceptions will be thrown as an instance of this type. * @sample TimestreamQueryClient.Query * @see AWS API * Documentation */ @Override public QueryIterable queryPaginator(QueryRequest queryRequest) throws AccessDeniedException, ConflictException, InternalServerException, QueryExecutionException, ThrottlingException, ValidationException, InvalidEndpointException, AwsServiceException, SdkClientException, TimestreamQueryException { return new QueryIterable(this, applyPaginatorUserAgent(queryRequest)); } private static List resolveMetricPublishers(SdkClientConfiguration clientConfiguration, RequestOverrideConfiguration requestOverrideConfiguration) { List publishers = null; if (requestOverrideConfiguration != null) { publishers = requestOverrideConfiguration.metricPublishers(); } if (publishers == null || publishers.isEmpty()) { publishers = clientConfiguration.option(SdkClientOption.METRIC_PUBLISHERS); } if (publishers == null) { publishers = Collections.emptyList(); } return publishers; } private HttpResponseHandler createErrorResponseHandler(BaseAwsJsonProtocolFactory protocolFactory, JsonOperationMetadata operationMetadata) { return protocolFactory.createErrorResponseHandler(operationMetadata); } private > T init(T builder) { return builder .clientConfiguration(clientConfiguration) .defaultServiceExceptionSupplier(TimestreamQueryException::builder) .protocol(AwsJsonProtocol.AWS_JSON) .protocolVersion("1.0") .registerModeledException( ExceptionMetadata.builder().errorCode("AccessDeniedException") .exceptionBuilderSupplier(AccessDeniedException::builder).build()) .registerModeledException( ExceptionMetadata.builder().errorCode("ValidationException") .exceptionBuilderSupplier(ValidationException::builder).build()) .registerModeledException( ExceptionMetadata.builder().errorCode("ConflictException") .exceptionBuilderSupplier(ConflictException::builder).build()) .registerModeledException( ExceptionMetadata.builder().errorCode("InternalServerException") .exceptionBuilderSupplier(InternalServerException::builder).build()) .registerModeledException( ExceptionMetadata.builder().errorCode("InvalidEndpointException") .exceptionBuilderSupplier(InvalidEndpointException::builder).build()) .registerModeledException( ExceptionMetadata.builder().errorCode("QueryExecutionException") .exceptionBuilderSupplier(QueryExecutionException::builder).build()) .registerModeledException( ExceptionMetadata.builder().errorCode("ThrottlingException") .exceptionBuilderSupplier(ThrottlingException::builder).build()); } @Override public void close() { clientHandler.close(); } private T applyPaginatorUserAgent(T request) { Consumer userAgentApplier = b -> b.addApiName(ApiName.builder() .version(VersionInfo.SDK_VERSION).name("PAGINATED").build()); AwsRequestOverrideConfiguration overrideConfiguration = request.overrideConfiguration() .map(c -> c.toBuilder().applyMutation(userAgentApplier).build()) .orElse((AwsRequestOverrideConfiguration.builder().applyMutation(userAgentApplier).build())); return (T) request.toBuilder().overrideConfiguration(overrideConfiguration).build(); } }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy