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

software.amazon.awssdk.services.personalizeruntime.DefaultPersonalizeRuntimeClient Maven / Gradle / Ivy

Go to download

The AWS Java SDK for Personalize Runtime module holds the client classes that are used for communicating with Personalize Runtime.

There is a newer version: 2.29.15
Show newest version
/*
 * 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.personalizeruntime;

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.client.handler.AwsSyncClientHandler;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.awscore.internal.AwsProtocolMetadata;
import software.amazon.awssdk.awscore.internal.AwsServiceProtocol;
import software.amazon.awssdk.awscore.retry.AwsRetryStrategy;
import software.amazon.awssdk.core.RequestOverrideConfiguration;
import software.amazon.awssdk.core.SdkPlugin;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
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.exception.SdkClientException;
import software.amazon.awssdk.core.http.HttpResponseHandler;
import software.amazon.awssdk.core.metrics.CoreMetric;
import software.amazon.awssdk.core.retry.RetryMode;
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.retries.api.RetryStrategy;
import software.amazon.awssdk.services.personalizeruntime.internal.PersonalizeRuntimeServiceClientConfigurationBuilder;
import software.amazon.awssdk.services.personalizeruntime.model.GetActionRecommendationsRequest;
import software.amazon.awssdk.services.personalizeruntime.model.GetActionRecommendationsResponse;
import software.amazon.awssdk.services.personalizeruntime.model.GetPersonalizedRankingRequest;
import software.amazon.awssdk.services.personalizeruntime.model.GetPersonalizedRankingResponse;
import software.amazon.awssdk.services.personalizeruntime.model.GetRecommendationsRequest;
import software.amazon.awssdk.services.personalizeruntime.model.GetRecommendationsResponse;
import software.amazon.awssdk.services.personalizeruntime.model.InvalidInputException;
import software.amazon.awssdk.services.personalizeruntime.model.PersonalizeRuntimeException;
import software.amazon.awssdk.services.personalizeruntime.model.ResourceNotFoundException;
import software.amazon.awssdk.services.personalizeruntime.transform.GetActionRecommendationsRequestMarshaller;
import software.amazon.awssdk.services.personalizeruntime.transform.GetPersonalizedRankingRequestMarshaller;
import software.amazon.awssdk.services.personalizeruntime.transform.GetRecommendationsRequestMarshaller;
import software.amazon.awssdk.utils.Logger;

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

    private static final AwsProtocolMetadata protocolMetadata = AwsProtocolMetadata.builder()
            .serviceProtocol(AwsServiceProtocol.REST_JSON).build();

    private final SyncClientHandler clientHandler;

    private final AwsJsonProtocolFactory protocolFactory;

    private final SdkClientConfiguration clientConfiguration;

    protected DefaultPersonalizeRuntimeClient(SdkClientConfiguration clientConfiguration) {
        this.clientHandler = new AwsSyncClientHandler(clientConfiguration);
        this.clientConfiguration = clientConfiguration.toBuilder().option(SdkClientOption.SDK_CLIENT, this).build();
        this.protocolFactory = init(AwsJsonProtocolFactory.builder()).build();
    }

    /**
     * 

* Returns a list of recommended actions in sorted in descending order by prediction score. Use the * GetActionRecommendations API if you have a custom campaign that deploys a solution version trained * with a PERSONALIZED_ACTIONS recipe. *

*

* For more information about PERSONALIZED_ACTIONS recipes, see PERSONALIZED_ACTIONS * recipes. For more information about getting action recommendations, see Getting action * recommendations. *

* * @param getActionRecommendationsRequest * @return Result of the GetActionRecommendations operation returned by the service. * @throws InvalidInputException * Provide a valid value for the field or parameter. * @throws ResourceNotFoundException * The specified resource does not exist. * @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 PersonalizeRuntimeException * Base class for all service exceptions. Unknown exceptions will be thrown as an instance of this type. * @sample PersonalizeRuntimeClient.GetActionRecommendations * @see AWS API Documentation */ @Override public GetActionRecommendationsResponse getActionRecommendations( GetActionRecommendationsRequest getActionRecommendationsRequest) throws InvalidInputException, ResourceNotFoundException, AwsServiceException, SdkClientException, PersonalizeRuntimeException { JsonOperationMetadata operationMetadata = JsonOperationMetadata.builder().hasStreamingSuccessResponse(false) .isPayloadJson(true).build(); HttpResponseHandler responseHandler = protocolFactory.createResponseHandler( operationMetadata, GetActionRecommendationsResponse::builder); HttpResponseHandler errorResponseHandler = createErrorResponseHandler(protocolFactory, operationMetadata); SdkClientConfiguration clientConfiguration = updateSdkClientConfiguration(getActionRecommendationsRequest, this.clientConfiguration); List metricPublishers = resolveMetricPublishers(clientConfiguration, getActionRecommendationsRequest .overrideConfiguration().orElse(null)); MetricCollector apiCallMetricCollector = metricPublishers.isEmpty() ? NoOpMetricCollector.create() : MetricCollector .create("ApiCall"); try { apiCallMetricCollector.reportMetric(CoreMetric.SERVICE_ID, "Personalize Runtime"); apiCallMetricCollector.reportMetric(CoreMetric.OPERATION_NAME, "GetActionRecommendations"); return clientHandler .execute(new ClientExecutionParams() .withOperationName("GetActionRecommendations").withProtocolMetadata(protocolMetadata) .withResponseHandler(responseHandler).withErrorResponseHandler(errorResponseHandler) .withRequestConfiguration(clientConfiguration).withInput(getActionRecommendationsRequest) .withMetricCollector(apiCallMetricCollector) .withMarshaller(new GetActionRecommendationsRequestMarshaller(protocolFactory))); } finally { metricPublishers.forEach(p -> p.publish(apiCallMetricCollector.collect())); } } /** *

* Re-ranks a list of recommended items for the given user. The first item in the list is deemed the most likely * item to be of interest to the user. *

* *

* The solution backing the campaign must have been created using a recipe of type PERSONALIZED_RANKING. *

*
* * @param getPersonalizedRankingRequest * @return Result of the GetPersonalizedRanking operation returned by the service. * @throws InvalidInputException * Provide a valid value for the field or parameter. * @throws ResourceNotFoundException * The specified resource does not exist. * @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 PersonalizeRuntimeException * Base class for all service exceptions. Unknown exceptions will be thrown as an instance of this type. * @sample PersonalizeRuntimeClient.GetPersonalizedRanking * @see AWS API Documentation */ @Override public GetPersonalizedRankingResponse getPersonalizedRanking(GetPersonalizedRankingRequest getPersonalizedRankingRequest) throws InvalidInputException, ResourceNotFoundException, AwsServiceException, SdkClientException, PersonalizeRuntimeException { JsonOperationMetadata operationMetadata = JsonOperationMetadata.builder().hasStreamingSuccessResponse(false) .isPayloadJson(true).build(); HttpResponseHandler responseHandler = protocolFactory.createResponseHandler( operationMetadata, GetPersonalizedRankingResponse::builder); HttpResponseHandler errorResponseHandler = createErrorResponseHandler(protocolFactory, operationMetadata); SdkClientConfiguration clientConfiguration = updateSdkClientConfiguration(getPersonalizedRankingRequest, this.clientConfiguration); List metricPublishers = resolveMetricPublishers(clientConfiguration, getPersonalizedRankingRequest .overrideConfiguration().orElse(null)); MetricCollector apiCallMetricCollector = metricPublishers.isEmpty() ? NoOpMetricCollector.create() : MetricCollector .create("ApiCall"); try { apiCallMetricCollector.reportMetric(CoreMetric.SERVICE_ID, "Personalize Runtime"); apiCallMetricCollector.reportMetric(CoreMetric.OPERATION_NAME, "GetPersonalizedRanking"); return clientHandler .execute(new ClientExecutionParams() .withOperationName("GetPersonalizedRanking").withProtocolMetadata(protocolMetadata) .withResponseHandler(responseHandler).withErrorResponseHandler(errorResponseHandler) .withRequestConfiguration(clientConfiguration).withInput(getPersonalizedRankingRequest) .withMetricCollector(apiCallMetricCollector) .withMarshaller(new GetPersonalizedRankingRequestMarshaller(protocolFactory))); } finally { metricPublishers.forEach(p -> p.publish(apiCallMetricCollector.collect())); } } /** *

* Returns a list of recommended items. For campaigns, the campaign's Amazon Resource Name (ARN) is required and the * required user and item input depends on the recipe type used to create the solution backing the campaign as * follows: *

*
    *
  • *

    * USER_PERSONALIZATION - userId required, itemId not used *

    *
  • *
  • *

    * RELATED_ITEMS - itemId required, userId not used *

    *
  • *
* *

* Campaigns that are backed by a solution created using a recipe of type PERSONALIZED_RANKING use the API. *

*
*

* For recommenders, the recommender's ARN is required and the required item and user input depends on the use case * (domain-based recipe) backing the recommender. For information on use case requirements see Choosing recommender use * cases. *

* * @param getRecommendationsRequest * @return Result of the GetRecommendations operation returned by the service. * @throws InvalidInputException * Provide a valid value for the field or parameter. * @throws ResourceNotFoundException * The specified resource does not exist. * @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 PersonalizeRuntimeException * Base class for all service exceptions. Unknown exceptions will be thrown as an instance of this type. * @sample PersonalizeRuntimeClient.GetRecommendations * @see AWS API Documentation */ @Override public GetRecommendationsResponse getRecommendations(GetRecommendationsRequest getRecommendationsRequest) throws InvalidInputException, ResourceNotFoundException, AwsServiceException, SdkClientException, PersonalizeRuntimeException { JsonOperationMetadata operationMetadata = JsonOperationMetadata.builder().hasStreamingSuccessResponse(false) .isPayloadJson(true).build(); HttpResponseHandler responseHandler = protocolFactory.createResponseHandler( operationMetadata, GetRecommendationsResponse::builder); HttpResponseHandler errorResponseHandler = createErrorResponseHandler(protocolFactory, operationMetadata); SdkClientConfiguration clientConfiguration = updateSdkClientConfiguration(getRecommendationsRequest, this.clientConfiguration); List metricPublishers = resolveMetricPublishers(clientConfiguration, getRecommendationsRequest .overrideConfiguration().orElse(null)); MetricCollector apiCallMetricCollector = metricPublishers.isEmpty() ? NoOpMetricCollector.create() : MetricCollector .create("ApiCall"); try { apiCallMetricCollector.reportMetric(CoreMetric.SERVICE_ID, "Personalize Runtime"); apiCallMetricCollector.reportMetric(CoreMetric.OPERATION_NAME, "GetRecommendations"); return clientHandler.execute(new ClientExecutionParams() .withOperationName("GetRecommendations").withProtocolMetadata(protocolMetadata) .withResponseHandler(responseHandler).withErrorResponseHandler(errorResponseHandler) .withRequestConfiguration(clientConfiguration).withInput(getRecommendationsRequest) .withMetricCollector(apiCallMetricCollector) .withMarshaller(new GetRecommendationsRequestMarshaller(protocolFactory))); } finally { metricPublishers.forEach(p -> p.publish(apiCallMetricCollector.collect())); } } @Override public final String serviceName() { return SERVICE_NAME; } 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 void updateRetryStrategyClientConfiguration(SdkClientConfiguration.Builder configuration) { ClientOverrideConfiguration.Builder builder = configuration.asOverrideConfigurationBuilder(); RetryMode retryMode = builder.retryMode(); if (retryMode != null) { configuration.option(SdkClientOption.RETRY_STRATEGY, AwsRetryStrategy.forRetryMode(retryMode)); } else { Consumer> configurator = builder.retryStrategyConfigurator(); if (configurator != null) { RetryStrategy.Builder defaultBuilder = AwsRetryStrategy.defaultRetryStrategy().toBuilder(); configurator.accept(defaultBuilder); configuration.option(SdkClientOption.RETRY_STRATEGY, defaultBuilder.build()); } else { RetryStrategy retryStrategy = builder.retryStrategy(); if (retryStrategy != null) { configuration.option(SdkClientOption.RETRY_STRATEGY, retryStrategy); } } } configuration.option(SdkClientOption.CONFIGURED_RETRY_MODE, null); configuration.option(SdkClientOption.CONFIGURED_RETRY_STRATEGY, null); configuration.option(SdkClientOption.CONFIGURED_RETRY_CONFIGURATOR, null); } private SdkClientConfiguration updateSdkClientConfiguration(SdkRequest request, SdkClientConfiguration clientConfiguration) { List plugins = request.overrideConfiguration().map(c -> c.plugins()).orElse(Collections.emptyList()); SdkClientConfiguration.Builder configuration = clientConfiguration.toBuilder(); if (plugins.isEmpty()) { return configuration.build(); } PersonalizeRuntimeServiceClientConfigurationBuilder serviceConfigBuilder = new PersonalizeRuntimeServiceClientConfigurationBuilder( configuration); for (SdkPlugin plugin : plugins) { plugin.configureClient(serviceConfigBuilder); } updateRetryStrategyClientConfiguration(configuration); return configuration.build(); } private > T init(T builder) { return builder .clientConfiguration(clientConfiguration) .defaultServiceExceptionSupplier(PersonalizeRuntimeException::builder) .protocol(AwsJsonProtocol.REST_JSON) .protocolVersion("1.1") .registerModeledException( ExceptionMetadata.builder().errorCode("InvalidInputException") .exceptionBuilderSupplier(InvalidInputException::builder).httpStatusCode(400).build()) .registerModeledException( ExceptionMetadata.builder().errorCode("ResourceNotFoundException") .exceptionBuilderSupplier(ResourceNotFoundException::builder).httpStatusCode(404).build()); } @Override public final PersonalizeRuntimeServiceClientConfiguration serviceClientConfiguration() { return new PersonalizeRuntimeServiceClientConfigurationBuilder(this.clientConfiguration.toBuilder()).build(); } @Override public void close() { clientHandler.close(); } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy