index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws/greengrass/SubscribeToConfigurationUpdateResponseHandler.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.aws.greengrass; import java.lang.Override; import java.lang.Void; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.aws.greengrass.model.SubscribeToConfigurationUpdateResponse; import software.amazon.awssdk.eventstreamrpc.OperationResponse; import software.amazon.awssdk.eventstreamrpc.StreamResponse; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public final class SubscribeToConfigurationUpdateResponseHandler implements StreamResponse<SubscribeToConfigurationUpdateResponse, EventStreamJsonMessage> { private final OperationResponse<SubscribeToConfigurationUpdateResponse, EventStreamJsonMessage> operationResponse; public SubscribeToConfigurationUpdateResponseHandler( final OperationResponse<SubscribeToConfigurationUpdateResponse, EventStreamJsonMessage> operationResponse) { this.operationResponse = operationResponse; } @Override public CompletableFuture<Void> getRequestFlushFuture() { return operationResponse.getRequestFlushFuture(); } @Override public CompletableFuture<SubscribeToConfigurationUpdateResponse> getResponse() { return operationResponse.getResponse(); } @Override public CompletableFuture<Void> sendStreamEvent(final EventStreamJsonMessage event) { return operationResponse.sendStreamEvent(event); } @Override public CompletableFuture<Void> closeStream() { return operationResponse.closeStream(); } @Override public boolean isClosed() { return operationResponse.isClosed(); } }
5,400
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws/greengrass/GetComponentDetailsResponseHandler.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.aws.greengrass; import java.lang.Override; import java.lang.Void; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.aws.greengrass.model.GetComponentDetailsResponse; import software.amazon.awssdk.eventstreamrpc.OperationResponse; import software.amazon.awssdk.eventstreamrpc.StreamResponse; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public final class GetComponentDetailsResponseHandler implements StreamResponse<GetComponentDetailsResponse, EventStreamJsonMessage> { private final OperationResponse<GetComponentDetailsResponse, EventStreamJsonMessage> operationResponse; public GetComponentDetailsResponseHandler( final OperationResponse<GetComponentDetailsResponse, EventStreamJsonMessage> operationResponse) { this.operationResponse = operationResponse; } @Override public CompletableFuture<Void> getRequestFlushFuture() { return operationResponse.getRequestFlushFuture(); } @Override public CompletableFuture<GetComponentDetailsResponse> getResponse() { return operationResponse.getResponse(); } @Override public CompletableFuture<Void> sendStreamEvent(final EventStreamJsonMessage event) { return operationResponse.sendStreamEvent(event); } @Override public CompletableFuture<Void> closeStream() { return operationResponse.closeStream(); } @Override public boolean isClosed() { return operationResponse.isClosed(); } }
5,401
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws/greengrass/StopComponentResponseHandler.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.aws.greengrass; import java.lang.Override; import java.lang.Void; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.aws.greengrass.model.StopComponentResponse; import software.amazon.awssdk.eventstreamrpc.OperationResponse; import software.amazon.awssdk.eventstreamrpc.StreamResponse; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public final class StopComponentResponseHandler implements StreamResponse<StopComponentResponse, EventStreamJsonMessage> { private final OperationResponse<StopComponentResponse, EventStreamJsonMessage> operationResponse; public StopComponentResponseHandler( final OperationResponse<StopComponentResponse, EventStreamJsonMessage> operationResponse) { this.operationResponse = operationResponse; } @Override public CompletableFuture<Void> getRequestFlushFuture() { return operationResponse.getRequestFlushFuture(); } @Override public CompletableFuture<StopComponentResponse> getResponse() { return operationResponse.getResponse(); } @Override public CompletableFuture<Void> sendStreamEvent(final EventStreamJsonMessage event) { return operationResponse.sendStreamEvent(event); } @Override public CompletableFuture<Void> closeStream() { return operationResponse.closeStream(); } @Override public boolean isClosed() { return operationResponse.isClosed(); } }
5,402
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws/greengrass/UpdateConfigurationResponseHandler.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.aws.greengrass; import java.lang.Override; import java.lang.Void; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.aws.greengrass.model.UpdateConfigurationResponse; import software.amazon.awssdk.eventstreamrpc.OperationResponse; import software.amazon.awssdk.eventstreamrpc.StreamResponse; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public final class UpdateConfigurationResponseHandler implements StreamResponse<UpdateConfigurationResponse, EventStreamJsonMessage> { private final OperationResponse<UpdateConfigurationResponse, EventStreamJsonMessage> operationResponse; public UpdateConfigurationResponseHandler( final OperationResponse<UpdateConfigurationResponse, EventStreamJsonMessage> operationResponse) { this.operationResponse = operationResponse; } @Override public CompletableFuture<Void> getRequestFlushFuture() { return operationResponse.getRequestFlushFuture(); } @Override public CompletableFuture<UpdateConfigurationResponse> getResponse() { return operationResponse.getResponse(); } @Override public CompletableFuture<Void> sendStreamEvent(final EventStreamJsonMessage event) { return operationResponse.sendStreamEvent(event); } @Override public CompletableFuture<Void> closeStream() { return operationResponse.closeStream(); } @Override public boolean isClosed() { return operationResponse.isClosed(); } }
5,403
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws/greengrass/ValidateAuthorizationTokenResponseHandler.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.aws.greengrass; import java.lang.Override; import java.lang.Void; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.aws.greengrass.model.ValidateAuthorizationTokenResponse; import software.amazon.awssdk.eventstreamrpc.OperationResponse; import software.amazon.awssdk.eventstreamrpc.StreamResponse; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public final class ValidateAuthorizationTokenResponseHandler implements StreamResponse<ValidateAuthorizationTokenResponse, EventStreamJsonMessage> { private final OperationResponse<ValidateAuthorizationTokenResponse, EventStreamJsonMessage> operationResponse; public ValidateAuthorizationTokenResponseHandler( final OperationResponse<ValidateAuthorizationTokenResponse, EventStreamJsonMessage> operationResponse) { this.operationResponse = operationResponse; } @Override public CompletableFuture<Void> getRequestFlushFuture() { return operationResponse.getRequestFlushFuture(); } @Override public CompletableFuture<ValidateAuthorizationTokenResponse> getResponse() { return operationResponse.getResponse(); } @Override public CompletableFuture<Void> sendStreamEvent(final EventStreamJsonMessage event) { return operationResponse.sendStreamEvent(event); } @Override public CompletableFuture<Void> closeStream() { return operationResponse.closeStream(); } @Override public boolean isClosed() { return operationResponse.isClosed(); } }
5,404
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws/greengrass/ResumeComponentResponseHandler.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.aws.greengrass; import java.lang.Override; import java.lang.Void; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.aws.greengrass.model.ResumeComponentResponse; import software.amazon.awssdk.eventstreamrpc.OperationResponse; import software.amazon.awssdk.eventstreamrpc.StreamResponse; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public final class ResumeComponentResponseHandler implements StreamResponse<ResumeComponentResponse, EventStreamJsonMessage> { private final OperationResponse<ResumeComponentResponse, EventStreamJsonMessage> operationResponse; public ResumeComponentResponseHandler( final OperationResponse<ResumeComponentResponse, EventStreamJsonMessage> operationResponse) { this.operationResponse = operationResponse; } @Override public CompletableFuture<Void> getRequestFlushFuture() { return operationResponse.getRequestFlushFuture(); } @Override public CompletableFuture<ResumeComponentResponse> getResponse() { return operationResponse.getResponse(); } @Override public CompletableFuture<Void> sendStreamEvent(final EventStreamJsonMessage event) { return operationResponse.sendStreamEvent(event); } @Override public CompletableFuture<Void> closeStream() { return operationResponse.closeStream(); } @Override public boolean isClosed() { return operationResponse.isClosed(); } }
5,405
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws/greengrass/PublishToIoTCoreResponseHandler.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.aws.greengrass; import java.lang.Override; import java.lang.Void; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.aws.greengrass.model.PublishToIoTCoreResponse; import software.amazon.awssdk.eventstreamrpc.OperationResponse; import software.amazon.awssdk.eventstreamrpc.StreamResponse; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public final class PublishToIoTCoreResponseHandler implements StreamResponse<PublishToIoTCoreResponse, EventStreamJsonMessage> { private final OperationResponse<PublishToIoTCoreResponse, EventStreamJsonMessage> operationResponse; public PublishToIoTCoreResponseHandler( final OperationResponse<PublishToIoTCoreResponse, EventStreamJsonMessage> operationResponse) { this.operationResponse = operationResponse; } @Override public CompletableFuture<Void> getRequestFlushFuture() { return operationResponse.getRequestFlushFuture(); } @Override public CompletableFuture<PublishToIoTCoreResponse> getResponse() { return operationResponse.getResponse(); } @Override public CompletableFuture<Void> sendStreamEvent(final EventStreamJsonMessage event) { return operationResponse.sendStreamEvent(event); } @Override public CompletableFuture<Void> closeStream() { return operationResponse.closeStream(); } @Override public boolean isClosed() { return operationResponse.isClosed(); } }
5,406
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws/greengrass/GetThingShadowResponseHandler.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.aws.greengrass; import java.lang.Override; import java.lang.Void; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.aws.greengrass.model.GetThingShadowResponse; import software.amazon.awssdk.eventstreamrpc.OperationResponse; import software.amazon.awssdk.eventstreamrpc.StreamResponse; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public final class GetThingShadowResponseHandler implements StreamResponse<GetThingShadowResponse, EventStreamJsonMessage> { private final OperationResponse<GetThingShadowResponse, EventStreamJsonMessage> operationResponse; public GetThingShadowResponseHandler( final OperationResponse<GetThingShadowResponse, EventStreamJsonMessage> operationResponse) { this.operationResponse = operationResponse; } @Override public CompletableFuture<Void> getRequestFlushFuture() { return operationResponse.getRequestFlushFuture(); } @Override public CompletableFuture<GetThingShadowResponse> getResponse() { return operationResponse.getResponse(); } @Override public CompletableFuture<Void> sendStreamEvent(final EventStreamJsonMessage event) { return operationResponse.sendStreamEvent(event); } @Override public CompletableFuture<Void> closeStream() { return operationResponse.closeStream(); } @Override public boolean isClosed() { return operationResponse.isClosed(); } }
5,407
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws/greengrass/SubscribeToIoTCoreResponseHandler.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.aws.greengrass; import java.lang.Override; import java.lang.Void; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.aws.greengrass.model.SubscribeToIoTCoreResponse; import software.amazon.awssdk.eventstreamrpc.OperationResponse; import software.amazon.awssdk.eventstreamrpc.StreamResponse; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public final class SubscribeToIoTCoreResponseHandler implements StreamResponse<SubscribeToIoTCoreResponse, EventStreamJsonMessage> { private final OperationResponse<SubscribeToIoTCoreResponse, EventStreamJsonMessage> operationResponse; public SubscribeToIoTCoreResponseHandler( final OperationResponse<SubscribeToIoTCoreResponse, EventStreamJsonMessage> operationResponse) { this.operationResponse = operationResponse; } @Override public CompletableFuture<Void> getRequestFlushFuture() { return operationResponse.getRequestFlushFuture(); } @Override public CompletableFuture<SubscribeToIoTCoreResponse> getResponse() { return operationResponse.getResponse(); } @Override public CompletableFuture<Void> sendStreamEvent(final EventStreamJsonMessage event) { return operationResponse.sendStreamEvent(event); } @Override public CompletableFuture<Void> closeStream() { return operationResponse.closeStream(); } @Override public boolean isClosed() { return operationResponse.isClosed(); } }
5,408
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws/greengrass/SubscribeToComponentUpdatesResponseHandler.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.aws.greengrass; import java.lang.Override; import java.lang.Void; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.aws.greengrass.model.SubscribeToComponentUpdatesResponse; import software.amazon.awssdk.eventstreamrpc.OperationResponse; import software.amazon.awssdk.eventstreamrpc.StreamResponse; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public final class SubscribeToComponentUpdatesResponseHandler implements StreamResponse<SubscribeToComponentUpdatesResponse, EventStreamJsonMessage> { private final OperationResponse<SubscribeToComponentUpdatesResponse, EventStreamJsonMessage> operationResponse; public SubscribeToComponentUpdatesResponseHandler( final OperationResponse<SubscribeToComponentUpdatesResponse, EventStreamJsonMessage> operationResponse) { this.operationResponse = operationResponse; } @Override public CompletableFuture<Void> getRequestFlushFuture() { return operationResponse.getRequestFlushFuture(); } @Override public CompletableFuture<SubscribeToComponentUpdatesResponse> getResponse() { return operationResponse.getResponse(); } @Override public CompletableFuture<Void> sendStreamEvent(final EventStreamJsonMessage event) { return operationResponse.sendStreamEvent(event); } @Override public CompletableFuture<Void> closeStream() { return operationResponse.closeStream(); } @Override public boolean isClosed() { return operationResponse.isClosed(); } }
5,409
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws/greengrass/PutComponentMetricResponseHandler.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.aws.greengrass; import java.lang.Override; import java.lang.Void; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.aws.greengrass.model.PutComponentMetricResponse; import software.amazon.awssdk.eventstreamrpc.OperationResponse; import software.amazon.awssdk.eventstreamrpc.StreamResponse; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public final class PutComponentMetricResponseHandler implements StreamResponse<PutComponentMetricResponse, EventStreamJsonMessage> { private final OperationResponse<PutComponentMetricResponse, EventStreamJsonMessage> operationResponse; public PutComponentMetricResponseHandler( final OperationResponse<PutComponentMetricResponse, EventStreamJsonMessage> operationResponse) { this.operationResponse = operationResponse; } @Override public CompletableFuture<Void> getRequestFlushFuture() { return operationResponse.getRequestFlushFuture(); } @Override public CompletableFuture<PutComponentMetricResponse> getResponse() { return operationResponse.getResponse(); } @Override public CompletableFuture<Void> sendStreamEvent(final EventStreamJsonMessage event) { return operationResponse.sendStreamEvent(event); } @Override public CompletableFuture<Void> closeStream() { return operationResponse.closeStream(); } @Override public boolean isClosed() { return operationResponse.isClosed(); } }
5,410
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws/greengrass/SubscribeToTopicResponseHandler.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.aws.greengrass; import java.lang.Override; import java.lang.Void; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicResponse; import software.amazon.awssdk.eventstreamrpc.OperationResponse; import software.amazon.awssdk.eventstreamrpc.StreamResponse; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public final class SubscribeToTopicResponseHandler implements StreamResponse<SubscribeToTopicResponse, EventStreamJsonMessage> { private final OperationResponse<SubscribeToTopicResponse, EventStreamJsonMessage> operationResponse; public SubscribeToTopicResponseHandler( final OperationResponse<SubscribeToTopicResponse, EventStreamJsonMessage> operationResponse) { this.operationResponse = operationResponse; } @Override public CompletableFuture<Void> getRequestFlushFuture() { return operationResponse.getRequestFlushFuture(); } @Override public CompletableFuture<SubscribeToTopicResponse> getResponse() { return operationResponse.getResponse(); } @Override public CompletableFuture<Void> sendStreamEvent(final EventStreamJsonMessage event) { return operationResponse.sendStreamEvent(event); } @Override public CompletableFuture<Void> closeStream() { return operationResponse.closeStream(); } @Override public boolean isClosed() { return operationResponse.isClosed(); } }
5,411
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws/greengrass/GreengrassCoreIPCClientV2.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.aws.greengrass; import java.io.IOException; import java.lang.AutoCloseable; import java.lang.Boolean; import java.lang.Exception; import java.lang.InterruptedException; import java.lang.Override; import java.lang.Runnable; import java.lang.RuntimeException; import java.lang.String; import java.lang.Throwable; import java.lang.Void; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.function.Consumer; import java.util.function.Function; import software.amazon.awssdk.aws.greengrass.model.AuthorizeClientDeviceActionRequest; import software.amazon.awssdk.aws.greengrass.model.AuthorizeClientDeviceActionResponse; import software.amazon.awssdk.aws.greengrass.model.CancelLocalDeploymentRequest; import software.amazon.awssdk.aws.greengrass.model.CancelLocalDeploymentResponse; import software.amazon.awssdk.aws.greengrass.model.CertificateUpdateEvent; import software.amazon.awssdk.aws.greengrass.model.ComponentUpdatePolicyEvents; import software.amazon.awssdk.aws.greengrass.model.ConfigurationUpdateEvents; import software.amazon.awssdk.aws.greengrass.model.CreateDebugPasswordRequest; import software.amazon.awssdk.aws.greengrass.model.CreateDebugPasswordResponse; import software.amazon.awssdk.aws.greengrass.model.CreateLocalDeploymentRequest; import software.amazon.awssdk.aws.greengrass.model.CreateLocalDeploymentResponse; import software.amazon.awssdk.aws.greengrass.model.DeferComponentUpdateRequest; import software.amazon.awssdk.aws.greengrass.model.DeferComponentUpdateResponse; import software.amazon.awssdk.aws.greengrass.model.DeleteThingShadowRequest; import software.amazon.awssdk.aws.greengrass.model.DeleteThingShadowResponse; import software.amazon.awssdk.aws.greengrass.model.GetClientDeviceAuthTokenRequest; import software.amazon.awssdk.aws.greengrass.model.GetClientDeviceAuthTokenResponse; import software.amazon.awssdk.aws.greengrass.model.GetComponentDetailsRequest; import software.amazon.awssdk.aws.greengrass.model.GetComponentDetailsResponse; import software.amazon.awssdk.aws.greengrass.model.GetConfigurationRequest; import software.amazon.awssdk.aws.greengrass.model.GetConfigurationResponse; import software.amazon.awssdk.aws.greengrass.model.GetLocalDeploymentStatusRequest; import software.amazon.awssdk.aws.greengrass.model.GetLocalDeploymentStatusResponse; import software.amazon.awssdk.aws.greengrass.model.GetSecretValueRequest; import software.amazon.awssdk.aws.greengrass.model.GetSecretValueResponse; import software.amazon.awssdk.aws.greengrass.model.GetThingShadowRequest; import software.amazon.awssdk.aws.greengrass.model.GetThingShadowResponse; import software.amazon.awssdk.aws.greengrass.model.IoTCoreMessage; import software.amazon.awssdk.aws.greengrass.model.ListComponentsRequest; import software.amazon.awssdk.aws.greengrass.model.ListComponentsResponse; import software.amazon.awssdk.aws.greengrass.model.ListLocalDeploymentsRequest; import software.amazon.awssdk.aws.greengrass.model.ListLocalDeploymentsResponse; import software.amazon.awssdk.aws.greengrass.model.ListNamedShadowsForThingRequest; import software.amazon.awssdk.aws.greengrass.model.ListNamedShadowsForThingResponse; import software.amazon.awssdk.aws.greengrass.model.PauseComponentRequest; import software.amazon.awssdk.aws.greengrass.model.PauseComponentResponse; import software.amazon.awssdk.aws.greengrass.model.PublishToIoTCoreRequest; import software.amazon.awssdk.aws.greengrass.model.PublishToIoTCoreResponse; import software.amazon.awssdk.aws.greengrass.model.PublishToTopicRequest; import software.amazon.awssdk.aws.greengrass.model.PublishToTopicResponse; import software.amazon.awssdk.aws.greengrass.model.PutComponentMetricRequest; import software.amazon.awssdk.aws.greengrass.model.PutComponentMetricResponse; import software.amazon.awssdk.aws.greengrass.model.RestartComponentRequest; import software.amazon.awssdk.aws.greengrass.model.RestartComponentResponse; import software.amazon.awssdk.aws.greengrass.model.ResumeComponentRequest; import software.amazon.awssdk.aws.greengrass.model.ResumeComponentResponse; import software.amazon.awssdk.aws.greengrass.model.SendConfigurationValidityReportRequest; import software.amazon.awssdk.aws.greengrass.model.SendConfigurationValidityReportResponse; import software.amazon.awssdk.aws.greengrass.model.StopComponentRequest; import software.amazon.awssdk.aws.greengrass.model.StopComponentResponse; import software.amazon.awssdk.aws.greengrass.model.SubscribeToCertificateUpdatesRequest; import software.amazon.awssdk.aws.greengrass.model.SubscribeToCertificateUpdatesResponse; import software.amazon.awssdk.aws.greengrass.model.SubscribeToComponentUpdatesRequest; import software.amazon.awssdk.aws.greengrass.model.SubscribeToComponentUpdatesResponse; import software.amazon.awssdk.aws.greengrass.model.SubscribeToConfigurationUpdateRequest; import software.amazon.awssdk.aws.greengrass.model.SubscribeToConfigurationUpdateResponse; import software.amazon.awssdk.aws.greengrass.model.SubscribeToIoTCoreRequest; import software.amazon.awssdk.aws.greengrass.model.SubscribeToIoTCoreResponse; import software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicRequest; import software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicResponse; import software.amazon.awssdk.aws.greengrass.model.SubscribeToValidateConfigurationUpdatesRequest; import software.amazon.awssdk.aws.greengrass.model.SubscribeToValidateConfigurationUpdatesResponse; import software.amazon.awssdk.aws.greengrass.model.SubscriptionResponseMessage; import software.amazon.awssdk.aws.greengrass.model.UpdateConfigurationRequest; import software.amazon.awssdk.aws.greengrass.model.UpdateConfigurationResponse; import software.amazon.awssdk.aws.greengrass.model.UpdateStateRequest; import software.amazon.awssdk.aws.greengrass.model.UpdateStateResponse; import software.amazon.awssdk.aws.greengrass.model.UpdateThingShadowRequest; import software.amazon.awssdk.aws.greengrass.model.UpdateThingShadowResponse; import software.amazon.awssdk.aws.greengrass.model.ValidateAuthorizationTokenRequest; import software.amazon.awssdk.aws.greengrass.model.ValidateAuthorizationTokenResponse; import software.amazon.awssdk.aws.greengrass.model.ValidateConfigurationUpdateEvents; import software.amazon.awssdk.aws.greengrass.model.VerifyClientDeviceIdentityRequest; import software.amazon.awssdk.aws.greengrass.model.VerifyClientDeviceIdentityResponse; import software.amazon.awssdk.crt.io.ClientBootstrap; import software.amazon.awssdk.crt.io.EventLoopGroup; import software.amazon.awssdk.crt.io.SocketOptions; import software.amazon.awssdk.crt.io.SocketOptions.SocketDomain; import software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection; import software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnectionConfig; import software.amazon.awssdk.eventstreamrpc.GreengrassConnectMessageSupplier; import software.amazon.awssdk.eventstreamrpc.StreamResponseHandler; /** * V2 Client for Greengrass. */ public class GreengrassCoreIPCClientV2 implements AutoCloseable { protected GreengrassCoreIPC client; protected Executor executor; protected EventStreamRPCConnection connection; GreengrassCoreIPCClientV2(GreengrassCoreIPC client, EventStreamRPCConnection connection, Executor executor) { this.client = client; this.connection = connection; this.executor = executor; } @Override public void close() throws Exception { if (client instanceof AutoCloseable) { ((AutoCloseable) client).close(); } if (connection != null) { connection.close(); } } public GreengrassCoreIPC getClient() { return client; } public static Builder builder() { return new Builder(); } /** * Perform the authorizeClientDeviceAction operation synchronously. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object */ public AuthorizeClientDeviceActionResponse authorizeClientDeviceAction( final AuthorizeClientDeviceActionRequest request) throws InterruptedException { return getResponse(this.authorizeClientDeviceActionAsync(request)); } /** * Perform the authorizeClientDeviceAction operation asynchronously. * * @return a future which resolves to the response * * @param request request object */ public CompletableFuture<AuthorizeClientDeviceActionResponse> authorizeClientDeviceActionAsync( final AuthorizeClientDeviceActionRequest request) { return client.authorizeClientDeviceAction(request, Optional.empty()).getResponse(); } /** * Perform the cancelLocalDeployment operation synchronously. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object */ public CancelLocalDeploymentResponse cancelLocalDeployment( final CancelLocalDeploymentRequest request) throws InterruptedException { return getResponse(this.cancelLocalDeploymentAsync(request)); } /** * Perform the cancelLocalDeployment operation asynchronously. * * @return a future which resolves to the response * * @param request request object */ public CompletableFuture<CancelLocalDeploymentResponse> cancelLocalDeploymentAsync( final CancelLocalDeploymentRequest request) { return client.cancelLocalDeployment(request, Optional.empty()).getResponse(); } /** * Perform the createDebugPassword operation synchronously. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object */ public CreateDebugPasswordResponse createDebugPassword(final CreateDebugPasswordRequest request) throws InterruptedException { return getResponse(this.createDebugPasswordAsync(request)); } /** * Perform the createDebugPassword operation asynchronously. * * @return a future which resolves to the response * * @param request request object */ public CompletableFuture<CreateDebugPasswordResponse> createDebugPasswordAsync( final CreateDebugPasswordRequest request) { return client.createDebugPassword(request, Optional.empty()).getResponse(); } /** * Perform the createLocalDeployment operation synchronously. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object */ public CreateLocalDeploymentResponse createLocalDeployment( final CreateLocalDeploymentRequest request) throws InterruptedException { return getResponse(this.createLocalDeploymentAsync(request)); } /** * Perform the createLocalDeployment operation asynchronously. * * @return a future which resolves to the response * * @param request request object */ public CompletableFuture<CreateLocalDeploymentResponse> createLocalDeploymentAsync( final CreateLocalDeploymentRequest request) { return client.createLocalDeployment(request, Optional.empty()).getResponse(); } /** * Perform the deferComponentUpdate operation synchronously. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object */ public DeferComponentUpdateResponse deferComponentUpdate( final DeferComponentUpdateRequest request) throws InterruptedException { return getResponse(this.deferComponentUpdateAsync(request)); } /** * Perform the deferComponentUpdate operation asynchronously. * * @return a future which resolves to the response * * @param request request object */ public CompletableFuture<DeferComponentUpdateResponse> deferComponentUpdateAsync( final DeferComponentUpdateRequest request) { return client.deferComponentUpdate(request, Optional.empty()).getResponse(); } /** * Perform the deleteThingShadow operation synchronously. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object */ public DeleteThingShadowResponse deleteThingShadow(final DeleteThingShadowRequest request) throws InterruptedException { return getResponse(this.deleteThingShadowAsync(request)); } /** * Perform the deleteThingShadow operation asynchronously. * * @return a future which resolves to the response * * @param request request object */ public CompletableFuture<DeleteThingShadowResponse> deleteThingShadowAsync( final DeleteThingShadowRequest request) { return client.deleteThingShadow(request, Optional.empty()).getResponse(); } /** * Perform the getClientDeviceAuthToken operation synchronously. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object */ public GetClientDeviceAuthTokenResponse getClientDeviceAuthToken( final GetClientDeviceAuthTokenRequest request) throws InterruptedException { return getResponse(this.getClientDeviceAuthTokenAsync(request)); } /** * Perform the getClientDeviceAuthToken operation asynchronously. * * @return a future which resolves to the response * * @param request request object */ public CompletableFuture<GetClientDeviceAuthTokenResponse> getClientDeviceAuthTokenAsync( final GetClientDeviceAuthTokenRequest request) { return client.getClientDeviceAuthToken(request, Optional.empty()).getResponse(); } /** * Perform the getComponentDetails operation synchronously. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object */ public GetComponentDetailsResponse getComponentDetails(final GetComponentDetailsRequest request) throws InterruptedException { return getResponse(this.getComponentDetailsAsync(request)); } /** * Perform the getComponentDetails operation asynchronously. * * @return a future which resolves to the response * * @param request request object */ public CompletableFuture<GetComponentDetailsResponse> getComponentDetailsAsync( final GetComponentDetailsRequest request) { return client.getComponentDetails(request, Optional.empty()).getResponse(); } /** * Perform the getConfiguration operation synchronously. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object */ public GetConfigurationResponse getConfiguration(final GetConfigurationRequest request) throws InterruptedException { return getResponse(this.getConfigurationAsync(request)); } /** * Perform the getConfiguration operation asynchronously. * * @return a future which resolves to the response * * @param request request object */ public CompletableFuture<GetConfigurationResponse> getConfigurationAsync( final GetConfigurationRequest request) { return client.getConfiguration(request, Optional.empty()).getResponse(); } /** * Perform the getLocalDeploymentStatus operation synchronously. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object */ public GetLocalDeploymentStatusResponse getLocalDeploymentStatus( final GetLocalDeploymentStatusRequest request) throws InterruptedException { return getResponse(this.getLocalDeploymentStatusAsync(request)); } /** * Perform the getLocalDeploymentStatus operation asynchronously. * * @return a future which resolves to the response * * @param request request object */ public CompletableFuture<GetLocalDeploymentStatusResponse> getLocalDeploymentStatusAsync( final GetLocalDeploymentStatusRequest request) { return client.getLocalDeploymentStatus(request, Optional.empty()).getResponse(); } /** * Perform the getSecretValue operation synchronously. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object */ public GetSecretValueResponse getSecretValue(final GetSecretValueRequest request) throws InterruptedException { return getResponse(this.getSecretValueAsync(request)); } /** * Perform the getSecretValue operation asynchronously. * * @return a future which resolves to the response * * @param request request object */ public CompletableFuture<GetSecretValueResponse> getSecretValueAsync( final GetSecretValueRequest request) { return client.getSecretValue(request, Optional.empty()).getResponse(); } /** * Perform the getThingShadow operation synchronously. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object */ public GetThingShadowResponse getThingShadow(final GetThingShadowRequest request) throws InterruptedException { return getResponse(this.getThingShadowAsync(request)); } /** * Perform the getThingShadow operation asynchronously. * * @return a future which resolves to the response * * @param request request object */ public CompletableFuture<GetThingShadowResponse> getThingShadowAsync( final GetThingShadowRequest request) { return client.getThingShadow(request, Optional.empty()).getResponse(); } /** * Perform the listComponents operation synchronously. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object */ public ListComponentsResponse listComponents(final ListComponentsRequest request) throws InterruptedException { return getResponse(this.listComponentsAsync(request)); } /** * Perform the listComponents operation asynchronously. * * @return a future which resolves to the response * * @param request request object */ public CompletableFuture<ListComponentsResponse> listComponentsAsync( final ListComponentsRequest request) { return client.listComponents(request, Optional.empty()).getResponse(); } /** * Perform the listLocalDeployments operation synchronously. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object */ public ListLocalDeploymentsResponse listLocalDeployments( final ListLocalDeploymentsRequest request) throws InterruptedException { return getResponse(this.listLocalDeploymentsAsync(request)); } /** * Perform the listLocalDeployments operation asynchronously. * * @return a future which resolves to the response * * @param request request object */ public CompletableFuture<ListLocalDeploymentsResponse> listLocalDeploymentsAsync( final ListLocalDeploymentsRequest request) { return client.listLocalDeployments(request, Optional.empty()).getResponse(); } /** * Perform the listNamedShadowsForThing operation synchronously. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object */ public ListNamedShadowsForThingResponse listNamedShadowsForThing( final ListNamedShadowsForThingRequest request) throws InterruptedException { return getResponse(this.listNamedShadowsForThingAsync(request)); } /** * Perform the listNamedShadowsForThing operation asynchronously. * * @return a future which resolves to the response * * @param request request object */ public CompletableFuture<ListNamedShadowsForThingResponse> listNamedShadowsForThingAsync( final ListNamedShadowsForThingRequest request) { return client.listNamedShadowsForThing(request, Optional.empty()).getResponse(); } /** * Perform the pauseComponent operation synchronously. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object */ public PauseComponentResponse pauseComponent(final PauseComponentRequest request) throws InterruptedException { return getResponse(this.pauseComponentAsync(request)); } /** * Perform the pauseComponent operation asynchronously. * * @return a future which resolves to the response * * @param request request object */ public CompletableFuture<PauseComponentResponse> pauseComponentAsync( final PauseComponentRequest request) { return client.pauseComponent(request, Optional.empty()).getResponse(); } /** * Perform the publishToIoTCore operation synchronously. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object */ public PublishToIoTCoreResponse publishToIoTCore(final PublishToIoTCoreRequest request) throws InterruptedException { return getResponse(this.publishToIoTCoreAsync(request)); } /** * Perform the publishToIoTCore operation asynchronously. * * @return a future which resolves to the response * * @param request request object */ public CompletableFuture<PublishToIoTCoreResponse> publishToIoTCoreAsync( final PublishToIoTCoreRequest request) { return client.publishToIoTCore(request, Optional.empty()).getResponse(); } /** * Perform the publishToTopic operation synchronously. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object */ public PublishToTopicResponse publishToTopic(final PublishToTopicRequest request) throws InterruptedException { return getResponse(this.publishToTopicAsync(request)); } /** * Perform the publishToTopic operation asynchronously. * * @return a future which resolves to the response * * @param request request object */ public CompletableFuture<PublishToTopicResponse> publishToTopicAsync( final PublishToTopicRequest request) { return client.publishToTopic(request, Optional.empty()).getResponse(); } /** * Perform the putComponentMetric operation synchronously. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object */ public PutComponentMetricResponse putComponentMetric(final PutComponentMetricRequest request) throws InterruptedException { return getResponse(this.putComponentMetricAsync(request)); } /** * Perform the putComponentMetric operation asynchronously. * * @return a future which resolves to the response * * @param request request object */ public CompletableFuture<PutComponentMetricResponse> putComponentMetricAsync( final PutComponentMetricRequest request) { return client.putComponentMetric(request, Optional.empty()).getResponse(); } /** * Perform the restartComponent operation synchronously. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object */ public RestartComponentResponse restartComponent(final RestartComponentRequest request) throws InterruptedException { return getResponse(this.restartComponentAsync(request)); } /** * Perform the restartComponent operation asynchronously. * * @return a future which resolves to the response * * @param request request object */ public CompletableFuture<RestartComponentResponse> restartComponentAsync( final RestartComponentRequest request) { return client.restartComponent(request, Optional.empty()).getResponse(); } /** * Perform the resumeComponent operation synchronously. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object */ public ResumeComponentResponse resumeComponent(final ResumeComponentRequest request) throws InterruptedException { return getResponse(this.resumeComponentAsync(request)); } /** * Perform the resumeComponent operation asynchronously. * * @return a future which resolves to the response * * @param request request object */ public CompletableFuture<ResumeComponentResponse> resumeComponentAsync( final ResumeComponentRequest request) { return client.resumeComponent(request, Optional.empty()).getResponse(); } /** * Perform the sendConfigurationValidityReport operation synchronously. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object */ public SendConfigurationValidityReportResponse sendConfigurationValidityReport( final SendConfigurationValidityReportRequest request) throws InterruptedException { return getResponse(this.sendConfigurationValidityReportAsync(request)); } /** * Perform the sendConfigurationValidityReport operation asynchronously. * * @return a future which resolves to the response * * @param request request object */ public CompletableFuture<SendConfigurationValidityReportResponse> sendConfigurationValidityReportAsync( final SendConfigurationValidityReportRequest request) { return client.sendConfigurationValidityReport(request, Optional.empty()).getResponse(); } /** * Perform the stopComponent operation synchronously. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object */ public StopComponentResponse stopComponent(final StopComponentRequest request) throws InterruptedException { return getResponse(this.stopComponentAsync(request)); } /** * Perform the stopComponent operation asynchronously. * * @return a future which resolves to the response * * @param request request object */ public CompletableFuture<StopComponentResponse> stopComponentAsync( final StopComponentRequest request) { return client.stopComponent(request, Optional.empty()).getResponse(); } /** * Perform the subscribeToCertificateUpdates operation asynchronously. * The initial response or error will be returned as the result of the asynchronous future, further events will * arrive via the streaming callbacks. * * @return a future which resolves to the response * * @param request request object * @param onStreamEvent Callback for stream events. If an executor is provided, this method will run in the executor. * @param onStreamError Callback for stream errors. Return true to close the stream, * return false to keep the stream open. Even if an executor is provided, * this method will not run in the executor. * @param onStreamClosed Callback for when the stream closes. If an executor is provided, this method will run in the executor. */ public StreamingResponse<CompletableFuture<SubscribeToCertificateUpdatesResponse>, SubscribeToCertificateUpdatesResponseHandler> subscribeToCertificateUpdatesAsync( final SubscribeToCertificateUpdatesRequest request, Consumer<CertificateUpdateEvent> onStreamEvent, Optional<Function<Throwable, Boolean>> onStreamError, Optional<Runnable> onStreamClosed) { return this.subscribeToCertificateUpdatesAsync(request, getStreamingResponseHandler(onStreamEvent, onStreamError, onStreamClosed)); } /** * Perform the subscribeToCertificateUpdates operation synchronously. * The initial response or error will be returned synchronously, * further events will arrive via the streaming callbacks. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object * @param onStreamEvent Callback for stream events. If an executor is provided, this method will run in the executor. * @param onStreamError Callback for stream errors. Return true to close the stream, * return false to keep the stream open. Even if an executor is provided, * this method will not run in the executor. * @param onStreamClosed Callback for when the stream closes. If an executor is provided, this method will run in the executor. */ public StreamingResponse<SubscribeToCertificateUpdatesResponse, SubscribeToCertificateUpdatesResponseHandler> subscribeToCertificateUpdates( final SubscribeToCertificateUpdatesRequest request, Consumer<CertificateUpdateEvent> onStreamEvent, Optional<Function<Throwable, Boolean>> onStreamError, Optional<Runnable> onStreamClosed) throws InterruptedException { StreamingResponse<CompletableFuture<SubscribeToCertificateUpdatesResponse>, SubscribeToCertificateUpdatesResponseHandler> r = this.subscribeToCertificateUpdatesAsync(request, onStreamEvent, onStreamError, onStreamClosed); return new StreamingResponse<>(getResponse(r.getResponse()), r.getHandler()); } /** * Perform the subscribeToCertificateUpdates operation synchronously. * The initial response or error will be returned synchronously, further events will * arrive via the streaming callbacks. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object * @param streamResponseHandler Methods on this object will be called as stream events happen on this operation. * If an executor is provided, the onStreamEvent and onStreamClosed methods will run in the executor. */ public StreamingResponse<SubscribeToCertificateUpdatesResponse, SubscribeToCertificateUpdatesResponseHandler> subscribeToCertificateUpdates( final SubscribeToCertificateUpdatesRequest request, final StreamResponseHandler<CertificateUpdateEvent> streamResponseHandler) throws InterruptedException { StreamingResponse<CompletableFuture<SubscribeToCertificateUpdatesResponse>, SubscribeToCertificateUpdatesResponseHandler> r = this.subscribeToCertificateUpdatesAsync(request, streamResponseHandler); return new StreamingResponse<>(getResponse(r.getResponse()), r.getHandler()); } /** * Perform the subscribeToCertificateUpdates operation asynchronously. * The initial response or error will be returned as the result of the asynchronous future, further events will * arrive via the streaming callbacks. * * @return a future which resolves to the response * * @param request request object * @param streamResponseHandler Methods on this object will be called as stream events happen on this operation. * If an executor is provided, the onStreamEvent and onStreamClosed methods will run in the executor. */ public StreamingResponse<CompletableFuture<SubscribeToCertificateUpdatesResponse>, SubscribeToCertificateUpdatesResponseHandler> subscribeToCertificateUpdatesAsync( final SubscribeToCertificateUpdatesRequest request, final StreamResponseHandler<CertificateUpdateEvent> streamResponseHandler) { SubscribeToCertificateUpdatesResponseHandler r = client.subscribeToCertificateUpdates(request, Optional.ofNullable(getStreamingResponseHandler(streamResponseHandler))); return new StreamingResponse<>(r.getResponse(), r); } /** * Perform the subscribeToComponentUpdates operation asynchronously. * The initial response or error will be returned as the result of the asynchronous future, further events will * arrive via the streaming callbacks. * * @return a future which resolves to the response * * @param request request object * @param onStreamEvent Callback for stream events. If an executor is provided, this method will run in the executor. * @param onStreamError Callback for stream errors. Return true to close the stream, * return false to keep the stream open. Even if an executor is provided, * this method will not run in the executor. * @param onStreamClosed Callback for when the stream closes. If an executor is provided, this method will run in the executor. */ public StreamingResponse<CompletableFuture<SubscribeToComponentUpdatesResponse>, SubscribeToComponentUpdatesResponseHandler> subscribeToComponentUpdatesAsync( final SubscribeToComponentUpdatesRequest request, Consumer<ComponentUpdatePolicyEvents> onStreamEvent, Optional<Function<Throwable, Boolean>> onStreamError, Optional<Runnable> onStreamClosed) { return this.subscribeToComponentUpdatesAsync(request, getStreamingResponseHandler(onStreamEvent, onStreamError, onStreamClosed)); } /** * Perform the subscribeToComponentUpdates operation synchronously. * The initial response or error will be returned synchronously, * further events will arrive via the streaming callbacks. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object * @param onStreamEvent Callback for stream events. If an executor is provided, this method will run in the executor. * @param onStreamError Callback for stream errors. Return true to close the stream, * return false to keep the stream open. Even if an executor is provided, * this method will not run in the executor. * @param onStreamClosed Callback for when the stream closes. If an executor is provided, this method will run in the executor. */ public StreamingResponse<SubscribeToComponentUpdatesResponse, SubscribeToComponentUpdatesResponseHandler> subscribeToComponentUpdates( final SubscribeToComponentUpdatesRequest request, Consumer<ComponentUpdatePolicyEvents> onStreamEvent, Optional<Function<Throwable, Boolean>> onStreamError, Optional<Runnable> onStreamClosed) throws InterruptedException { StreamingResponse<CompletableFuture<SubscribeToComponentUpdatesResponse>, SubscribeToComponentUpdatesResponseHandler> r = this.subscribeToComponentUpdatesAsync(request, onStreamEvent, onStreamError, onStreamClosed); return new StreamingResponse<>(getResponse(r.getResponse()), r.getHandler()); } /** * Perform the subscribeToComponentUpdates operation synchronously. * The initial response or error will be returned synchronously, further events will * arrive via the streaming callbacks. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object * @param streamResponseHandler Methods on this object will be called as stream events happen on this operation. * If an executor is provided, the onStreamEvent and onStreamClosed methods will run in the executor. */ public StreamingResponse<SubscribeToComponentUpdatesResponse, SubscribeToComponentUpdatesResponseHandler> subscribeToComponentUpdates( final SubscribeToComponentUpdatesRequest request, final StreamResponseHandler<ComponentUpdatePolicyEvents> streamResponseHandler) throws InterruptedException { StreamingResponse<CompletableFuture<SubscribeToComponentUpdatesResponse>, SubscribeToComponentUpdatesResponseHandler> r = this.subscribeToComponentUpdatesAsync(request, streamResponseHandler); return new StreamingResponse<>(getResponse(r.getResponse()), r.getHandler()); } /** * Perform the subscribeToComponentUpdates operation asynchronously. * The initial response or error will be returned as the result of the asynchronous future, further events will * arrive via the streaming callbacks. * * @return a future which resolves to the response * * @param request request object * @param streamResponseHandler Methods on this object will be called as stream events happen on this operation. * If an executor is provided, the onStreamEvent and onStreamClosed methods will run in the executor. */ public StreamingResponse<CompletableFuture<SubscribeToComponentUpdatesResponse>, SubscribeToComponentUpdatesResponseHandler> subscribeToComponentUpdatesAsync( final SubscribeToComponentUpdatesRequest request, final StreamResponseHandler<ComponentUpdatePolicyEvents> streamResponseHandler) { SubscribeToComponentUpdatesResponseHandler r = client.subscribeToComponentUpdates(request, Optional.ofNullable(getStreamingResponseHandler(streamResponseHandler))); return new StreamingResponse<>(r.getResponse(), r); } /** * Perform the subscribeToConfigurationUpdate operation asynchronously. * The initial response or error will be returned as the result of the asynchronous future, further events will * arrive via the streaming callbacks. * * @return a future which resolves to the response * * @param request request object * @param onStreamEvent Callback for stream events. If an executor is provided, this method will run in the executor. * @param onStreamError Callback for stream errors. Return true to close the stream, * return false to keep the stream open. Even if an executor is provided, * this method will not run in the executor. * @param onStreamClosed Callback for when the stream closes. If an executor is provided, this method will run in the executor. */ public StreamingResponse<CompletableFuture<SubscribeToConfigurationUpdateResponse>, SubscribeToConfigurationUpdateResponseHandler> subscribeToConfigurationUpdateAsync( final SubscribeToConfigurationUpdateRequest request, Consumer<ConfigurationUpdateEvents> onStreamEvent, Optional<Function<Throwable, Boolean>> onStreamError, Optional<Runnable> onStreamClosed) { return this.subscribeToConfigurationUpdateAsync(request, getStreamingResponseHandler(onStreamEvent, onStreamError, onStreamClosed)); } /** * Perform the subscribeToConfigurationUpdate operation synchronously. * The initial response or error will be returned synchronously, * further events will arrive via the streaming callbacks. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object * @param onStreamEvent Callback for stream events. If an executor is provided, this method will run in the executor. * @param onStreamError Callback for stream errors. Return true to close the stream, * return false to keep the stream open. Even if an executor is provided, * this method will not run in the executor. * @param onStreamClosed Callback for when the stream closes. If an executor is provided, this method will run in the executor. */ public StreamingResponse<SubscribeToConfigurationUpdateResponse, SubscribeToConfigurationUpdateResponseHandler> subscribeToConfigurationUpdate( final SubscribeToConfigurationUpdateRequest request, Consumer<ConfigurationUpdateEvents> onStreamEvent, Optional<Function<Throwable, Boolean>> onStreamError, Optional<Runnable> onStreamClosed) throws InterruptedException { StreamingResponse<CompletableFuture<SubscribeToConfigurationUpdateResponse>, SubscribeToConfigurationUpdateResponseHandler> r = this.subscribeToConfigurationUpdateAsync(request, onStreamEvent, onStreamError, onStreamClosed); return new StreamingResponse<>(getResponse(r.getResponse()), r.getHandler()); } /** * Perform the subscribeToConfigurationUpdate operation synchronously. * The initial response or error will be returned synchronously, further events will * arrive via the streaming callbacks. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object * @param streamResponseHandler Methods on this object will be called as stream events happen on this operation. * If an executor is provided, the onStreamEvent and onStreamClosed methods will run in the executor. */ public StreamingResponse<SubscribeToConfigurationUpdateResponse, SubscribeToConfigurationUpdateResponseHandler> subscribeToConfigurationUpdate( final SubscribeToConfigurationUpdateRequest request, final StreamResponseHandler<ConfigurationUpdateEvents> streamResponseHandler) throws InterruptedException { StreamingResponse<CompletableFuture<SubscribeToConfigurationUpdateResponse>, SubscribeToConfigurationUpdateResponseHandler> r = this.subscribeToConfigurationUpdateAsync(request, streamResponseHandler); return new StreamingResponse<>(getResponse(r.getResponse()), r.getHandler()); } /** * Perform the subscribeToConfigurationUpdate operation asynchronously. * The initial response or error will be returned as the result of the asynchronous future, further events will * arrive via the streaming callbacks. * * @return a future which resolves to the response * * @param request request object * @param streamResponseHandler Methods on this object will be called as stream events happen on this operation. * If an executor is provided, the onStreamEvent and onStreamClosed methods will run in the executor. */ public StreamingResponse<CompletableFuture<SubscribeToConfigurationUpdateResponse>, SubscribeToConfigurationUpdateResponseHandler> subscribeToConfigurationUpdateAsync( final SubscribeToConfigurationUpdateRequest request, final StreamResponseHandler<ConfigurationUpdateEvents> streamResponseHandler) { SubscribeToConfigurationUpdateResponseHandler r = client.subscribeToConfigurationUpdate(request, Optional.ofNullable(getStreamingResponseHandler(streamResponseHandler))); return new StreamingResponse<>(r.getResponse(), r); } /** * Perform the subscribeToIoTCore operation asynchronously. * The initial response or error will be returned as the result of the asynchronous future, further events will * arrive via the streaming callbacks. * * @return a future which resolves to the response * * @param request request object * @param onStreamEvent Callback for stream events. If an executor is provided, this method will run in the executor. * @param onStreamError Callback for stream errors. Return true to close the stream, * return false to keep the stream open. Even if an executor is provided, * this method will not run in the executor. * @param onStreamClosed Callback for when the stream closes. If an executor is provided, this method will run in the executor. */ public StreamingResponse<CompletableFuture<SubscribeToIoTCoreResponse>, SubscribeToIoTCoreResponseHandler> subscribeToIoTCoreAsync( final SubscribeToIoTCoreRequest request, Consumer<IoTCoreMessage> onStreamEvent, Optional<Function<Throwable, Boolean>> onStreamError, Optional<Runnable> onStreamClosed) { return this.subscribeToIoTCoreAsync(request, getStreamingResponseHandler(onStreamEvent, onStreamError, onStreamClosed)); } /** * Perform the subscribeToIoTCore operation synchronously. * The initial response or error will be returned synchronously, * further events will arrive via the streaming callbacks. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object * @param onStreamEvent Callback for stream events. If an executor is provided, this method will run in the executor. * @param onStreamError Callback for stream errors. Return true to close the stream, * return false to keep the stream open. Even if an executor is provided, * this method will not run in the executor. * @param onStreamClosed Callback for when the stream closes. If an executor is provided, this method will run in the executor. */ public StreamingResponse<SubscribeToIoTCoreResponse, SubscribeToIoTCoreResponseHandler> subscribeToIoTCore( final SubscribeToIoTCoreRequest request, Consumer<IoTCoreMessage> onStreamEvent, Optional<Function<Throwable, Boolean>> onStreamError, Optional<Runnable> onStreamClosed) throws InterruptedException { StreamingResponse<CompletableFuture<SubscribeToIoTCoreResponse>, SubscribeToIoTCoreResponseHandler> r = this.subscribeToIoTCoreAsync(request, onStreamEvent, onStreamError, onStreamClosed); return new StreamingResponse<>(getResponse(r.getResponse()), r.getHandler()); } /** * Perform the subscribeToIoTCore operation synchronously. * The initial response or error will be returned synchronously, further events will * arrive via the streaming callbacks. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object * @param streamResponseHandler Methods on this object will be called as stream events happen on this operation. * If an executor is provided, the onStreamEvent and onStreamClosed methods will run in the executor. */ public StreamingResponse<SubscribeToIoTCoreResponse, SubscribeToIoTCoreResponseHandler> subscribeToIoTCore( final SubscribeToIoTCoreRequest request, final StreamResponseHandler<IoTCoreMessage> streamResponseHandler) throws InterruptedException { StreamingResponse<CompletableFuture<SubscribeToIoTCoreResponse>, SubscribeToIoTCoreResponseHandler> r = this.subscribeToIoTCoreAsync(request, streamResponseHandler); return new StreamingResponse<>(getResponse(r.getResponse()), r.getHandler()); } /** * Perform the subscribeToIoTCore operation asynchronously. * The initial response or error will be returned as the result of the asynchronous future, further events will * arrive via the streaming callbacks. * * @return a future which resolves to the response * * @param request request object * @param streamResponseHandler Methods on this object will be called as stream events happen on this operation. * If an executor is provided, the onStreamEvent and onStreamClosed methods will run in the executor. */ public StreamingResponse<CompletableFuture<SubscribeToIoTCoreResponse>, SubscribeToIoTCoreResponseHandler> subscribeToIoTCoreAsync( final SubscribeToIoTCoreRequest request, final StreamResponseHandler<IoTCoreMessage> streamResponseHandler) { SubscribeToIoTCoreResponseHandler r = client.subscribeToIoTCore(request, Optional.ofNullable(getStreamingResponseHandler(streamResponseHandler))); return new StreamingResponse<>(r.getResponse(), r); } /** * Perform the subscribeToTopic operation asynchronously. * The initial response or error will be returned as the result of the asynchronous future, further events will * arrive via the streaming callbacks. * * @return a future which resolves to the response * * @param request request object * @param onStreamEvent Callback for stream events. If an executor is provided, this method will run in the executor. * @param onStreamError Callback for stream errors. Return true to close the stream, * return false to keep the stream open. Even if an executor is provided, * this method will not run in the executor. * @param onStreamClosed Callback for when the stream closes. If an executor is provided, this method will run in the executor. */ public StreamingResponse<CompletableFuture<SubscribeToTopicResponse>, SubscribeToTopicResponseHandler> subscribeToTopicAsync( final SubscribeToTopicRequest request, Consumer<SubscriptionResponseMessage> onStreamEvent, Optional<Function<Throwable, Boolean>> onStreamError, Optional<Runnable> onStreamClosed) { return this.subscribeToTopicAsync(request, getStreamingResponseHandler(onStreamEvent, onStreamError, onStreamClosed)); } /** * Perform the subscribeToTopic operation synchronously. * The initial response or error will be returned synchronously, * further events will arrive via the streaming callbacks. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object * @param onStreamEvent Callback for stream events. If an executor is provided, this method will run in the executor. * @param onStreamError Callback for stream errors. Return true to close the stream, * return false to keep the stream open. Even if an executor is provided, * this method will not run in the executor. * @param onStreamClosed Callback for when the stream closes. If an executor is provided, this method will run in the executor. */ public StreamingResponse<SubscribeToTopicResponse, SubscribeToTopicResponseHandler> subscribeToTopic( final SubscribeToTopicRequest request, Consumer<SubscriptionResponseMessage> onStreamEvent, Optional<Function<Throwable, Boolean>> onStreamError, Optional<Runnable> onStreamClosed) throws InterruptedException { StreamingResponse<CompletableFuture<SubscribeToTopicResponse>, SubscribeToTopicResponseHandler> r = this.subscribeToTopicAsync(request, onStreamEvent, onStreamError, onStreamClosed); return new StreamingResponse<>(getResponse(r.getResponse()), r.getHandler()); } /** * Perform the subscribeToTopic operation synchronously. * The initial response or error will be returned synchronously, further events will * arrive via the streaming callbacks. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object * @param streamResponseHandler Methods on this object will be called as stream events happen on this operation. * If an executor is provided, the onStreamEvent and onStreamClosed methods will run in the executor. */ public StreamingResponse<SubscribeToTopicResponse, SubscribeToTopicResponseHandler> subscribeToTopic( final SubscribeToTopicRequest request, final StreamResponseHandler<SubscriptionResponseMessage> streamResponseHandler) throws InterruptedException { StreamingResponse<CompletableFuture<SubscribeToTopicResponse>, SubscribeToTopicResponseHandler> r = this.subscribeToTopicAsync(request, streamResponseHandler); return new StreamingResponse<>(getResponse(r.getResponse()), r.getHandler()); } /** * Perform the subscribeToTopic operation asynchronously. * The initial response or error will be returned as the result of the asynchronous future, further events will * arrive via the streaming callbacks. * * @return a future which resolves to the response * * @param request request object * @param streamResponseHandler Methods on this object will be called as stream events happen on this operation. * If an executor is provided, the onStreamEvent and onStreamClosed methods will run in the executor. */ public StreamingResponse<CompletableFuture<SubscribeToTopicResponse>, SubscribeToTopicResponseHandler> subscribeToTopicAsync( final SubscribeToTopicRequest request, final StreamResponseHandler<SubscriptionResponseMessage> streamResponseHandler) { SubscribeToTopicResponseHandler r = client.subscribeToTopic(request, Optional.ofNullable(getStreamingResponseHandler(streamResponseHandler))); return new StreamingResponse<>(r.getResponse(), r); } /** * Perform the subscribeToValidateConfigurationUpdates operation asynchronously. * The initial response or error will be returned as the result of the asynchronous future, further events will * arrive via the streaming callbacks. * * @return a future which resolves to the response * * @param request request object * @param onStreamEvent Callback for stream events. If an executor is provided, this method will run in the executor. * @param onStreamError Callback for stream errors. Return true to close the stream, * return false to keep the stream open. Even if an executor is provided, * this method will not run in the executor. * @param onStreamClosed Callback for when the stream closes. If an executor is provided, this method will run in the executor. */ public StreamingResponse<CompletableFuture<SubscribeToValidateConfigurationUpdatesResponse>, SubscribeToValidateConfigurationUpdatesResponseHandler> subscribeToValidateConfigurationUpdatesAsync( final SubscribeToValidateConfigurationUpdatesRequest request, Consumer<ValidateConfigurationUpdateEvents> onStreamEvent, Optional<Function<Throwable, Boolean>> onStreamError, Optional<Runnable> onStreamClosed) { return this.subscribeToValidateConfigurationUpdatesAsync(request, getStreamingResponseHandler(onStreamEvent, onStreamError, onStreamClosed)); } /** * Perform the subscribeToValidateConfigurationUpdates operation synchronously. * The initial response or error will be returned synchronously, * further events will arrive via the streaming callbacks. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object * @param onStreamEvent Callback for stream events. If an executor is provided, this method will run in the executor. * @param onStreamError Callback for stream errors. Return true to close the stream, * return false to keep the stream open. Even if an executor is provided, * this method will not run in the executor. * @param onStreamClosed Callback for when the stream closes. If an executor is provided, this method will run in the executor. */ public StreamingResponse<SubscribeToValidateConfigurationUpdatesResponse, SubscribeToValidateConfigurationUpdatesResponseHandler> subscribeToValidateConfigurationUpdates( final SubscribeToValidateConfigurationUpdatesRequest request, Consumer<ValidateConfigurationUpdateEvents> onStreamEvent, Optional<Function<Throwable, Boolean>> onStreamError, Optional<Runnable> onStreamClosed) throws InterruptedException { StreamingResponse<CompletableFuture<SubscribeToValidateConfigurationUpdatesResponse>, SubscribeToValidateConfigurationUpdatesResponseHandler> r = this.subscribeToValidateConfigurationUpdatesAsync(request, onStreamEvent, onStreamError, onStreamClosed); return new StreamingResponse<>(getResponse(r.getResponse()), r.getHandler()); } /** * Perform the subscribeToValidateConfigurationUpdates operation synchronously. * The initial response or error will be returned synchronously, further events will * arrive via the streaming callbacks. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object * @param streamResponseHandler Methods on this object will be called as stream events happen on this operation. * If an executor is provided, the onStreamEvent and onStreamClosed methods will run in the executor. */ public StreamingResponse<SubscribeToValidateConfigurationUpdatesResponse, SubscribeToValidateConfigurationUpdatesResponseHandler> subscribeToValidateConfigurationUpdates( final SubscribeToValidateConfigurationUpdatesRequest request, final StreamResponseHandler<ValidateConfigurationUpdateEvents> streamResponseHandler) throws InterruptedException { StreamingResponse<CompletableFuture<SubscribeToValidateConfigurationUpdatesResponse>, SubscribeToValidateConfigurationUpdatesResponseHandler> r = this.subscribeToValidateConfigurationUpdatesAsync(request, streamResponseHandler); return new StreamingResponse<>(getResponse(r.getResponse()), r.getHandler()); } /** * Perform the subscribeToValidateConfigurationUpdates operation asynchronously. * The initial response or error will be returned as the result of the asynchronous future, further events will * arrive via the streaming callbacks. * * @return a future which resolves to the response * * @param request request object * @param streamResponseHandler Methods on this object will be called as stream events happen on this operation. * If an executor is provided, the onStreamEvent and onStreamClosed methods will run in the executor. */ public StreamingResponse<CompletableFuture<SubscribeToValidateConfigurationUpdatesResponse>, SubscribeToValidateConfigurationUpdatesResponseHandler> subscribeToValidateConfigurationUpdatesAsync( final SubscribeToValidateConfigurationUpdatesRequest request, final StreamResponseHandler<ValidateConfigurationUpdateEvents> streamResponseHandler) { SubscribeToValidateConfigurationUpdatesResponseHandler r = client.subscribeToValidateConfigurationUpdates(request, Optional.ofNullable(getStreamingResponseHandler(streamResponseHandler))); return new StreamingResponse<>(r.getResponse(), r); } /** * Perform the updateConfiguration operation synchronously. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object */ public UpdateConfigurationResponse updateConfiguration(final UpdateConfigurationRequest request) throws InterruptedException { return getResponse(this.updateConfigurationAsync(request)); } /** * Perform the updateConfiguration operation asynchronously. * * @return a future which resolves to the response * * @param request request object */ public CompletableFuture<UpdateConfigurationResponse> updateConfigurationAsync( final UpdateConfigurationRequest request) { return client.updateConfiguration(request, Optional.empty()).getResponse(); } /** * Perform the updateState operation synchronously. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object */ public UpdateStateResponse updateState(final UpdateStateRequest request) throws InterruptedException { return getResponse(this.updateStateAsync(request)); } /** * Perform the updateState operation asynchronously. * * @return a future which resolves to the response * * @param request request object */ public CompletableFuture<UpdateStateResponse> updateStateAsync(final UpdateStateRequest request) { return client.updateState(request, Optional.empty()).getResponse(); } /** * Perform the updateThingShadow operation synchronously. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object */ public UpdateThingShadowResponse updateThingShadow(final UpdateThingShadowRequest request) throws InterruptedException { return getResponse(this.updateThingShadowAsync(request)); } /** * Perform the updateThingShadow operation asynchronously. * * @return a future which resolves to the response * * @param request request object */ public CompletableFuture<UpdateThingShadowResponse> updateThingShadowAsync( final UpdateThingShadowRequest request) { return client.updateThingShadow(request, Optional.empty()).getResponse(); } /** * Perform the validateAuthorizationToken operation synchronously. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object */ public ValidateAuthorizationTokenResponse validateAuthorizationToken( final ValidateAuthorizationTokenRequest request) throws InterruptedException { return getResponse(this.validateAuthorizationTokenAsync(request)); } /** * Perform the validateAuthorizationToken operation asynchronously. * * @return a future which resolves to the response * * @param request request object */ public CompletableFuture<ValidateAuthorizationTokenResponse> validateAuthorizationTokenAsync( final ValidateAuthorizationTokenRequest request) { return client.validateAuthorizationToken(request, Optional.empty()).getResponse(); } /** * Perform the verifyClientDeviceIdentity operation synchronously. * * @throws InterruptedException if thread is interrupted while waiting for the response * @return the response * * @param request request object */ public VerifyClientDeviceIdentityResponse verifyClientDeviceIdentity( final VerifyClientDeviceIdentityRequest request) throws InterruptedException { return getResponse(this.verifyClientDeviceIdentityAsync(request)); } /** * Perform the verifyClientDeviceIdentity operation asynchronously. * * @return a future which resolves to the response * * @param request request object */ public CompletableFuture<VerifyClientDeviceIdentityResponse> verifyClientDeviceIdentityAsync( final VerifyClientDeviceIdentityRequest request) { return client.verifyClientDeviceIdentity(request, Optional.empty()).getResponse(); } protected static <T> T getResponse(Future<T> fut) throws InterruptedException { try { return fut.get(); } catch (ExecutionException e) { if (e.getCause() instanceof RuntimeException) { throw ((RuntimeException) e.getCause()); } // the cause should always be RuntimeException, but we will handle this case anyway throw new RuntimeException(e.getCause()); } } protected <T> StreamResponseHandler<T> getStreamingResponseHandler(StreamResponseHandler<T> h) { if (h == null || executor == null) { return h; } return new StreamResponseHandler<T>() { @Override public void onStreamEvent(T event) { executor.execute(() -> h.onStreamEvent(event)); } @Override public boolean onStreamError(Throwable error) { return h.onStreamError(error); } @Override public void onStreamClosed() { executor.execute(h::onStreamClosed); } } ; } protected <T> StreamResponseHandler<T> getStreamingResponseHandler(Consumer<T> onStreamEvent, Optional<Function<Throwable, Boolean>> onStreamError, Optional<Runnable> onStreamClosed) { return new StreamResponseHandler<T>() { @Override public void onStreamEvent(T event) { onStreamEvent.accept(event); } @Override public boolean onStreamError(Throwable error) { if (onStreamError != null && onStreamError.isPresent()) { return onStreamError.get().apply(error); } return true; } @Override public void onStreamClosed() { if (onStreamClosed != null && onStreamClosed.isPresent()) { onStreamClosed.get().run(); } } } ; } public static class StreamingResponse<T, U> { protected final T r; protected final U h; public StreamingResponse(T r, U h) { this.r = r; this.h = h; } public T getResponse() { return r; } public U getHandler() { return h; } } public static class Builder { protected GreengrassCoreIPC client; protected Executor executor; protected boolean useExecutor = true; protected String socketPath = System.getenv("AWS_GG_NUCLEUS_DOMAIN_SOCKET_FILEPATH_FOR_COMPONENT"); protected String authToken = System.getenv("SVCUID"); protected int port = 8888; protected EventStreamRPCConnection connection = null; protected SocketDomain socketDomain = SocketDomain.LOCAL; public GreengrassCoreIPCClientV2 build() throws IOException { if (client == null) { String ipcServerSocketPath = this.socketPath; String authToken = this.authToken; try (EventLoopGroup elGroup = new EventLoopGroup(1); ClientBootstrap clientBootstrap = new ClientBootstrap(elGroup, null); SocketOptions socketOptions = new SocketOptions()) { socketOptions.connectTimeoutMs = 3000; socketOptions.domain = this.socketDomain; socketOptions.type = SocketOptions.SocketType.STREAM; final EventStreamRPCConnectionConfig config = new EventStreamRPCConnectionConfig(clientBootstrap, elGroup, socketOptions, null, ipcServerSocketPath, this.port, GreengrassConnectMessageSupplier.connectMessageSupplier(authToken)); connection = new EventStreamRPCConnection(config); CompletableFuture<Void> connected = new CompletableFuture<>(); connection.connect(new EventStreamRPCConnection.LifecycleHandler() { @Override public void onConnect() { connected.complete(null); } @Override public void onDisconnect(int errorCode) { } @Override public boolean onError(Throwable t) { connected.completeExceptionally(t); return true; } } ); try { connected.get(); } catch (ExecutionException | InterruptedException e) { connection.close(); throw new IOException(e); } this.client = new GreengrassCoreIPCClient(connection); } } if (this.useExecutor && this.executor == null) { this.executor = Executors.newCachedThreadPool(); } return new GreengrassCoreIPCClientV2(this.client, this.connection, this.executor); } public Builder withClient(GreengrassCoreIPC client) { this.client = client; return this; } public Builder withAuthToken(String authToken) { this.authToken = authToken; return this; } public Builder withSocketPath(String socketPath) { this.socketPath = socketPath; return this; } public Builder withSocketDomain(SocketDomain domain) { this.socketDomain = domain; return this; } public Builder withPort(int port) { this.port = port; return this; } public Builder withExecutor(Executor executor) { this.useExecutor = true; this.executor = executor; return this; } public Builder withoutExecutor() { this.useExecutor = false; this.executor = null; return this; } } }
5,412
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws/greengrass/ListNamedShadowsForThingResponseHandler.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.aws.greengrass; import java.lang.Override; import java.lang.Void; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.aws.greengrass.model.ListNamedShadowsForThingResponse; import software.amazon.awssdk.eventstreamrpc.OperationResponse; import software.amazon.awssdk.eventstreamrpc.StreamResponse; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public final class ListNamedShadowsForThingResponseHandler implements StreamResponse<ListNamedShadowsForThingResponse, EventStreamJsonMessage> { private final OperationResponse<ListNamedShadowsForThingResponse, EventStreamJsonMessage> operationResponse; public ListNamedShadowsForThingResponseHandler( final OperationResponse<ListNamedShadowsForThingResponse, EventStreamJsonMessage> operationResponse) { this.operationResponse = operationResponse; } @Override public CompletableFuture<Void> getRequestFlushFuture() { return operationResponse.getRequestFlushFuture(); } @Override public CompletableFuture<ListNamedShadowsForThingResponse> getResponse() { return operationResponse.getResponse(); } @Override public CompletableFuture<Void> sendStreamEvent(final EventStreamJsonMessage event) { return operationResponse.sendStreamEvent(event); } @Override public CompletableFuture<Void> closeStream() { return operationResponse.closeStream(); } @Override public boolean isClosed() { return operationResponse.isClosed(); } }
5,413
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws/greengrass/PublishToTopicResponseHandler.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.aws.greengrass; import java.lang.Override; import java.lang.Void; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.aws.greengrass.model.PublishToTopicResponse; import software.amazon.awssdk.eventstreamrpc.OperationResponse; import software.amazon.awssdk.eventstreamrpc.StreamResponse; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public final class PublishToTopicResponseHandler implements StreamResponse<PublishToTopicResponse, EventStreamJsonMessage> { private final OperationResponse<PublishToTopicResponse, EventStreamJsonMessage> operationResponse; public PublishToTopicResponseHandler( final OperationResponse<PublishToTopicResponse, EventStreamJsonMessage> operationResponse) { this.operationResponse = operationResponse; } @Override public CompletableFuture<Void> getRequestFlushFuture() { return operationResponse.getRequestFlushFuture(); } @Override public CompletableFuture<PublishToTopicResponse> getResponse() { return operationResponse.getResponse(); } @Override public CompletableFuture<Void> sendStreamEvent(final EventStreamJsonMessage event) { return operationResponse.sendStreamEvent(event); } @Override public CompletableFuture<Void> closeStream() { return operationResponse.closeStream(); } @Override public boolean isClosed() { return operationResponse.isClosed(); } }
5,414
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws/greengrass/VerifyClientDeviceIdentityResponseHandler.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.aws.greengrass; import java.lang.Override; import java.lang.Void; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.aws.greengrass.model.VerifyClientDeviceIdentityResponse; import software.amazon.awssdk.eventstreamrpc.OperationResponse; import software.amazon.awssdk.eventstreamrpc.StreamResponse; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public final class VerifyClientDeviceIdentityResponseHandler implements StreamResponse<VerifyClientDeviceIdentityResponse, EventStreamJsonMessage> { private final OperationResponse<VerifyClientDeviceIdentityResponse, EventStreamJsonMessage> operationResponse; public VerifyClientDeviceIdentityResponseHandler( final OperationResponse<VerifyClientDeviceIdentityResponse, EventStreamJsonMessage> operationResponse) { this.operationResponse = operationResponse; } @Override public CompletableFuture<Void> getRequestFlushFuture() { return operationResponse.getRequestFlushFuture(); } @Override public CompletableFuture<VerifyClientDeviceIdentityResponse> getResponse() { return operationResponse.getResponse(); } @Override public CompletableFuture<Void> sendStreamEvent(final EventStreamJsonMessage event) { return operationResponse.sendStreamEvent(event); } @Override public CompletableFuture<Void> closeStream() { return operationResponse.closeStream(); } @Override public boolean isClosed() { return operationResponse.isClosed(); } }
5,415
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws/greengrass/DeferComponentUpdateResponseHandler.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.aws.greengrass; import java.lang.Override; import java.lang.Void; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.aws.greengrass.model.DeferComponentUpdateResponse; import software.amazon.awssdk.eventstreamrpc.OperationResponse; import software.amazon.awssdk.eventstreamrpc.StreamResponse; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public final class DeferComponentUpdateResponseHandler implements StreamResponse<DeferComponentUpdateResponse, EventStreamJsonMessage> { private final OperationResponse<DeferComponentUpdateResponse, EventStreamJsonMessage> operationResponse; public DeferComponentUpdateResponseHandler( final OperationResponse<DeferComponentUpdateResponse, EventStreamJsonMessage> operationResponse) { this.operationResponse = operationResponse; } @Override public CompletableFuture<Void> getRequestFlushFuture() { return operationResponse.getRequestFlushFuture(); } @Override public CompletableFuture<DeferComponentUpdateResponse> getResponse() { return operationResponse.getResponse(); } @Override public CompletableFuture<Void> sendStreamEvent(final EventStreamJsonMessage event) { return operationResponse.sendStreamEvent(event); } @Override public CompletableFuture<Void> closeStream() { return operationResponse.closeStream(); } @Override public boolean isClosed() { return operationResponse.isClosed(); } }
5,416
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/event-stream-rpc-java/client/software/amazon/awssdk/aws/greengrass/SendConfigurationValidityReportResponseHandler.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.aws.greengrass; import java.lang.Override; import java.lang.Void; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.aws.greengrass.model.SendConfigurationValidityReportResponse; import software.amazon.awssdk.eventstreamrpc.OperationResponse; import software.amazon.awssdk.eventstreamrpc.StreamResponse; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public final class SendConfigurationValidityReportResponseHandler implements StreamResponse<SendConfigurationValidityReportResponse, EventStreamJsonMessage> { private final OperationResponse<SendConfigurationValidityReportResponse, EventStreamJsonMessage> operationResponse; public SendConfigurationValidityReportResponseHandler( final OperationResponse<SendConfigurationValidityReportResponse, EventStreamJsonMessage> operationResponse) { this.operationResponse = operationResponse; } @Override public CompletableFuture<Void> getRequestFlushFuture() { return operationResponse.getRequestFlushFuture(); } @Override public CompletableFuture<SendConfigurationValidityReportResponse> getResponse() { return operationResponse.getResponse(); } @Override public CompletableFuture<Void> sendStreamEvent(final EventStreamJsonMessage event) { return operationResponse.sendStreamEvent(event); } @Override public CompletableFuture<Void> closeStream() { return operationResponse.closeStream(); } @Override public boolean isClosed() { return operationResponse.isClosed(); } }
5,417
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/test
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/test/java/GreengrassV2ClientTest.java
import com.google.gson.Gson; import greengrass.GeneratedAbstractCreateLocalDeploymentOperationHandler; import greengrass.GeneratedAbstractSubscribeToTopicOperationHandler; import greengrass.GreengrassCoreIPCService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCClientV2; import software.amazon.awssdk.aws.greengrass.SubscribeToTopicResponseHandler; import software.amazon.awssdk.aws.greengrass.model.BinaryMessage; import software.amazon.awssdk.aws.greengrass.model.CreateLocalDeploymentRequest; import software.amazon.awssdk.aws.greengrass.model.CreateLocalDeploymentResponse; import software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicRequest; import software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicResponse; import software.amazon.awssdk.aws.greengrass.model.SubscriptionResponseMessage; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.io.EventLoopGroup; import software.amazon.awssdk.crt.io.SocketOptions; import software.amazon.awssdk.eventstreamrpc.Authorization; import software.amazon.awssdk.eventstreamrpc.GreengrassEventStreamConnectMessage; import software.amazon.awssdk.eventstreamrpc.RpcServer; import software.amazon.awssdk.eventstreamrpc.StreamResponseHandler; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Optional; import java.util.Random; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import static org.junit.jupiter.api.Assertions.assertEquals; public class GreengrassV2ClientTest { private static final Random RANDOM = new Random(); //default instantiation uses time private int port; private RpcServer ipcServer; private GreengrassEventStreamConnectMessage authenticationRequest; private GreengrassCoreIPCClientV2 client; private CompletableFuture<Void> subscriptionClosed = new CompletableFuture<>(); public static int randomPort() { return RANDOM.nextInt(65535 - 1024) + 1024; } @BeforeEach public void before() throws IOException { port = randomPort(); try (final EventLoopGroup elGroup = new EventLoopGroup(1); SocketOptions socketOptions = new SocketOptions()) { socketOptions.connectTimeoutMs = 3000; socketOptions.domain = SocketOptions.SocketDomain.IPv4; socketOptions.type = SocketOptions.SocketType.STREAM; GreengrassCoreIPCService service = new GreengrassCoreIPCService(); service.setCreateLocalDeploymentHandler((c) -> new GeneratedAbstractCreateLocalDeploymentOperationHandler(c) { @Override protected void onStreamClosed() { } @Override public CreateLocalDeploymentResponse handleRequest(CreateLocalDeploymentRequest request) { return new CreateLocalDeploymentResponse().withDeploymentId("deployment"); } @Override public void handleStreamEvent(EventStreamJsonMessage streamRequestEvent) { } }); service.setSubscribeToTopicHandler((c) -> new GeneratedAbstractSubscribeToTopicOperationHandler(c) { @Override protected void onStreamClosed() { subscriptionClosed.complete(null); } @Override public SubscribeToTopicResponse handleRequest(SubscribeToTopicRequest request) { new Thread(() -> { sendStreamEvent(new SubscriptionResponseMessage().withBinaryMessage( new BinaryMessage().withMessage("message".getBytes(StandardCharsets.UTF_8)))); }).start(); return new SubscribeToTopicResponse().withTopicName(request.getTopic()); } @Override public void handleStreamEvent(EventStreamJsonMessage streamRequestEvent) { } }); service.setAuthenticationHandler((headers, bytes) -> { authenticationRequest = new Gson().fromJson(new String(bytes), GreengrassEventStreamConnectMessage.class); return () -> "connected"; }); service.setAuthorizationHandler(authenticationData -> Authorization.ACCEPT); ipcServer = new RpcServer(elGroup, socketOptions, null, "127.0.0.1", port, service); ipcServer.runServer(); client = GreengrassCoreIPCClientV2.builder().withPort(port).withSocketPath("127.0.0.1") .withSocketDomain(SocketOptions.SocketDomain.IPv4).withAuthToken("myAuthToken").build(); } } @AfterEach public void after() throws Exception { ipcServer.close(); if (client != null) { client.close(); } CrtResource.waitForNoResources(); } @Test public void testV2Client() throws InterruptedException, ExecutionException, TimeoutException { assertEquals(authenticationRequest.getAuthToken(), "myAuthToken"); CreateLocalDeploymentResponse depResp = client.createLocalDeployment(new CreateLocalDeploymentRequest()); assertEquals("deployment", depResp.getDeploymentId()); CompletableFuture<CreateLocalDeploymentResponse> asyncDepResp = client.createLocalDeploymentAsync(new CreateLocalDeploymentRequest()); assertEquals("deployment", asyncDepResp.get().getDeploymentId()); CompletableFuture<String> receivedMessage = new CompletableFuture<>(); CompletableFuture<String> finalReceivedMessage = receivedMessage; GreengrassCoreIPCClientV2.StreamingResponse<SubscribeToTopicResponse, SubscribeToTopicResponseHandler> subResp = client.subscribeToTopic(new SubscribeToTopicRequest().withTopic("abc"), (x) -> { if (!Thread.currentThread().getName().contains("pool")) { System.out.println(Thread.currentThread().getName()); finalReceivedMessage.completeExceptionally( new RuntimeException("Ran on event loop instead of executor")); } finalReceivedMessage.complete(new String(x.getBinaryMessage().getMessage())); }, Optional.empty(), Optional.empty()); assertEquals("message", receivedMessage.get()); subResp.getHandler().closeStream().get(); subscriptionClosed.get(5, TimeUnit.SECONDS); subscriptionClosed = new CompletableFuture<>(); receivedMessage = new CompletableFuture<>(); CompletableFuture<String> finalReceivedMessage1 = receivedMessage; subResp = client.subscribeToTopic(new SubscribeToTopicRequest().withTopic("abc"), new StreamResponseHandler<SubscriptionResponseMessage>() { @Override public void onStreamEvent(SubscriptionResponseMessage streamEvent) { if (!Thread.currentThread().getName().contains("pool")) { finalReceivedMessage1.completeExceptionally( new RuntimeException("Ran on event loop instead of executor")); } finalReceivedMessage1.complete(new String(streamEvent.getBinaryMessage().getMessage())); } @Override public boolean onStreamError(Throwable error) { return false; } @Override public void onStreamClosed() { } }); assertEquals("message", receivedMessage.get()); subResp.getHandler().closeStream().get(); subscriptionClosed.get(5, TimeUnit.SECONDS); subscriptionClosed = new CompletableFuture<>(); receivedMessage = new CompletableFuture<>(); CompletableFuture<String> finalReceivedMessage2 = receivedMessage; GreengrassCoreIPCClientV2.StreamingResponse<CompletableFuture<SubscribeToTopicResponse>, SubscribeToTopicResponseHandler> subRespAsync = client.subscribeToTopicAsync(new SubscribeToTopicRequest().withTopic("abc"), new StreamResponseHandler<SubscriptionResponseMessage>() { @Override public void onStreamEvent(SubscriptionResponseMessage streamEvent) { if (!Thread.currentThread().getName().contains("pool")) { finalReceivedMessage2.completeExceptionally( new RuntimeException("Ran on event loop instead of executor")); } finalReceivedMessage2.complete(new String(streamEvent.getBinaryMessage().getMessage())); } @Override public boolean onStreamError(Throwable error) { return false; } @Override public void onStreamClosed() { } }); assertEquals("message", receivedMessage.get()); subRespAsync.getHandler().closeStream().get(); subscriptionClosed.get(5, TimeUnit.SECONDS); subscriptionClosed = new CompletableFuture<>(); receivedMessage = new CompletableFuture<>(); CompletableFuture<String> finalReceivedMessage3 = receivedMessage; subRespAsync = client.subscribeToTopicAsync(new SubscribeToTopicRequest().withTopic("abc"), (x) -> { if (!Thread.currentThread().getName().contains("pool")) { finalReceivedMessage3.completeExceptionally( new RuntimeException("Ran on event loop instead of executor")); } finalReceivedMessage3.complete(new String(x.getBinaryMessage().getMessage())); }, Optional.empty(), Optional.empty()); assertEquals("message", receivedMessage.get()); subRespAsync.getHandler().closeStream().get(); subscriptionClosed.get(5, TimeUnit.SECONDS); } }
5,418
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/test/java
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/test/java/greengrass/GreengrassCoreIPCService.java
package greengrass; import software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCServiceModel; import software.amazon.awssdk.crt.eventstream.ServerConnectionContinuationHandler; import software.amazon.awssdk.eventstreamrpc.EventStreamRPCServiceHandler; import software.amazon.awssdk.eventstreamrpc.EventStreamRPCServiceModel; import software.amazon.awssdk.eventstreamrpc.OperationContinuationHandlerContext; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.function.Function; public final class GreengrassCoreIPCService extends EventStreamRPCServiceHandler { public static final String SERVICE_NAMESPACE = "aws.greengrass"; protected static final Set<String> SERVICE_OPERATION_SET; public static final String SUBSCRIBE_TO_TOPIC = SERVICE_NAMESPACE + "#SubscribeToTopic"; public static final String CREATE_LOCAL_DEPLOYMENT = SERVICE_NAMESPACE + "#CreateLocalDeployment"; static { SERVICE_OPERATION_SET = new HashSet<>(); SERVICE_OPERATION_SET.add(SUBSCRIBE_TO_TOPIC); SERVICE_OPERATION_SET.add(CREATE_LOCAL_DEPLOYMENT); } private final Map<String, Function<OperationContinuationHandlerContext, ? extends ServerConnectionContinuationHandler>> operationSupplierMap; public GreengrassCoreIPCService() { this.operationSupplierMap = new HashMap<>(); } @Override public EventStreamRPCServiceModel getServiceModel() { return GreengrassCoreIPCServiceModel.getInstance(); } public void setSubscribeToTopicHandler( Function<OperationContinuationHandlerContext, GeneratedAbstractSubscribeToTopicOperationHandler> handler) { operationSupplierMap.put(SUBSCRIBE_TO_TOPIC, handler); } public void setCreateLocalDeploymentHandler( Function<OperationContinuationHandlerContext, GeneratedAbstractCreateLocalDeploymentOperationHandler> handler) { operationSupplierMap.put(CREATE_LOCAL_DEPLOYMENT, handler); } @Override public Set<String> getAllOperations() { return SERVICE_OPERATION_SET; } @Override public boolean hasHandlerForOperation(String operation) { return operationSupplierMap.containsKey(operation); } @Override public Function<OperationContinuationHandlerContext, ? extends ServerConnectionContinuationHandler> getOperationHandler( String operation) { return operationSupplierMap.get(operation); } public void setOperationHandler(String operation, Function<OperationContinuationHandlerContext, ? extends ServerConnectionContinuationHandler> handler) { operationSupplierMap.put(operation, handler); } }
5,419
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/test/java
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/test/java/greengrass/GeneratedAbstractSubscribeToTopicOperationHandler.java
package greengrass; import software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCServiceModel; import software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicRequest; import software.amazon.awssdk.aws.greengrass.model.SubscribeToTopicResponse; import software.amazon.awssdk.aws.greengrass.model.SubscriptionResponseMessage; import software.amazon.awssdk.eventstreamrpc.OperationContinuationHandler; import software.amazon.awssdk.eventstreamrpc.OperationContinuationHandlerContext; import software.amazon.awssdk.eventstreamrpc.OperationModelContext; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public abstract class GeneratedAbstractSubscribeToTopicOperationHandler extends OperationContinuationHandler<SubscribeToTopicRequest, SubscribeToTopicResponse, EventStreamJsonMessage, SubscriptionResponseMessage> { protected GeneratedAbstractSubscribeToTopicOperationHandler( OperationContinuationHandlerContext context) { super(context); } @Override public OperationModelContext<SubscribeToTopicRequest, SubscribeToTopicResponse, EventStreamJsonMessage, SubscriptionResponseMessage> getOperationModelContext( ) { return GreengrassCoreIPCServiceModel.getSubscribeToTopicModelContext(); } }
5,420
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/test/java
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/greengrass-client/src/test/java/greengrass/GeneratedAbstractCreateLocalDeploymentOperationHandler.java
package greengrass; import software.amazon.awssdk.aws.greengrass.GreengrassCoreIPCServiceModel; import software.amazon.awssdk.aws.greengrass.model.CreateLocalDeploymentRequest; import software.amazon.awssdk.aws.greengrass.model.CreateLocalDeploymentResponse; import software.amazon.awssdk.eventstreamrpc.OperationContinuationHandler; import software.amazon.awssdk.eventstreamrpc.OperationContinuationHandlerContext; import software.amazon.awssdk.eventstreamrpc.OperationModelContext; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public abstract class GeneratedAbstractCreateLocalDeploymentOperationHandler extends OperationContinuationHandler<CreateLocalDeploymentRequest, CreateLocalDeploymentResponse, EventStreamJsonMessage, EventStreamJsonMessage> { protected GeneratedAbstractCreateLocalDeploymentOperationHandler( OperationContinuationHandlerContext context) { super(context); } @Override public OperationModelContext<CreateLocalDeploymentRequest, CreateLocalDeploymentResponse, EventStreamJsonMessage, EventStreamJsonMessage> getOperationModelContext( ) { return GreengrassCoreIPCServiceModel.getCreateLocalDeploymentModelContext(); } }
5,421
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/eventstreamrpc/ObjectModelTests.java
package software.amazon.awssdk.eventstreamrpc; import org.json.JSONObject; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import software.amazon.awssdk.awstest.EchoTestRPCServiceModel; import software.amazon.awssdk.awstest.model.*; import software.amazon.awssdk.crt.eventstream.Header; import software.amazon.awssdk.crt.eventstream.MessageType; import software.amazon.awssdk.eventstreamrpc.model.EventStreamError; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.*; public class ObjectModelTests { @Test void testBasicModelSerialize() { final String testString = "fooStringMessage"; final EchoMessageRequest requestObject = new EchoMessageRequest(); final MessageData data = new MessageData(); data.setStringMessage(testString); requestObject.setMessage(data); final JSONObject jsonObject = new JSONObject(new String(EchoTestRPCServiceModel.getInstance().toJson(requestObject), StandardCharsets.UTF_8)); Assertions.assertTrue(jsonObject.has("message")); Assertions.assertTrue(jsonObject.getJSONObject("message").has("stringMessage")); Assertions.assertEquals(testString, jsonObject.getJSONObject("message").getString("stringMessage")); } @Test void testBlobAndDeserializeEquivalence() { byte[] testContent = new byte[] { (byte)0xDE, (byte)0xAD, (byte)0xBE, (byte)0xEF }; final EchoMessageRequest requestObject = new EchoMessageRequest(); final MessageData data = new MessageData(); data.setBlobMessage(testContent); requestObject.setMessage(data); final JSONObject jsonObject = new JSONObject(new String(EchoTestRPCServiceModel.getInstance().toJson(requestObject), StandardCharsets.UTF_8)); Assertions.assertTrue(jsonObject.has("message")); Assertions.assertTrue(jsonObject.getJSONObject("message").has("blobMessage")); Assertions.assertEquals(new String(Base64.getEncoder().encode(testContent), StandardCharsets.UTF_8), jsonObject.getJSONObject("message").getString("blobMessage")); final EchoMessageRequest deserialized = EchoTestRPCServiceModel.getInstance().fromJson(EchoMessageRequest.class, jsonObject.toString().getBytes(StandardCharsets.UTF_8)); Assertions.assertTrue(requestObject.equals(deserialized)); } @Test void testEnumGetter() { MessageData data = new MessageData(); for(FruitEnum value:FruitEnum.values()) { data.setEnumMessage(value); FruitEnum enumGet = data.getEnumMessage(); } } @Test void testEmptyObjectIsNotNullAndIsEmpty() { final EchoMessageRequest requestObject = new EchoMessageRequest(); final JSONObject jsonObject = new JSONObject(new String(EchoTestRPCServiceModel.getInstance().toJson(requestObject), StandardCharsets.UTF_8)); Assertions.assertTrue(jsonObject.isEmpty()); } @Test void testNestedEqualsAndHashCodeObject() { final String testString = "fooStringMessage"; final EchoMessageRequest requestObject = new EchoMessageRequest(); final MessageData data = new MessageData(); data.setStringMessage(testString); requestObject.setMessage(data); final String testString2 = "fooStringMessage"; final EchoMessageRequest requestObject2 = new EchoMessageRequest(); final MessageData data2 = new MessageData(); data2.setStringMessage(testString2); requestObject2.setMessage(data2); final String testString3 = "fooStringMessage-changed"; final EchoMessageRequest requestObject3 = new EchoMessageRequest(); final MessageData data3 = new MessageData(); data3.setStringMessage(testString3); requestObject3.setMessage(data3); //Test equals both ways Assertions.assertTrue(requestObject.equals(requestObject2)); Assertions.assertTrue(requestObject2.equals(requestObject)); Assertions.assertFalse(requestObject.equals(null)); Assertions.assertFalse(requestObject2.equals(null)); Assertions.assertFalse(requestObject.equals(requestObject3)); Assertions.assertTrue(requestObject.hashCode() == requestObject2.hashCode(), "Hash code of nested equivalent objects are not equal!"); Assertions.assertTrue(requestObject.hashCode() != requestObject3.hashCode(), "Hash code of nested different objects should not be equals!"); } @Test void testSetRequiredFieldToNull() { //"key" setKey() is a required field in the presence of a Pair //however, it should never be verified client side via object model final Pair pair = new Pair(); pair.setKey(null); pair.setValue(null); } @Test void testInstantSerialization() { final MessageData data = new MessageData(); final Instant someInstant = Instant.ofEpochSecond(1606173648); data.setTimeMessage(someInstant); final JSONObject jsonObject = new JSONObject(EchoTestRPCServiceModel.getInstance().toJsonString(data)); final MessageData dataDeserialized = EchoTestRPCServiceModel.getInstance().fromJson(MessageData.class, jsonObject.toString().getBytes(StandardCharsets.UTF_8)); //Timestamp comparison is susceptible to precision issues due to double and serialization to JSON Assertions.assertEquals(Math.abs(data.getTimeMessage().toEpochMilli()), Math.abs(dataDeserialized.getTimeMessage().toEpochMilli())); } @Test void testUnionShapeSerializeAndDeserialize() { final EchoStreamingMessage streamingMessage = new EchoStreamingMessage(); final Pair pair = new Pair(); pair.setKey("fooKey"); pair.setValue("barValue"); streamingMessage.setKeyValuePair(pair); final JSONObject obj = new JSONObject(EchoTestRPCServiceModel.getInstance().toJsonString(streamingMessage)); Assertions.assertTrue(obj.has("keyValuePair")); final EchoStreamingMessage deserialized = EchoTestRPCServiceModel.getInstance() .fromJson(EchoStreamingMessage.class, obj.toString().getBytes(StandardCharsets.UTF_8)); Assertions.assertEquals(EchoStreamingMessage.UnionMember.KEY_VALUE_PAIR, deserialized.getSetUnionMember()); Assertions.assertTrue(deserialized.getKeyValuePair().equals(pair)); streamingMessage.selfDesignateSetUnionMember(); //shouldn't throw exception Assertions.assertEquals(streamingMessage, deserialized); //and should remain the same internally //changing the set member should cause prior member to be null //and self designating should not see more than one member final MessageData data = new MessageData(); data.setEnumMessage(FruitEnum.BANANA); streamingMessage.setStreamMessage(data); Assertions.assertNull(streamingMessage.getKeyValuePair()); streamingMessage.selfDesignateSetUnionMember(); } @Test void testEnumSerializeDeserialize() { final MessageData data = new MessageData(); data.setEnumMessage(FruitEnum.BANANA); final JSONObject obj = new JSONObject(EchoTestRPCServiceModel.getInstance().toJsonString(data)); Assertions.assertTrue(obj.has("enumMessage")); Assertions.assertEquals(FruitEnum.BANANA.getValue(), obj.get("enumMessage")); final MessageData deserialized = EchoTestRPCServiceModel.getInstance() .fromJson(MessageData.class, obj.toString().getBytes(StandardCharsets.UTF_8)); Assertions.assertTrue(data.equals(deserialized)); } @Test void testDocumentNullSerialize() { final MessageData data = new MessageData(); final Map<String, Object> docPart = new HashMap<>(); //TODO: Gson deserializes integers into float and causes equals checks to fail later // questionable if this is considered improper //docPart.put("int", Integer.valueOf(1)); docPart.put("string", "bar"); docPart.put("null", null); docPart.put("nullStringValueLiteral", "null"); data.setDocumentMessage(docPart); final JSONObject obj = new JSONObject(EchoTestRPCServiceModel.getInstance().toJsonString(data)); final MessageData deserialized = EchoTestRPCServiceModel.getInstance() .fromJson(MessageData.class, obj.toString().getBytes(StandardCharsets.UTF_8)); Assertions.assertTrue(data.equals(deserialized)); //verifies that the null deserialized back Assertions.assertTrue(deserialized.getDocumentMessage().containsKey("null")); Assertions.assertFalse(deserialized.getDocumentMessage().containsKey("nullNotPresent")); } @Test void testDocumentNullDeserialize() { final EchoMessageRequest data = new EchoMessageRequest(); Map<String, Product> sTV = new HashMap<String, Product>(); Product p = new Product(); p.setPrice(1.f); // leaving product's name as null for previously found issue sTV.put("A", p); MessageData m = new MessageData(); data.setMessage(m); m.setStringToValue(sTV); final JSONObject obj = new JSONObject(EchoTestRPCServiceModel.getInstance().toJsonString(data)); final EchoMessageRequest deserialized = EchoTestRPCServiceModel.getInstance() .fromJson(EchoMessageRequest.class, obj.toString().getBytes(StandardCharsets.UTF_8)); } @Test void testBadJsonDeserialize() { List<Header> headers = new ArrayList<>(); byte[] badJsonPayload = "{\"derp\":\"value\"; }".getBytes(StandardCharsets.UTF_8); EventStreamError errorMessage = EventStreamError.create(headers, badJsonPayload, MessageType.ProtocolError); Assertions.assertNotNull(errorMessage); } }
5,422
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest/EchoMessageOperationContext.java
package software.amazon.awssdk.awstest; import java.lang.Class; import java.lang.Override; import java.lang.String; import java.util.Optional; import software.amazon.awssdk.awstest.model.EchoMessageRequest; import software.amazon.awssdk.awstest.model.EchoMessageResponse; import software.amazon.awssdk.eventstreamrpc.EventStreamRPCServiceModel; import software.amazon.awssdk.eventstreamrpc.OperationModelContext; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public class EchoMessageOperationContext implements OperationModelContext<EchoMessageRequest, EchoMessageResponse, EventStreamJsonMessage, EventStreamJsonMessage> { @Override public EventStreamRPCServiceModel getServiceModel() { return EchoTestRPCServiceModel.getInstance(); } @Override public String getOperationName() { return EchoTestRPCServiceModel.ECHO_MESSAGE; } @Override public Class<EchoMessageRequest> getRequestTypeClass() { return EchoMessageRequest.class; } @Override public Class<EchoMessageResponse> getResponseTypeClass() { return EchoMessageResponse.class; } @Override public String getRequestApplicationModelType() { return EchoMessageRequest.APPLICATION_MODEL_TYPE; } @Override public String getResponseApplicationModelType() { return EchoMessageResponse.APPLICATION_MODEL_TYPE; } @Override public Optional<Class<EventStreamJsonMessage>> getStreamingRequestTypeClass() { return Optional.empty(); } @Override public Optional<Class<EventStreamJsonMessage>> getStreamingResponseTypeClass() { return Optional.empty(); } public Optional<String> getStreamingRequestApplicationModelType() { return Optional.empty(); } @Override public Optional<String> getStreamingResponseApplicationModelType() { return Optional.empty(); } }
5,423
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest/CauseServiceErrorOperationContext.java
package software.amazon.awssdk.awstest; import java.lang.Class; import java.lang.Override; import java.lang.String; import java.util.Optional; import software.amazon.awssdk.awstest.model.CauseServiceErrorRequest; import software.amazon.awssdk.awstest.model.CauseServiceErrorResponse; import software.amazon.awssdk.eventstreamrpc.EventStreamRPCServiceModel; import software.amazon.awssdk.eventstreamrpc.OperationModelContext; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public class CauseServiceErrorOperationContext implements OperationModelContext<CauseServiceErrorRequest, CauseServiceErrorResponse, EventStreamJsonMessage, EventStreamJsonMessage> { @Override public EventStreamRPCServiceModel getServiceModel() { return EchoTestRPCServiceModel.getInstance(); } @Override public String getOperationName() { return EchoTestRPCServiceModel.CAUSE_SERVICE_ERROR; } @Override public Class<CauseServiceErrorRequest> getRequestTypeClass() { return CauseServiceErrorRequest.class; } @Override public Class<CauseServiceErrorResponse> getResponseTypeClass() { return CauseServiceErrorResponse.class; } @Override public String getRequestApplicationModelType() { return CauseServiceErrorRequest.APPLICATION_MODEL_TYPE; } @Override public String getResponseApplicationModelType() { return CauseServiceErrorResponse.APPLICATION_MODEL_TYPE; } @Override public Optional<Class<EventStreamJsonMessage>> getStreamingRequestTypeClass() { return Optional.empty(); } @Override public Optional<Class<EventStreamJsonMessage>> getStreamingResponseTypeClass() { return Optional.empty(); } public Optional<String> getStreamingRequestApplicationModelType() { return Optional.empty(); } @Override public Optional<String> getStreamingResponseApplicationModelType() { return Optional.empty(); } }
5,424
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest/CauseStreamServiceToErrorOperationContext.java
package software.amazon.awssdk.awstest; import java.lang.Class; import java.lang.Override; import java.lang.String; import java.util.Optional; import software.amazon.awssdk.awstest.model.EchoStreamingMessage; import software.amazon.awssdk.awstest.model.EchoStreamingRequest; import software.amazon.awssdk.awstest.model.EchoStreamingResponse; import software.amazon.awssdk.eventstreamrpc.EventStreamRPCServiceModel; import software.amazon.awssdk.eventstreamrpc.OperationModelContext; public class CauseStreamServiceToErrorOperationContext implements OperationModelContext<EchoStreamingRequest, EchoStreamingResponse, EchoStreamingMessage, EchoStreamingMessage> { @Override public EventStreamRPCServiceModel getServiceModel() { return EchoTestRPCServiceModel.getInstance(); } @Override public String getOperationName() { return EchoTestRPCServiceModel.CAUSE_STREAM_SERVICE_TO_ERROR; } @Override public Class<EchoStreamingRequest> getRequestTypeClass() { return EchoStreamingRequest.class; } @Override public Class<EchoStreamingResponse> getResponseTypeClass() { return EchoStreamingResponse.class; } @Override public String getRequestApplicationModelType() { return EchoStreamingRequest.APPLICATION_MODEL_TYPE; } @Override public String getResponseApplicationModelType() { return EchoStreamingResponse.APPLICATION_MODEL_TYPE; } @Override public Optional<Class<EchoStreamingMessage>> getStreamingRequestTypeClass() { return Optional.of(EchoStreamingMessage.class); } @Override public Optional<Class<EchoStreamingMessage>> getStreamingResponseTypeClass() { return Optional.of(EchoStreamingMessage.class); } public Optional<String> getStreamingRequestApplicationModelType() { return Optional.of(EchoStreamingMessage.APPLICATION_MODEL_TYPE); } @Override public Optional<String> getStreamingResponseApplicationModelType() { return Optional.of(EchoStreamingMessage.APPLICATION_MODEL_TYPE); } }
5,425
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest/GetAllCustomersOperationContext.java
package software.amazon.awssdk.awstest; import java.lang.Class; import java.lang.Override; import java.lang.String; import java.util.Optional; import software.amazon.awssdk.awstest.model.GetAllCustomersRequest; import software.amazon.awssdk.awstest.model.GetAllCustomersResponse; import software.amazon.awssdk.eventstreamrpc.EventStreamRPCServiceModel; import software.amazon.awssdk.eventstreamrpc.OperationModelContext; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public class GetAllCustomersOperationContext implements OperationModelContext<GetAllCustomersRequest, GetAllCustomersResponse, EventStreamJsonMessage, EventStreamJsonMessage> { @Override public EventStreamRPCServiceModel getServiceModel() { return EchoTestRPCServiceModel.getInstance(); } @Override public String getOperationName() { return EchoTestRPCServiceModel.GET_ALL_CUSTOMERS; } @Override public Class<GetAllCustomersRequest> getRequestTypeClass() { return GetAllCustomersRequest.class; } @Override public Class<GetAllCustomersResponse> getResponseTypeClass() { return GetAllCustomersResponse.class; } @Override public String getRequestApplicationModelType() { return GetAllCustomersRequest.APPLICATION_MODEL_TYPE; } @Override public String getResponseApplicationModelType() { return GetAllCustomersResponse.APPLICATION_MODEL_TYPE; } @Override public Optional<Class<EventStreamJsonMessage>> getStreamingRequestTypeClass() { return Optional.empty(); } @Override public Optional<Class<EventStreamJsonMessage>> getStreamingResponseTypeClass() { return Optional.empty(); } public Optional<String> getStreamingRequestApplicationModelType() { return Optional.empty(); } @Override public Optional<String> getStreamingResponseApplicationModelType() { return Optional.empty(); } }
5,426
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest/EchoStreamMessagesOperationContext.java
package software.amazon.awssdk.awstest; import java.lang.Class; import java.lang.Override; import java.lang.String; import java.util.Optional; import software.amazon.awssdk.awstest.model.EchoStreamingMessage; import software.amazon.awssdk.awstest.model.EchoStreamingRequest; import software.amazon.awssdk.awstest.model.EchoStreamingResponse; import software.amazon.awssdk.eventstreamrpc.EventStreamRPCServiceModel; import software.amazon.awssdk.eventstreamrpc.OperationModelContext; public class EchoStreamMessagesOperationContext implements OperationModelContext<EchoStreamingRequest, EchoStreamingResponse, EchoStreamingMessage, EchoStreamingMessage> { @Override public EventStreamRPCServiceModel getServiceModel() { return EchoTestRPCServiceModel.getInstance(); } @Override public String getOperationName() { return EchoTestRPCServiceModel.ECHO_STREAM_MESSAGES; } @Override public Class<EchoStreamingRequest> getRequestTypeClass() { return EchoStreamingRequest.class; } @Override public Class<EchoStreamingResponse> getResponseTypeClass() { return EchoStreamingResponse.class; } @Override public String getRequestApplicationModelType() { return EchoStreamingRequest.APPLICATION_MODEL_TYPE; } @Override public String getResponseApplicationModelType() { return EchoStreamingResponse.APPLICATION_MODEL_TYPE; } @Override public Optional<Class<EchoStreamingMessage>> getStreamingRequestTypeClass() { return Optional.of(EchoStreamingMessage.class); } @Override public Optional<Class<EchoStreamingMessage>> getStreamingResponseTypeClass() { return Optional.of(EchoStreamingMessage.class); } public Optional<String> getStreamingRequestApplicationModelType() { return Optional.of(EchoStreamingMessage.APPLICATION_MODEL_TYPE); } @Override public Optional<String> getStreamingResponseApplicationModelType() { return Optional.of(EchoStreamingMessage.APPLICATION_MODEL_TYPE); } }
5,427
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest/GetAllProductsOperationContext.java
package software.amazon.awssdk.awstest; import java.lang.Class; import java.lang.Override; import java.lang.String; import java.util.Optional; import software.amazon.awssdk.awstest.model.GetAllProductsRequest; import software.amazon.awssdk.awstest.model.GetAllProductsResponse; import software.amazon.awssdk.eventstreamrpc.EventStreamRPCServiceModel; import software.amazon.awssdk.eventstreamrpc.OperationModelContext; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public class GetAllProductsOperationContext implements OperationModelContext<GetAllProductsRequest, GetAllProductsResponse, EventStreamJsonMessage, EventStreamJsonMessage> { @Override public EventStreamRPCServiceModel getServiceModel() { return EchoTestRPCServiceModel.getInstance(); } @Override public String getOperationName() { return EchoTestRPCServiceModel.GET_ALL_PRODUCTS; } @Override public Class<GetAllProductsRequest> getRequestTypeClass() { return GetAllProductsRequest.class; } @Override public Class<GetAllProductsResponse> getResponseTypeClass() { return GetAllProductsResponse.class; } @Override public String getRequestApplicationModelType() { return GetAllProductsRequest.APPLICATION_MODEL_TYPE; } @Override public String getResponseApplicationModelType() { return GetAllProductsResponse.APPLICATION_MODEL_TYPE; } @Override public Optional<Class<EventStreamJsonMessage>> getStreamingRequestTypeClass() { return Optional.empty(); } @Override public Optional<Class<EventStreamJsonMessage>> getStreamingResponseTypeClass() { return Optional.empty(); } public Optional<String> getStreamingRequestApplicationModelType() { return Optional.empty(); } @Override public Optional<String> getStreamingResponseApplicationModelType() { return Optional.empty(); } }
5,428
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest/EchoTestRPCServiceModel.java
package software.amazon.awssdk.awstest; import java.lang.Class; import java.lang.Override; import java.lang.String; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.Set; import software.amazon.awssdk.awstest.model.CauseServiceErrorRequest; import software.amazon.awssdk.awstest.model.CauseServiceErrorResponse; import software.amazon.awssdk.awstest.model.Customer; import software.amazon.awssdk.awstest.model.EchoMessageRequest; import software.amazon.awssdk.awstest.model.EchoMessageResponse; import software.amazon.awssdk.awstest.model.EchoStreamingMessage; import software.amazon.awssdk.awstest.model.EchoStreamingRequest; import software.amazon.awssdk.awstest.model.EchoStreamingResponse; import software.amazon.awssdk.awstest.model.FruitEnum; import software.amazon.awssdk.awstest.model.GetAllCustomersRequest; import software.amazon.awssdk.awstest.model.GetAllCustomersResponse; import software.amazon.awssdk.awstest.model.GetAllProductsRequest; import software.amazon.awssdk.awstest.model.GetAllProductsResponse; import software.amazon.awssdk.awstest.model.MessageData; import software.amazon.awssdk.awstest.model.Pair; import software.amazon.awssdk.awstest.model.Product; import software.amazon.awssdk.awstest.model.ServiceError; import software.amazon.awssdk.eventstreamrpc.EventStreamRPCServiceModel; import software.amazon.awssdk.eventstreamrpc.OperationModelContext; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public class EchoTestRPCServiceModel extends EventStreamRPCServiceModel { private static final EchoTestRPCServiceModel INSTANCE = new EchoTestRPCServiceModel(); public static final String SERVICE_NAMESPACE = "awstest"; public static final String SERVICE_NAME = SERVICE_NAMESPACE + "#" + "EchoTestRPC"; private static final Set<String> SERVICE_OPERATION_SET = new HashSet<String>(); private static final Map<String, OperationModelContext> SERVICE_OPERATION_MODEL_MAP = new HashMap<String, OperationModelContext>(); private static final Map<String, Class<? extends EventStreamJsonMessage>> SERVICE_OBJECT_MODEL_MAP = new HashMap<String, Class<? extends EventStreamJsonMessage>>(); public static final String CAUSE_SERVICE_ERROR = SERVICE_NAMESPACE + "#" + "CauseServiceError"; private static final CauseServiceErrorOperationContext _CAUSE_SERVICE_ERROR_OPERATION_CONTEXT = new CauseServiceErrorOperationContext(); public static final String CAUSE_STREAM_SERVICE_TO_ERROR = SERVICE_NAMESPACE + "#" + "CauseStreamServiceToError"; private static final CauseStreamServiceToErrorOperationContext _CAUSE_STREAM_SERVICE_TO_ERROR_OPERATION_CONTEXT = new CauseStreamServiceToErrorOperationContext(); public static final String ECHO_MESSAGE = SERVICE_NAMESPACE + "#" + "EchoMessage"; private static final EchoMessageOperationContext _ECHO_MESSAGE_OPERATION_CONTEXT = new EchoMessageOperationContext(); public static final String ECHO_STREAM_MESSAGES = SERVICE_NAMESPACE + "#" + "EchoStreamMessages"; private static final EchoStreamMessagesOperationContext _ECHO_STREAM_MESSAGES_OPERATION_CONTEXT = new EchoStreamMessagesOperationContext(); public static final String GET_ALL_CUSTOMERS = SERVICE_NAMESPACE + "#" + "GetAllCustomers"; private static final GetAllCustomersOperationContext _GET_ALL_CUSTOMERS_OPERATION_CONTEXT = new GetAllCustomersOperationContext(); public static final String GET_ALL_PRODUCTS = SERVICE_NAMESPACE + "#" + "GetAllProducts"; private static final GetAllProductsOperationContext _GET_ALL_PRODUCTS_OPERATION_CONTEXT = new GetAllProductsOperationContext(); static { SERVICE_OPERATION_MODEL_MAP.put(CAUSE_SERVICE_ERROR, _CAUSE_SERVICE_ERROR_OPERATION_CONTEXT); SERVICE_OPERATION_SET.add(CAUSE_SERVICE_ERROR); SERVICE_OPERATION_MODEL_MAP.put(CAUSE_STREAM_SERVICE_TO_ERROR, _CAUSE_STREAM_SERVICE_TO_ERROR_OPERATION_CONTEXT); SERVICE_OPERATION_SET.add(CAUSE_STREAM_SERVICE_TO_ERROR); SERVICE_OPERATION_MODEL_MAP.put(ECHO_MESSAGE, _ECHO_MESSAGE_OPERATION_CONTEXT); SERVICE_OPERATION_SET.add(ECHO_MESSAGE); SERVICE_OPERATION_MODEL_MAP.put(ECHO_STREAM_MESSAGES, _ECHO_STREAM_MESSAGES_OPERATION_CONTEXT); SERVICE_OPERATION_SET.add(ECHO_STREAM_MESSAGES); SERVICE_OPERATION_MODEL_MAP.put(GET_ALL_CUSTOMERS, _GET_ALL_CUSTOMERS_OPERATION_CONTEXT); SERVICE_OPERATION_SET.add(GET_ALL_CUSTOMERS); SERVICE_OPERATION_MODEL_MAP.put(GET_ALL_PRODUCTS, _GET_ALL_PRODUCTS_OPERATION_CONTEXT); SERVICE_OPERATION_SET.add(GET_ALL_PRODUCTS); SERVICE_OBJECT_MODEL_MAP.put(CauseServiceErrorRequest.APPLICATION_MODEL_TYPE, CauseServiceErrorRequest.class); SERVICE_OBJECT_MODEL_MAP.put(CauseServiceErrorResponse.APPLICATION_MODEL_TYPE, CauseServiceErrorResponse.class); SERVICE_OBJECT_MODEL_MAP.put(Customer.APPLICATION_MODEL_TYPE, Customer.class); SERVICE_OBJECT_MODEL_MAP.put(EchoMessageRequest.APPLICATION_MODEL_TYPE, EchoMessageRequest.class); SERVICE_OBJECT_MODEL_MAP.put(EchoMessageResponse.APPLICATION_MODEL_TYPE, EchoMessageResponse.class); SERVICE_OBJECT_MODEL_MAP.put(EchoStreamingMessage.APPLICATION_MODEL_TYPE, EchoStreamingMessage.class); SERVICE_OBJECT_MODEL_MAP.put(EchoStreamingRequest.APPLICATION_MODEL_TYPE, EchoStreamingRequest.class); SERVICE_OBJECT_MODEL_MAP.put(EchoStreamingResponse.APPLICATION_MODEL_TYPE, EchoStreamingResponse.class); SERVICE_OBJECT_MODEL_MAP.put(FruitEnum.APPLICATION_MODEL_TYPE, FruitEnum.class); SERVICE_OBJECT_MODEL_MAP.put(GetAllCustomersRequest.APPLICATION_MODEL_TYPE, GetAllCustomersRequest.class); SERVICE_OBJECT_MODEL_MAP.put(GetAllCustomersResponse.APPLICATION_MODEL_TYPE, GetAllCustomersResponse.class); SERVICE_OBJECT_MODEL_MAP.put(GetAllProductsRequest.APPLICATION_MODEL_TYPE, GetAllProductsRequest.class); SERVICE_OBJECT_MODEL_MAP.put(GetAllProductsResponse.APPLICATION_MODEL_TYPE, GetAllProductsResponse.class); SERVICE_OBJECT_MODEL_MAP.put(MessageData.APPLICATION_MODEL_TYPE, MessageData.class); SERVICE_OBJECT_MODEL_MAP.put(Pair.APPLICATION_MODEL_TYPE, Pair.class); SERVICE_OBJECT_MODEL_MAP.put(Product.APPLICATION_MODEL_TYPE, Product.class); SERVICE_OBJECT_MODEL_MAP.put(ServiceError.APPLICATION_MODEL_TYPE, ServiceError.class); } private EchoTestRPCServiceModel() { } public static EchoTestRPCServiceModel getInstance() { return INSTANCE; } @Override public String getServiceName() { return "awstest#EchoTestRPC"; } public static CauseServiceErrorOperationContext getCauseServiceErrorModelContext() { return _CAUSE_SERVICE_ERROR_OPERATION_CONTEXT; } public static CauseStreamServiceToErrorOperationContext getCauseStreamServiceToErrorModelContext( ) { return _CAUSE_STREAM_SERVICE_TO_ERROR_OPERATION_CONTEXT; } public static EchoMessageOperationContext getEchoMessageModelContext() { return _ECHO_MESSAGE_OPERATION_CONTEXT; } public static EchoStreamMessagesOperationContext getEchoStreamMessagesModelContext() { return _ECHO_STREAM_MESSAGES_OPERATION_CONTEXT; } public static GetAllCustomersOperationContext getGetAllCustomersModelContext() { return _GET_ALL_CUSTOMERS_OPERATION_CONTEXT; } public static GetAllProductsOperationContext getGetAllProductsModelContext() { return _GET_ALL_PRODUCTS_OPERATION_CONTEXT; } @Override public final Collection<String> getAllOperations() { // Return a defensive copy so caller cannot change internal structure of service model return new HashSet<String>(SERVICE_OPERATION_SET); } @Override protected Optional<Class<? extends EventStreamJsonMessage>> getServiceClassType( String applicationModelType) { if (SERVICE_OBJECT_MODEL_MAP.containsKey(applicationModelType)) { return Optional.of(SERVICE_OBJECT_MODEL_MAP.get(applicationModelType)); } return Optional.empty(); } @Override public OperationModelContext getOperationModelContext(String operationName) { return SERVICE_OPERATION_MODEL_MAP.get(operationName); } }
5,429
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest/model/EchoStreamingResponse.java
package software.amazon.awssdk.awstest.model; import java.lang.Object; import java.lang.Override; import java.lang.String; import java.util.Objects; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public class EchoStreamingResponse implements EventStreamJsonMessage { public static final String APPLICATION_MODEL_TYPE = "awstest#EchoStreamingResponse"; public static final EchoStreamingResponse VOID; static { VOID = new EchoStreamingResponse() { @Override public boolean isVoid() { return true; } }; } public EchoStreamingResponse() { } @Override public String getApplicationModelType() { return APPLICATION_MODEL_TYPE; } @Override public boolean equals(Object rhs) { if (rhs == null) return false; if (!(rhs instanceof EchoStreamingResponse)) return false; if (this == rhs) return true; final EchoStreamingResponse other = (EchoStreamingResponse)rhs; boolean isEquals = true; return isEquals; } @Override public int hashCode() { return Objects.hash(); } }
5,430
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest/model/Product.java
package software.amazon.awssdk.awstest.model; import com.google.gson.annotations.Expose; import java.lang.Float; import java.lang.Object; import java.lang.Override; import java.lang.String; import java.util.Objects; import java.util.Optional; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public class Product implements EventStreamJsonMessage { public static final String APPLICATION_MODEL_TYPE = "awstest#Product"; public static final Product VOID; static { VOID = new Product() { @Override public boolean isVoid() { return true; } }; } @Expose( serialize = true, deserialize = true ) private Optional<String> name; @Expose( serialize = true, deserialize = true ) private Optional<Float> price; public Product() { this.name = Optional.empty(); this.price = Optional.empty(); } public String getName() { if (name.isPresent()) { return name.get(); } return null; } public void setName(final String name) { this.name = Optional.ofNullable(name); } public Product withName(final String name) { setName(name); return this; } public Float getPrice() { if (price.isPresent()) { return price.get(); } return null; } public void setPrice(final Float price) { this.price = Optional.ofNullable(price); } public Product withPrice(final Float price) { setPrice(price); return this; } @Override public String getApplicationModelType() { return APPLICATION_MODEL_TYPE; } @Override public boolean equals(Object rhs) { if (rhs == null) return false; if (!(rhs instanceof Product)) return false; if (this == rhs) return true; final Product other = (Product)rhs; boolean isEquals = true; isEquals = isEquals && this.name.equals(other.name); isEquals = isEquals && this.price.equals(other.price); return isEquals; } @Override public int hashCode() { return Objects.hash(name, price); } }
5,431
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest/model/Pair.java
package software.amazon.awssdk.awstest.model; import com.google.gson.annotations.Expose; import java.lang.Object; import java.lang.Override; import java.lang.String; import java.util.Objects; import java.util.Optional; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public class Pair implements EventStreamJsonMessage { public static final String APPLICATION_MODEL_TYPE = "awstest#Pair"; public static final Pair VOID; static { VOID = new Pair() { @Override public boolean isVoid() { return true; } }; } @Expose( serialize = true, deserialize = true ) private Optional<String> key; @Expose( serialize = true, deserialize = true ) private Optional<String> value; public Pair() { this.key = Optional.empty(); this.value = Optional.empty(); } public String getKey() { if (key.isPresent()) { return key.get(); } return null; } public void setKey(final String key) { this.key = Optional.ofNullable(key); } public Pair withKey(final String key) { setKey(key); return this; } public String getValue() { if (value.isPresent()) { return value.get(); } return null; } public void setValue(final String value) { this.value = Optional.ofNullable(value); } public Pair withValue(final String value) { setValue(value); return this; } @Override public String getApplicationModelType() { return APPLICATION_MODEL_TYPE; } @Override public boolean equals(Object rhs) { if (rhs == null) return false; if (!(rhs instanceof Pair)) return false; if (this == rhs) return true; final Pair other = (Pair)rhs; boolean isEquals = true; isEquals = isEquals && this.key.equals(other.key); isEquals = isEquals && this.value.equals(other.value); return isEquals; } @Override public int hashCode() { return Objects.hash(key, value); } }
5,432
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest/model/Customer.java
package software.amazon.awssdk.awstest.model; import com.google.gson.annotations.Expose; import java.lang.Long; import java.lang.Object; import java.lang.Override; import java.lang.String; import java.util.Objects; import java.util.Optional; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public class Customer implements EventStreamJsonMessage { public static final String APPLICATION_MODEL_TYPE = "awstest#Customer"; public static final Customer VOID; static { VOID = new Customer() { @Override public boolean isVoid() { return true; } }; } @Expose( serialize = true, deserialize = true ) private Optional<Long> id; @Expose( serialize = true, deserialize = true ) private Optional<String> firstName; @Expose( serialize = true, deserialize = true ) private Optional<String> lastName; public Customer() { this.id = Optional.empty(); this.firstName = Optional.empty(); this.lastName = Optional.empty(); } public Long getId() { if (id.isPresent()) { return id.get(); } return null; } public void setId(final Long id) { this.id = Optional.ofNullable(id); } public Customer withId(final Long id) { setId(id); return this; } public String getFirstName() { if (firstName.isPresent()) { return firstName.get(); } return null; } public void setFirstName(final String firstName) { this.firstName = Optional.ofNullable(firstName); } public Customer withFirstName(final String firstName) { setFirstName(firstName); return this; } public String getLastName() { if (lastName.isPresent()) { return lastName.get(); } return null; } public void setLastName(final String lastName) { this.lastName = Optional.ofNullable(lastName); } public Customer withLastName(final String lastName) { setLastName(lastName); return this; } @Override public String getApplicationModelType() { return APPLICATION_MODEL_TYPE; } @Override public boolean equals(Object rhs) { if (rhs == null) return false; if (!(rhs instanceof Customer)) return false; if (this == rhs) return true; final Customer other = (Customer)rhs; boolean isEquals = true; isEquals = isEquals && this.id.equals(other.id); isEquals = isEquals && this.firstName.equals(other.firstName); isEquals = isEquals && this.lastName.equals(other.lastName); return isEquals; } @Override public int hashCode() { return Objects.hash(id, firstName, lastName); } }
5,433
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest/model/GetAllProductsResponse.java
package software.amazon.awssdk.awstest.model; import com.google.gson.annotations.Expose; import java.lang.Object; import java.lang.Override; import java.lang.String; import java.util.Map; import java.util.Objects; import java.util.Optional; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public class GetAllProductsResponse implements EventStreamJsonMessage { public static final String APPLICATION_MODEL_TYPE = "awstest#GetAllProductsResponse"; public static final GetAllProductsResponse VOID; static { VOID = new GetAllProductsResponse() { @Override public boolean isVoid() { return true; } }; } @Expose( serialize = true, deserialize = true ) private Optional<Map<String, Product>> products; public GetAllProductsResponse() { this.products = Optional.empty(); } public Map<String, Product> getProducts() { if (products.isPresent()) { return products.get(); } return null; } public void setProducts(final Map<String, Product> products) { this.products = Optional.ofNullable(products); } public GetAllProductsResponse withProducts(final Map<String, Product> products) { setProducts(products); return this; } @Override public String getApplicationModelType() { return APPLICATION_MODEL_TYPE; } @Override public boolean equals(Object rhs) { if (rhs == null) return false; if (!(rhs instanceof GetAllProductsResponse)) return false; if (this == rhs) return true; final GetAllProductsResponse other = (GetAllProductsResponse)rhs; boolean isEquals = true; isEquals = isEquals && this.products.equals(other.products); return isEquals; } @Override public int hashCode() { return Objects.hash(products); } }
5,434
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest/model/CauseServiceErrorRequest.java
package software.amazon.awssdk.awstest.model; import java.lang.Object; import java.lang.Override; import java.lang.String; import java.util.Objects; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public class CauseServiceErrorRequest implements EventStreamJsonMessage { public static final String APPLICATION_MODEL_TYPE = "awstest#CauseServiceErrorRequest"; public static final CauseServiceErrorRequest VOID; static { VOID = new CauseServiceErrorRequest() { @Override public boolean isVoid() { return true; } }; } public CauseServiceErrorRequest() { } @Override public String getApplicationModelType() { return APPLICATION_MODEL_TYPE; } @Override public boolean equals(Object rhs) { if (rhs == null) return false; if (!(rhs instanceof CauseServiceErrorRequest)) return false; if (this == rhs) return true; final CauseServiceErrorRequest other = (CauseServiceErrorRequest)rhs; boolean isEquals = true; return isEquals; } @Override public int hashCode() { return Objects.hash(); } }
5,435
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest/model/GetAllCustomersResponse.java
package software.amazon.awssdk.awstest.model; import com.google.gson.annotations.Expose; import java.lang.Object; import java.lang.Override; import java.lang.String; import java.util.List; import java.util.Objects; import java.util.Optional; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public class GetAllCustomersResponse implements EventStreamJsonMessage { public static final String APPLICATION_MODEL_TYPE = "awstest#GetAllCustomersResponse"; public static final GetAllCustomersResponse VOID; static { VOID = new GetAllCustomersResponse() { @Override public boolean isVoid() { return true; } }; } @Expose( serialize = true, deserialize = true ) private Optional<List<Customer>> customers; public GetAllCustomersResponse() { this.customers = Optional.empty(); } public List<Customer> getCustomers() { if (customers.isPresent()) { return customers.get(); } return null; } public void setCustomers(final List<Customer> customers) { this.customers = Optional.ofNullable(customers); } public GetAllCustomersResponse withCustomers(final List<Customer> customers) { setCustomers(customers); return this; } @Override public String getApplicationModelType() { return APPLICATION_MODEL_TYPE; } @Override public boolean equals(Object rhs) { if (rhs == null) return false; if (!(rhs instanceof GetAllCustomersResponse)) return false; if (this == rhs) return true; final GetAllCustomersResponse other = (GetAllCustomersResponse)rhs; boolean isEquals = true; isEquals = isEquals && this.customers.equals(other.customers); return isEquals; } @Override public int hashCode() { return Objects.hash(customers); } }
5,436
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest/model/EchoStreamingRequest.java
package software.amazon.awssdk.awstest.model; import java.lang.Object; import java.lang.Override; import java.lang.String; import java.util.Objects; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public class EchoStreamingRequest implements EventStreamJsonMessage { public static final String APPLICATION_MODEL_TYPE = "awstest#EchoStreamingRequest"; public static final EchoStreamingRequest VOID; static { VOID = new EchoStreamingRequest() { @Override public boolean isVoid() { return true; } }; } public EchoStreamingRequest() { } @Override public String getApplicationModelType() { return APPLICATION_MODEL_TYPE; } @Override public boolean equals(Object rhs) { if (rhs == null) return false; if (!(rhs instanceof EchoStreamingRequest)) return false; if (this == rhs) return true; final EchoStreamingRequest other = (EchoStreamingRequest)rhs; boolean isEquals = true; return isEquals; } @Override public int hashCode() { return Objects.hash(); } }
5,437
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest/model/EchoMessageRequest.java
package software.amazon.awssdk.awstest.model; import com.google.gson.annotations.Expose; import java.lang.Object; import java.lang.Override; import java.lang.String; import java.util.Objects; import java.util.Optional; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public class EchoMessageRequest implements EventStreamJsonMessage { public static final String APPLICATION_MODEL_TYPE = "awstest#EchoMessageRequest"; public static final EchoMessageRequest VOID; static { VOID = new EchoMessageRequest() { @Override public boolean isVoid() { return true; } }; } @Expose( serialize = true, deserialize = true ) private Optional<MessageData> message; public EchoMessageRequest() { this.message = Optional.empty(); } public MessageData getMessage() { if (message.isPresent()) { return message.get(); } return null; } public void setMessage(final MessageData message) { this.message = Optional.ofNullable(message); } public EchoMessageRequest withMessage(final MessageData message) { setMessage(message); return this; } @Override public String getApplicationModelType() { return APPLICATION_MODEL_TYPE; } @Override public boolean equals(Object rhs) { if (rhs == null) return false; if (!(rhs instanceof EchoMessageRequest)) return false; if (this == rhs) return true; final EchoMessageRequest other = (EchoMessageRequest)rhs; boolean isEquals = true; isEquals = isEquals && this.message.equals(other.message); return isEquals; } @Override public int hashCode() { return Objects.hash(message); } }
5,438
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest/model/GetAllProductsRequest.java
package software.amazon.awssdk.awstest.model; import java.lang.Object; import java.lang.Override; import java.lang.String; import java.util.Objects; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public class GetAllProductsRequest implements EventStreamJsonMessage { public static final String APPLICATION_MODEL_TYPE = "awstest#GetAllProductsRequest"; public static final GetAllProductsRequest VOID; static { VOID = new GetAllProductsRequest() { @Override public boolean isVoid() { return true; } }; } public GetAllProductsRequest() { } @Override public String getApplicationModelType() { return APPLICATION_MODEL_TYPE; } @Override public boolean equals(Object rhs) { if (rhs == null) return false; if (!(rhs instanceof GetAllProductsRequest)) return false; if (this == rhs) return true; final GetAllProductsRequest other = (GetAllProductsRequest)rhs; boolean isEquals = true; return isEquals; } @Override public int hashCode() { return Objects.hash(); } }
5,439
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest/model/MessageData.java
package software.amazon.awssdk.awstest.model; import com.google.gson.annotations.Expose; import java.lang.Boolean; import java.lang.Object; import java.lang.Override; import java.lang.String; import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import software.amazon.awssdk.eventstreamrpc.EventStreamRPCServiceModel; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public class MessageData implements EventStreamJsonMessage { public static final String APPLICATION_MODEL_TYPE = "awstest#MessageData"; public static final MessageData VOID; static { VOID = new MessageData() { @Override public boolean isVoid() { return true; } }; } @Expose( serialize = true, deserialize = true ) private Optional<String> stringMessage; @Expose( serialize = true, deserialize = true ) private Optional<Boolean> booleanMessage; @Expose( serialize = true, deserialize = true ) private Optional<Instant> timeMessage; @Expose( serialize = true, deserialize = true ) private Optional<Map<String, Object>> documentMessage; @Expose( serialize = true, deserialize = true ) private Optional<String> enumMessage; @Expose( serialize = true, deserialize = true ) private Optional<byte[]> blobMessage; @Expose( serialize = true, deserialize = true ) private Optional<List<String>> stringListMessage; @Expose( serialize = true, deserialize = true ) private Optional<List<Pair>> keyValuePairList; @Expose( serialize = true, deserialize = true ) private Optional<Map<String, Product>> stringToValue; public MessageData() { this.stringMessage = Optional.empty(); this.booleanMessage = Optional.empty(); this.timeMessage = Optional.empty(); this.documentMessage = Optional.empty(); this.enumMessage = Optional.empty(); this.blobMessage = Optional.empty(); this.stringListMessage = Optional.empty(); this.keyValuePairList = Optional.empty(); this.stringToValue = Optional.empty(); } public String getStringMessage() { if (stringMessage.isPresent()) { return stringMessage.get(); } return null; } public void setStringMessage(final String stringMessage) { this.stringMessage = Optional.ofNullable(stringMessage); } public MessageData withStringMessage(final String stringMessage) { setStringMessage(stringMessage); return this; } public Boolean isBooleanMessage() { if (booleanMessage.isPresent()) { return booleanMessage.get(); } return null; } public void setBooleanMessage(final Boolean booleanMessage) { this.booleanMessage = Optional.ofNullable(booleanMessage); } public MessageData withBooleanMessage(final Boolean booleanMessage) { setBooleanMessage(booleanMessage); return this; } public Instant getTimeMessage() { if (timeMessage.isPresent()) { return timeMessage.get(); } return null; } public void setTimeMessage(final Instant timeMessage) { this.timeMessage = Optional.ofNullable(timeMessage); } public MessageData withTimeMessage(final Instant timeMessage) { setTimeMessage(timeMessage); return this; } public Map<String, Object> getDocumentMessage() { if (documentMessage.isPresent()) { return documentMessage.get(); } return null; } public void setDocumentMessage(final Map<String, Object> documentMessage) { this.documentMessage = Optional.ofNullable(documentMessage); } public MessageData withDocumentMessage(final Map<String, Object> documentMessage) { setDocumentMessage(documentMessage); return this; } public FruitEnum getEnumMessage() { if (enumMessage.isPresent()) { return FruitEnum.get(enumMessage.get()); } return null; } public String getEnumMessageAsString() { if (enumMessage.isPresent()) { return enumMessage.get(); } return null; } public void setEnumMessage(final String enumMessage) { this.enumMessage = Optional.ofNullable(enumMessage); } public MessageData withEnumMessage(final String enumMessage) { setEnumMessage(enumMessage); return this; } public void setEnumMessage(final FruitEnum enumMessage) { this.enumMessage = Optional.ofNullable(enumMessage.getValue()); } public MessageData withEnumMessage(final FruitEnum enumMessage) { setEnumMessage(enumMessage); return this; } public byte[] getBlobMessage() { if (blobMessage.isPresent()) { return blobMessage.get(); } return null; } public void setBlobMessage(final byte[] blobMessage) { this.blobMessage = Optional.ofNullable(blobMessage); } public MessageData withBlobMessage(final byte[] blobMessage) { setBlobMessage(blobMessage); return this; } public List<String> getStringListMessage() { if (stringListMessage.isPresent()) { return stringListMessage.get(); } return null; } public void setStringListMessage(final List<String> stringListMessage) { this.stringListMessage = Optional.ofNullable(stringListMessage); } public MessageData withStringListMessage(final List<String> stringListMessage) { setStringListMessage(stringListMessage); return this; } public List<Pair> getKeyValuePairList() { if (keyValuePairList.isPresent()) { return keyValuePairList.get(); } return null; } public void setKeyValuePairList(final List<Pair> keyValuePairList) { this.keyValuePairList = Optional.ofNullable(keyValuePairList); } public MessageData withKeyValuePairList(final List<Pair> keyValuePairList) { setKeyValuePairList(keyValuePairList); return this; } public Map<String, Product> getStringToValue() { if (stringToValue.isPresent()) { return stringToValue.get(); } return null; } public void setStringToValue(final Map<String, Product> stringToValue) { this.stringToValue = Optional.ofNullable(stringToValue); } public MessageData withStringToValue(final Map<String, Product> stringToValue) { setStringToValue(stringToValue); return this; } @Override public String getApplicationModelType() { return APPLICATION_MODEL_TYPE; } @Override public boolean equals(Object rhs) { if (rhs == null) return false; if (!(rhs instanceof MessageData)) return false; if (this == rhs) return true; final MessageData other = (MessageData)rhs; boolean isEquals = true; isEquals = isEquals && this.stringMessage.equals(other.stringMessage); isEquals = isEquals && this.booleanMessage.equals(other.booleanMessage); isEquals = isEquals && this.timeMessage.equals(other.timeMessage); isEquals = isEquals && this.documentMessage.equals(other.documentMessage); isEquals = isEquals && this.enumMessage.equals(other.enumMessage); isEquals = isEquals && EventStreamRPCServiceModel.blobTypeEquals(this.blobMessage, other.blobMessage); isEquals = isEquals && this.stringListMessage.equals(other.stringListMessage); isEquals = isEquals && this.keyValuePairList.equals(other.keyValuePairList); isEquals = isEquals && this.stringToValue.equals(other.stringToValue); return isEquals; } @Override public int hashCode() { return Objects.hash(stringMessage, booleanMessage, timeMessage, documentMessage, enumMessage, blobMessage, stringListMessage, keyValuePairList, stringToValue); } }
5,440
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest/model/FruitEnum.java
package software.amazon.awssdk.awstest.model; import com.google.gson.annotations.SerializedName; import java.lang.Override; import java.lang.String; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public enum FruitEnum implements EventStreamJsonMessage { @SerializedName("apl") APPLE("apl"), @SerializedName("org") ORANGE("org"), @SerializedName("ban") BANANA("ban"), @SerializedName("pin") PINEAPPLE("pin"); public static final String APPLICATION_MODEL_TYPE = "awstest#FruitEnum"; private static final Map<String, FruitEnum> lookup = new HashMap<String, FruitEnum>(); static { for (FruitEnum value:FruitEnum.values()) { lookup.put(value.getValue(), value); } } String value; FruitEnum(String value) { this.value = value; } public String getValue() { return value; } @Override public String getApplicationModelType() { return APPLICATION_MODEL_TYPE; } public static FruitEnum get(String value) { return lookup.get(value); } }
5,441
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest/model/EchoTestRPCError.java
package software.amazon.awssdk.awstest.model; import java.lang.String; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; import software.amazon.awssdk.eventstreamrpc.model.EventStreamOperationError; public abstract class EchoTestRPCError extends EventStreamOperationError implements EventStreamJsonMessage { EchoTestRPCError(String errorCode, String errorMessage) { super("awstest#EchoTestRPC", errorCode, errorMessage); } public abstract String getErrorTypeString(); public boolean isRetryable() { return getErrorTypeString().equals("server"); } public boolean isServerError() { return getErrorTypeString().equals("server"); } public boolean isClientError() { return getErrorTypeString().equals("client"); } }
5,442
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest/model/EchoStreamingMessage.java
package software.amazon.awssdk.awstest.model; import com.google.gson.annotations.Expose; import java.lang.Object; import java.lang.Override; import java.lang.String; import java.util.Objects; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Predicate; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public class EchoStreamingMessage implements EventStreamJsonMessage { public static final String APPLICATION_MODEL_TYPE = "awstest#EchoStreamingMessage"; private transient UnionMember setUnionMember; @Expose( serialize = true, deserialize = true ) private Optional<MessageData> streamMessage; @Expose( serialize = true, deserialize = true ) private Optional<Pair> keyValuePair; public EchoStreamingMessage() { this.streamMessage = Optional.empty(); this.keyValuePair = Optional.empty(); } public MessageData getStreamMessage() { if (streamMessage.isPresent() && (setUnionMember == UnionMember.STREAM_MESSAGE)) { return streamMessage.get(); } return null; } public void setStreamMessage(final MessageData streamMessage) { if (setUnionMember != null) { setUnionMember.nullify(this); } this.streamMessage = Optional.of(streamMessage); this.setUnionMember = UnionMember.STREAM_MESSAGE; } public EchoStreamingMessage withStreamMessage(final MessageData streamMessage) { setStreamMessage(streamMessage); return this; } public Pair getKeyValuePair() { if (keyValuePair.isPresent() && (setUnionMember == UnionMember.KEY_VALUE_PAIR)) { return keyValuePair.get(); } return null; } public void setKeyValuePair(final Pair keyValuePair) { if (setUnionMember != null) { setUnionMember.nullify(this); } this.keyValuePair = Optional.of(keyValuePair); this.setUnionMember = UnionMember.KEY_VALUE_PAIR; } public EchoStreamingMessage withKeyValuePair(final Pair keyValuePair) { setKeyValuePair(keyValuePair); return this; } /** * Returns an indicator for which enum member is set. Can be used to convert to proper type. */ public UnionMember getSetUnionMember() { return setUnionMember; } @Override public String getApplicationModelType() { return APPLICATION_MODEL_TYPE; } public void selfDesignateSetUnionMember() { int setCount = 0; UnionMember[] members = UnionMember.values(); for (int memberIdx = 0; memberIdx < UnionMember.values().length; ++memberIdx) { if (members[memberIdx].isPresent(this)) { ++setCount; this.setUnionMember = members[memberIdx]; } } // only bad outcome here is if there's more than one member set. It's possible for none to be set if (setCount > 1) { throw new IllegalArgumentException("More than one union member set for type: " + getApplicationModelType()); } } @Override public void postFromJson() { selfDesignateSetUnionMember(); } @Override public boolean equals(Object rhs) { if (rhs == null) return false; if (!(rhs instanceof EchoStreamingMessage)) return false; if (this == rhs) return true; final EchoStreamingMessage other = (EchoStreamingMessage)rhs; boolean isEquals = true; isEquals = isEquals && this.streamMessage.equals(other.streamMessage); isEquals = isEquals && this.keyValuePair.equals(other.keyValuePair); isEquals = isEquals && this.setUnionMember.equals(other.setUnionMember); return isEquals; } @Override public int hashCode() { return Objects.hash(streamMessage, keyValuePair, setUnionMember); } public enum UnionMember { STREAM_MESSAGE("STREAM_MESSAGE", (software.amazon.awssdk.awstest.model.EchoStreamingMessage obj) -> obj.streamMessage = Optional.empty(), (software.amazon.awssdk.awstest.model.EchoStreamingMessage obj) -> obj.streamMessage != null && obj.streamMessage.isPresent()), KEY_VALUE_PAIR("KEY_VALUE_PAIR", (software.amazon.awssdk.awstest.model.EchoStreamingMessage obj) -> obj.keyValuePair = Optional.empty(), (software.amazon.awssdk.awstest.model.EchoStreamingMessage obj) -> obj.keyValuePair != null && obj.keyValuePair.isPresent()); private String fieldName; private Consumer<EchoStreamingMessage> nullifier; private Predicate<EchoStreamingMessage> isPresent; UnionMember(String fieldName, Consumer<EchoStreamingMessage> nullifier, Predicate<EchoStreamingMessage> isPresent) { this.fieldName = fieldName; this.nullifier = nullifier; this.isPresent = isPresent; } void nullify(EchoStreamingMessage obj) { nullifier.accept(obj); } boolean isPresent(EchoStreamingMessage obj) { return isPresent.test(obj); } } }
5,443
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest/model/ServiceError.java
package software.amazon.awssdk.awstest.model; import com.google.gson.annotations.Expose; import java.lang.Object; import java.lang.Override; import java.lang.String; import java.util.Objects; import java.util.Optional; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public class ServiceError extends EchoTestRPCError implements EventStreamJsonMessage { public static final String APPLICATION_MODEL_TYPE = "awstest#ServiceError"; public static final ServiceError VOID; static { VOID = new ServiceError() { @Override public boolean isVoid() { return true; } }; } @Expose( serialize = true, deserialize = true ) private Optional<String> message; @Expose( serialize = true, deserialize = true ) private Optional<String> value; public ServiceError(String errorMessage) { super("ServiceError", errorMessage); this.message = Optional.ofNullable(errorMessage); this.value = Optional.empty(); } public ServiceError() { super("ServiceError", ""); this.message = Optional.empty(); this.value = Optional.empty(); } @Override public String getErrorTypeString() { return "server"; } public String getMessage() { if (message.isPresent()) { return message.get(); } return null; } public void setMessage(final String message) { this.message = Optional.ofNullable(message); } public ServiceError withMessage(final String message) { setMessage(message); return this; } public String getValue() { if (value.isPresent()) { return value.get(); } return null; } public void setValue(final String value) { this.value = Optional.ofNullable(value); } public ServiceError withValue(final String value) { setValue(value); return this; } @Override public String getApplicationModelType() { return APPLICATION_MODEL_TYPE; } @Override public boolean equals(Object rhs) { if (rhs == null) return false; if (!(rhs instanceof ServiceError)) return false; if (this == rhs) return true; final ServiceError other = (ServiceError)rhs; boolean isEquals = true; isEquals = isEquals && this.message.equals(other.message); isEquals = isEquals && this.value.equals(other.value); return isEquals; } @Override public int hashCode() { return Objects.hash(message, value); } }
5,444
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest/model/GetAllCustomersRequest.java
package software.amazon.awssdk.awstest.model; import java.lang.Object; import java.lang.Override; import java.lang.String; import java.util.Objects; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public class GetAllCustomersRequest implements EventStreamJsonMessage { public static final String APPLICATION_MODEL_TYPE = "awstest#GetAllCustomersRequest"; public static final GetAllCustomersRequest VOID; static { VOID = new GetAllCustomersRequest() { @Override public boolean isVoid() { return true; } }; } public GetAllCustomersRequest() { } @Override public String getApplicationModelType() { return APPLICATION_MODEL_TYPE; } @Override public boolean equals(Object rhs) { if (rhs == null) return false; if (!(rhs instanceof GetAllCustomersRequest)) return false; if (this == rhs) return true; final GetAllCustomersRequest other = (GetAllCustomersRequest)rhs; boolean isEquals = true; return isEquals; } @Override public int hashCode() { return Objects.hash(); } }
5,445
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest/model/CauseServiceErrorResponse.java
package software.amazon.awssdk.awstest.model; import java.lang.Object; import java.lang.Override; import java.lang.String; import java.util.Objects; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public class CauseServiceErrorResponse implements EventStreamJsonMessage { public static final String APPLICATION_MODEL_TYPE = "awstest#CauseServiceErrorResponse"; public static final CauseServiceErrorResponse VOID; static { VOID = new CauseServiceErrorResponse() { @Override public boolean isVoid() { return true; } }; } public CauseServiceErrorResponse() { } @Override public String getApplicationModelType() { return APPLICATION_MODEL_TYPE; } @Override public boolean equals(Object rhs) { if (rhs == null) return false; if (!(rhs instanceof CauseServiceErrorResponse)) return false; if (this == rhs) return true; final CauseServiceErrorResponse other = (CauseServiceErrorResponse)rhs; boolean isEquals = true; return isEquals; } @Override public int hashCode() { return Objects.hash(); } }
5,446
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/test/java/software/amazon/awssdk/awstest/model/EchoMessageResponse.java
package software.amazon.awssdk.awstest.model; import com.google.gson.annotations.Expose; import java.lang.Object; import java.lang.Override; import java.lang.String; import java.util.Objects; import java.util.Optional; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public class EchoMessageResponse implements EventStreamJsonMessage { public static final String APPLICATION_MODEL_TYPE = "awstest#EchoMessageResponse"; public static final EchoMessageResponse VOID; static { VOID = new EchoMessageResponse() { @Override public boolean isVoid() { return true; } }; } @Expose( serialize = true, deserialize = true ) private Optional<MessageData> message; public EchoMessageResponse() { this.message = Optional.empty(); } public MessageData getMessage() { if (message.isPresent()) { return message.get(); } return null; } public void setMessage(final MessageData message) { this.message = Optional.ofNullable(message); } public EchoMessageResponse withMessage(final MessageData message) { setMessage(message); return this; } @Override public String getApplicationModelType() { return APPLICATION_MODEL_TYPE; } @Override public boolean equals(Object rhs) { if (rhs == null) return false; if (!(rhs instanceof EchoMessageResponse)) return false; if (this == rhs) return true; final EchoMessageResponse other = (EchoMessageResponse)rhs; boolean isEquals = true; isEquals = isEquals && this.message.equals(other.message); return isEquals; } @Override public int hashCode() { return Objects.hash(message); } }
5,447
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk/eventstreamrpc/StreamEventPublisher.java
package software.amazon.awssdk.eventstreamrpc; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; import java.util.concurrent.CompletableFuture; /** * Interface to enable sending events over an open stream operation. * * @param <StreamEventType> Data to push over the open stream */ public interface StreamEventPublisher<StreamEventType extends EventStreamJsonMessage> { /** * Publish an event over an open stream operation. * * @param streamEvent event to publish * @return Completable future indicating flush of the event over the stream */ public CompletableFuture<Void> sendStreamEvent(final StreamEventType streamEvent); /** * Closes the stream by sending an empty message * * @return Completable future indicating flush of the stream termination message */ public CompletableFuture<Void> closeStream(); }
5,448
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk/eventstreamrpc/EventStreamClosedException.java
package software.amazon.awssdk.eventstreamrpc; /** * Thrown when a EventStream closed exception occurs */ public class EventStreamClosedException extends RuntimeException { /** * Creates a new EventStreamClosedException from the given continuation ID * @param continauationId The continuation ID that caused the exception */ public EventStreamClosedException(long continauationId) { //TODO: Is hex formatting here useful? It is short, but not consistent anywhere else yet super(String.format("EventStream continuation [%s] is already closed!", Long.toHexString(continauationId))); } /** * Creates a new EventStreamClosedException with a given messasge * @param msg The message to associated with the EventStreamClosedException */ public EventStreamClosedException(String msg) { //TODO: Is hex formatting here useful? It is short, but not consistent anywhere else yet super(msg); } }
5,449
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk/eventstreamrpc/UnmappedDataException.java
package software.amazon.awssdk.eventstreamrpc; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; /** * Unmapped data exception is generated either on server or client side when recieving data * over the wire and is unable to map properly to an expected type to be received * for the operation. Or an exception (don't have to be called out). */ public class UnmappedDataException extends RuntimeException { /** * Creates a new Unmapped data exception. * @param applicationModelType The application model type that caused the exception */ public UnmappedDataException(String applicationModelType) { super(String.format("Cannot find Java class type for application model type: %s", applicationModelType)); } /** * Creates a new Unmapped data exception. * @param expectedClass The application class that caused the exception */ public UnmappedDataException(Class<? extends EventStreamJsonMessage> expectedClass) { super(String.format("Data does not map into Java class: %s", expectedClass.getCanonicalName())); } /** * Creates a new Unmapped data exception. * @param applicationModelType The application model type that caused the exception * @param expectedClass The application class that caused the exception */ public UnmappedDataException(String applicationModelType, Class<? extends EventStreamJsonMessage> expectedClass) { super(String.format("Found model-type {%s} which does not map into Java class: %s", applicationModelType, expectedClass.getCanonicalName())); } }
5,450
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk/eventstreamrpc/DeserializationException.java
package software.amazon.awssdk.eventstreamrpc; /** * Thrown when a deserialization exception occurs */ public class DeserializationException extends RuntimeException { /** * Creates a new DeserializationException from the given data * @param lexicalData The data that could not be deserialized */ public DeserializationException(Object lexicalData) { this(lexicalData, null); } /** * Creates a new DeserializationException from the given data * @param lexicalData The data that could not be deserialized * @param cause The reason the data could not be deserialized */ public DeserializationException(Object lexicalData, Throwable cause) { super("Could not deserialize data: [" + lexicalData.toString() + "]", cause); } }
5,451
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk/eventstreamrpc/MessageAmendInfo.java
package software.amazon.awssdk.eventstreamrpc; import software.amazon.awssdk.crt.eventstream.Header; import java.util.List; /** * Small data class used to hold information that may be used differently depending on the context * * For sending messages, the headers stored in the object may be used to append to existing headers, * where it won't overwrite an existing one that may be outgoing. * * The payload may or may not be used. Refer to the method that accepts or expects this structure to * understand what parts are used and which are not. For example, for EventStreamRPCConnection's * connect() method, the headers are used verbatim into the activate request and the payload too. * * For a sendStreamEvent(obj, amendInfo) hypothetical overload, only the headers that don't overwrite * :content-type, service-model-type would be used, and the payload would be completely ignored from * this structure. */ public class MessageAmendInfo { private final List<Header> headers; private final byte[] payload; /** * Constructs a new MessageAmendInfo * @param headers The headers to store * @param payload The payload to store */ public MessageAmendInfo(List<Header> headers, byte[] payload) { this.headers = headers; this.payload = payload; } /** * Returns the headers stored in the object. For sent messages, * the headers stored in the object may be used to append to existing headers, * where it won't overwrite an existing one that may be outgoing. * * @return The headers stored */ public List<Header> getHeaders() { return headers; } /** * Returns the payload stored in the object. A payload may, or may not, be used * in a given MessageAmendInfo. Refer to the method that accepts or expects this * structure to understand what parts are used and which are not. * @return The payload stored */ public byte[] getPayload() { return payload; } }
5,452
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk/eventstreamrpc/InvalidDataException.java
package software.amazon.awssdk.eventstreamrpc; import software.amazon.awssdk.crt.eventstream.MessageType; /** * An exception for invalid/unexpected data */ public class InvalidDataException extends RuntimeException { /** * Constructs a new InvalidDataException with the given MessageType, whose name will * be added to the exception. * @param unexpectedType The MessageType that caused the exception */ public InvalidDataException(MessageType unexpectedType) { super(String.format("Unexpected message type received: %s", unexpectedType.name())); } }
5,453
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk/eventstreamrpc/SerializationException.java
package software.amazon.awssdk.eventstreamrpc; /** * Thrown when a serialization exception occurs */ public class SerializationException extends RuntimeException { /** * Creates a new serlization exception * @param object The object that caused the serlization exception */ public SerializationException(Object object) { this(object, null); } /** * Creates a new serlization exception * @param object The object that caused the serlization exception * @param cause The cause of the serlization exception */ public SerializationException(Object object, Throwable cause) { super("Could not serialize object: " + object.toString(), cause); } }
5,454
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk/eventstreamrpc/EventStreamRPCServiceModel.java
package software.amazon.awssdk.eventstreamrpc; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import software.amazon.awssdk.eventstreamrpc.model.AccessDeniedException; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; import software.amazon.awssdk.eventstreamrpc.model.UnsupportedOperationException; import software.amazon.awssdk.eventstreamrpc.model.ValidationException; import java.io.IOException; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.Arrays; import java.util.Base64; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Optional; /** * Implementers of this service model are expected to likely be singletons. There * should be little value to having more than one, though between different instances * properly constructed for a service, they can be used interchangeably */ public abstract class EventStreamRPCServiceModel { private static final Gson GSON; /** * Version header string */ static final String VERSION_HEADER = ":version"; /** * Content type header string */ public static final String CONTENT_TYPE_HEADER = ":content-type"; /** * Content type application text string */ public static final String CONTENT_TYPE_APPLICATION_TEXT = "text/plain"; /** * Content type application json string */ public static final String CONTENT_TYPE_APPLICATION_JSON = "application/json"; /** * Service model type header */ public static final String SERVICE_MODEL_TYPE_HEADER = "service-model-type"; static { GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapterFactory(new ForceNullsForMapTypeAdapterFactory()); builder.registerTypeAdapterFactory(OptionalTypeAdapter.FACTORY); builder.registerTypeAdapterFactory(EventStreamPostFromJsonTypeAdapter.FACTORY); builder.registerTypeAdapter(byte[].class, new Base64BlobSerializerDeserializer()); builder.registerTypeAdapter(Instant.class, new InstantSerializerDeserializer()); builder.excludeFieldsWithoutExposeAnnotation(); GSON = builder.create(); } // Type adapter to automatically call "postFromJson" on all instances of EventStreamJsonMessage we construct private static class EventStreamPostFromJsonTypeAdapter<E extends EventStreamJsonMessage> extends TypeAdapter<E> { public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() { @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { if (EventStreamJsonMessage.class.isAssignableFrom(type.getRawType())) { final TypeAdapter<?> delegate = gson.getDelegateAdapter(this, type); return new EventStreamPostFromJsonTypeAdapter(delegate); } return null; } }; private final TypeAdapter<E> adapter; public EventStreamPostFromJsonTypeAdapter(TypeAdapter<E> adapter) { this.adapter = adapter; } @Override public void write(JsonWriter out, E value) throws IOException { adapter.write(out, value); } @Override public E read(JsonReader in) throws IOException { E obj = adapter.read(in); if (obj != null) { // Call postFromJson to finalize the deserialization. Especially important for unions to have their // member get set correctly. obj.postFromJson(); } return obj; } } private static class ForceNullsForMapTypeAdapterFactory implements TypeAdapterFactory { public final <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { if (Map.class.isAssignableFrom(type.getRawType())) { final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); return createCustomTypeAdapter(delegate); } return null; } private <T> TypeAdapter<T> createCustomTypeAdapter(TypeAdapter<T> delegate) { return new TypeAdapter<T>() { @Override public void write(JsonWriter out, T value) throws IOException { final boolean serializeNulls = out.getSerializeNulls(); try { out.setSerializeNulls(true); delegate.write(out, value); } finally { out.setSerializeNulls(serializeNulls); } } @Override public T read(JsonReader in) throws IOException { return delegate.read(in); } }; } } private static class OptionalTypeAdapter<E> extends TypeAdapter<Optional<E>> { public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() { @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { Class<T> rawType = (Class<T>) type.getRawType(); if (rawType != Optional.class) { return null; } final ParameterizedType parameterizedType = (ParameterizedType) type.getType(); final Type actualType = parameterizedType.getActualTypeArguments()[0]; final TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(actualType)); return new OptionalTypeAdapter(adapter); } }; private final TypeAdapter<E> adapter; public OptionalTypeAdapter(TypeAdapter<E> adapter) { this.adapter = adapter; } @Override public void write(JsonWriter out, Optional<E> value) throws IOException { if (value.isPresent()){ adapter.write(out, value.get()); } else if (value != null) { out.nullValue(); } else { } } @Override public Optional<E> read(JsonReader in) throws IOException { return Optional.ofNullable(adapter.read(in)); } } /** * Used to compare two members of a blob shape for equality. Array equals nesting * inside of an Optional doesn't work * * Note: Generated code for equals method of Smithy shapes relies on this * * @param lhs The first to compare * @param rhs The second to compare * @return True if both are equal, false otherwise */ public static boolean blobTypeEquals(Optional<byte[]> lhs, Optional<byte[]> rhs) { if (lhs.equals(rhs)) { //both are same instance, both are same contained array, or both are empty return true; } if (!lhs.isPresent() || !rhs.isPresent()) { //if just one or the other is empty at this point return false; } //now we know both are present so compare the arrays return Arrays.equals(lhs.get(), rhs.get()); } private static class Base64BlobSerializerDeserializer implements JsonSerializer<byte[]>, JsonDeserializer<byte[]> { private static final Base64.Encoder BASE_64_ENCODER = Base64.getEncoder(); private static final Base64.Decoder BASE_64_DECODER = Base64.getDecoder(); @Override public byte[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return BASE_64_DECODER.decode(json.getAsString()); } @Override public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(BASE_64_ENCODER.encodeToString(src)); } } private static class InstantSerializerDeserializer implements JsonSerializer<Instant>, JsonDeserializer<Instant> { @Override public Instant deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { double fSecondsEpoch = json.getAsDouble(); long secondsEpoch = (long)fSecondsEpoch; long nanoEpoch = (long)((fSecondsEpoch - secondsEpoch) * 1_000_000_000.); return Instant.ofEpochSecond(secondsEpoch, nanoEpoch); } @Override public JsonElement serialize(Instant src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive((double)src.getEpochSecond() + (double)src.getNano() / 1000000000.); } } /** * For getting the actual service name * @return The name of the service as a string */ public abstract String getServiceName(); private static final Map<String, Class<? extends EventStreamJsonMessage>> FRAMEWORK_APPLICATION_MODEL_TYPES = new HashMap<>(); static { //TODO: find a reliable way to verify all of these are set? reflection cannot scan a package FRAMEWORK_APPLICATION_MODEL_TYPES.put(AccessDeniedException.ERROR_CODE, AccessDeniedException.class); FRAMEWORK_APPLICATION_MODEL_TYPES.put(UnsupportedOperationException.ERROR_CODE, UnsupportedOperationException.class); FRAMEWORK_APPLICATION_MODEL_TYPES.put(ValidationException.ERROR_CODE, ValidationException.class); } /** * Returns the application model class * @param applicationModelType The application model * @return The class of the given application model */ final public Optional<Class<? extends EventStreamJsonMessage>> getApplicationModelClass(final String applicationModelType) { final Class<? extends EventStreamJsonMessage> clazz = FRAMEWORK_APPLICATION_MODEL_TYPES.get(applicationModelType); if (clazz != null) { return Optional.of(clazz); } return getServiceClassType(applicationModelType); } /** * Retreives all operations on the service * @return All operations on the service */ public abstract Collection<String> getAllOperations(); /** * Need to override per specific service type so it can look up all associated types and errors * possible. * * @param applicationModelType The application model * @return The service class type of the given application model */ protected abstract Optional<Class<? extends EventStreamJsonMessage>> getServiceClassType(String applicationModelType); /** * Retrieves the operation model context for a given operation name on the service * * This may not be a useful interface as generated code will typically pull a known operation model context * Public visibility is useful for testing * * @param operationName The name of the operation * @return The operation context associated with the given operation name */ public abstract OperationModelContext getOperationModelContext(String operationName); public byte[] toJson(final EventStreamJsonMessage message) { try { final byte[] json = message.toPayload(getGson()); final String stringJson = new String(json, StandardCharsets.UTF_8); //this feels like a hack. I'd prefer if java objects with no fields set serialized to being an empty object //rather than "null" if (null == stringJson || "null".equals(stringJson) || stringJson.isEmpty()) { return "{}".getBytes(StandardCharsets.UTF_8); } return json; } catch (Exception e) { throw new SerializationException(message, e); } } /** * Converts the given EventStreamJsonMessage to a JSON string * @param message The message to convert * @return A JSON string */ public String toJsonString(final EventStreamJsonMessage message) { return new String(toJson(message), StandardCharsets.UTF_8); } /** * Internal getter method can be used by subclasses of specific service models to override default Gson * @return Returns GSON context */ protected Gson getGson() { return GSON; } /** * In situations where the framework needs to do some JSON processing * without a specific service/operation in context * * @return the static Gson instance capable of processing the basics of EventStreamableJsonMessage */ public static Gson getStaticGson() { return GSON; } /** * Creates a EventStreamJsonMessage from the given application model type string and payload. * Uses this service's specific model class to create the EventStreamJsonMessage. * @param applicationModelType The application model type string * @param payload The payload * @return A EventStreamMessage */ public EventStreamJsonMessage fromJson(final String applicationModelType, byte[] payload) { final Optional<Class<? extends EventStreamJsonMessage>> clazz = getApplicationModelClass(applicationModelType); if (!clazz.isPresent()) { throw new UnmappedDataException(applicationModelType); } return fromJson(clazz.get(), payload); } /** * Creates a EventStreamJsonMessage of type T from the given application model * class and payload. * @param <T> The type to convert the result to * @param clazz The class * @param payload The payload * @return A EventStreamMessage of type T */ public <T extends EventStreamJsonMessage> T fromJson(final Class<T> clazz, byte[] payload) { try { return getGson().fromJson(new String(payload, StandardCharsets.UTF_8), clazz); } catch (Exception e) { throw new DeserializationException(payload, e); } } }
5,455
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk/eventstreamrpc/OperationModelContext.java
package software.amazon.awssdk.eventstreamrpc; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; import java.util.Optional; /** * Interface used for both client and server to dictate how to handle operations modeled by implementing this * interface. * * Smithy code generation should produce one of these per model, but we aren't going to take steps to prevent * hand construction. * * @param <RequestType> The initial-request * @param <ResponseType> The initial-response * @param <StreamingRequestType> The streaming initial-request * @param <StreamingResponseType> The streaming initial-response */ public interface OperationModelContext <RequestType extends EventStreamJsonMessage, ResponseType extends EventStreamJsonMessage, StreamingRequestType extends EventStreamJsonMessage, StreamingResponseType extends EventStreamJsonMessage> { /** * Returns the service model which can look up all/any Java error class types if an * operation throws it so the handling has a chance * * @return the service model which can look up all/any Java error class types if an * operation throws it so the handling has a chance */ EventStreamRPCServiceModel getServiceModel(); /** * Returns the canonical operation name associated with this context across any client language. * Namespace included * * Example: aws.greengrass#SubscribeToTopic * @return the canonical operation name associated with this context across any client language. */ String getOperationName(); /** * Returns the initial-request java class type * @return the initial-request java class type */ Class<RequestType> getRequestTypeClass(); /** * Returns the application model type string for the initial-request object * @return the application model type string for the initial-request object */ String getRequestApplicationModelType(); /** * Returns the initial-response java class type * @return the initial-response java class type */ Class<ResponseType> getResponseTypeClass(); /** * Returns the application model type string for the initial response object * @return the application model type string for the initial response object */ String getResponseApplicationModelType(); /** * Returns the streaming-request java class type * @return the streaming-request java class type */ Optional<Class<StreamingRequestType>> getStreamingRequestTypeClass(); /** * Returns the application model type of * @return the application model type of */ Optional<String> getStreamingRequestApplicationModelType(); /** * Returns the streaming-response java class type * * @return the streaming-response java class type */ Optional<Class<StreamingResponseType>> getStreamingResponseTypeClass(); /** * Returns the streaming response application model string * * @return the streaming response application model string */ Optional<String> getStreamingResponseApplicationModelType(); /** * Returns true if there is a streaming request or response associated with the operation * or both * @return true if there is a streaming request or response associated with the operation * or both */ default boolean isStreamingOperation() { return getStreamingRequestTypeClass().isPresent() || getStreamingResponseTypeClass().isPresent(); } }
5,456
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk/eventstreamrpc/Version.java
package software.amazon.awssdk.eventstreamrpc; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * https://semver.org/ minus the labels */ public class Version implements Comparable<Version> { private final static String PATTERN_REGEX_STRING = "^(\\d+)\\.(\\d+)\\.(\\d+)$"; /** * The Regex pattern used to parse versions from strings */ public final static Pattern PATTERN = Pattern.compile(PATTERN_REGEX_STRING); /** * Default major version number. Defaults to 0 */ public static final int MAJOR = 0; /** * Default minor version number. Defaults to 1 */ public static final int MINOR = 1; /** * Default patch version number. Defaults to 0 */ public static final int PATCH = 0; private static final Version INSTANCE = new Version(MAJOR, MINOR, PATCH); /** * @return Returns an instance of the version */ public static Version getInstance() { return INSTANCE; } private final int major; private final int minor; private final int patch; private Version(int major, int minor, int patch) { this.major = major; this.minor = minor; this.patch = patch; } /** * Returns the Version in string representation in the format: Major.Minor.Patch. * @return The Version converted to a string */ public String getVersionString() { return String.format("%d.%d.%d", MAJOR, MINOR, PATCH); } @Override public String toString() { return getVersionString(); } /** * Returns a new Version class from the given version string. * Will throw an exception if it cannot convert. * * @param versionString The version string to convert * @return The Version class created from the string */ public static Version fromString(final String versionString) { if (versionString == null) { throw new IllegalArgumentException("Cannot extract version from null string"); } final Matcher matcher = PATTERN.matcher(versionString); if (!matcher.matches()) { throw new IllegalArgumentException("Version string does not match regex: " + PATTERN_REGEX_STRING); } return new Version(Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2)), Integer.parseInt(matcher.group(3))); } @Override public int hashCode() { return Objects.hash(major, minor, patch); } @Override public boolean equals(final Object rhs) { if (rhs == null) { return false; } if (rhs instanceof Version) { return compareTo((Version)rhs) == 0; } return false; } @Override public int compareTo(final Version rhs) { if (rhs == null) { throw new IllegalArgumentException("Cannot compare to null version!"); } if (major - rhs.major == 0) { if (minor - rhs.minor == 0) { return patch - rhs.patch; } return minor - rhs.minor; } return major - rhs.major; } }
5,457
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk/eventstreamrpc
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk/eventstreamrpc/model/ValidationException.java
package software.amazon.awssdk.eventstreamrpc.model; /** * Thrown when a validation exception occurs */ public class ValidationException extends EventStreamOperationError { /** * The error code associated with a validation exception */ public static final String ERROR_CODE = "aws#ValidationException"; /** * Creates a new ValidationException with the given service name and message * @param serviceName The name of the service that caused the exception * @param message The reason for the exception */ public ValidationException(String serviceName, String message) { super(serviceName, ERROR_CODE, message); } /** * Returns the named model type. May be used for a header. * * @return the named model type */ @Override public String getApplicationModelType() { return ERROR_CODE; } }
5,458
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk/eventstreamrpc
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk/eventstreamrpc/model/EventStreamError.java
package software.amazon.awssdk.eventstreamrpc.model; import com.google.gson.JsonSyntaxException; import software.amazon.awssdk.crt.eventstream.Header; import software.amazon.awssdk.crt.eventstream.MessageType; import software.amazon.awssdk.eventstreamrpc.EventStreamRPCServiceModel; import java.util.HashMap; import java.util.List; /** * Used to hold event stream RPC error messages that are not tied to any service. * Message info comes back with a payload of JSON like: * * { "message": "..." } * * And we map that to this exception type to convey the information */ public class EventStreamError extends RuntimeException { private final List<Header> headers; private final MessageType messageType; /** * Creates a new EventStreamError * @param headers currently unusued, but likely a useful element for output * @param payload The payload to associated with the EventStreamError * @param messageType The message type to associate with the EventStreamError * @return A new EventStreamError */ public static EventStreamError create(final List<Header> headers, final byte[] payload, final MessageType messageType) { try { final HashMap<String, Object> map = EventStreamRPCServiceModel.getStaticGson().fromJson(new String(payload), HashMap.class); final String message = map.getOrDefault("message", "no message").toString(); return new EventStreamError(String.format("%s: %s", messageType.name(), message), headers, messageType); } catch (JsonSyntaxException jse) { return new EventStreamError(String.format("%s: Failed to deserialize error message as JSON(%s)", messageType.name(), jse.toString()), headers, messageType); } } /** * Creates a new EventStream error with only a message * @param message The message to associate with the EventStreamError */ public EventStreamError(String message) { super(message); this.messageType = null; this.headers = null; } /** * Creates a new EventStreamError with a message, headers, and message type * @param message The message to associate with the EventStreamError * @param headers Headers to associate with the EventStreamError * @param messageType The message type to associate with the EventStreamError */ public EventStreamError(String message, List<Header> headers, MessageType messageType) { super(message); this.messageType = messageType; this.headers = headers; } /** * Returns the headers associated with the EventStreamError * @return the headers associated with the EventStreamError */ public List<Header> getMessageHeaders() { return headers; } /** * Returns the message type associated with the EventStreamError * @return the message type associated with the EventStreamError */ public MessageType getMessageType() { return messageType; } }
5,459
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk/eventstreamrpc
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk/eventstreamrpc/model/InternalServerException.java
package software.amazon.awssdk.eventstreamrpc.model; /** * Thrown when a internal server exception occurs */ public class InternalServerException extends EventStreamOperationError { /** * The error code associated with a internal server exception */ public static final String ERROR_CODE = "aws#InternalServerException"; /** * Creates a new internal server exception from the given service name * @param serviceName The name of the service that caused the exception */ public InternalServerException(String serviceName) { super(serviceName, ERROR_CODE, "An internal server exception has occurred."); } /** * Returns the named model type. May be used for a header. * * @return - Application Model Type */ @Override public String getApplicationModelType() { return ERROR_CODE; } }
5,460
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk/eventstreamrpc
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk/eventstreamrpc/model/AccessDeniedException.java
package software.amazon.awssdk.eventstreamrpc.model; /** * Thrown when an access denied exception occurs */ public class AccessDeniedException extends EventStreamOperationError { /** * The error code associated with a access denied exception */ public static final String ERROR_CODE = "aws#AccessDenied"; /** * Message constructor may reveal what operation or resource was denied access * or the principal/authN that was rejected * * Do not overexpose reason or logic for AccessDenied. Prefer internal logging * * @param serviceName The name of the service that caused the exception * @param message The message to associate with the exception */ public AccessDeniedException(String serviceName, String message) { super(serviceName, ERROR_CODE, message); } /** * Message constructor may reveal what operation or resource was denied access * or the principal/authN that was rejected * * Do not overexpose reason or logic for AccessDenied. Prefer internal logging * * @param serviceName The name of the service that caused the exception */ public AccessDeniedException(String serviceName) { super(serviceName, ERROR_CODE, "AccessDenied"); } /** * Returns the named model type. May be used for a header. * * @return The named model type */ @Override public String getApplicationModelType() { return ERROR_CODE; } }
5,461
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk/eventstreamrpc
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk/eventstreamrpc/model/EventStreamJsonMessage.java
package software.amazon.awssdk.eventstreamrpc.model; import com.google.gson.Gson; import java.nio.charset.StandardCharsets; /** * All generated model types implement this interface, including errors. */ public interface EventStreamJsonMessage { /** * Serialize this object into a JSON payload. Does not validate object being serialized * * WARNING: implementers should not override this method. This could be an abstract class * with final implementations for serialization/deserialization. Or better yet, rework * how it works * * @param gson The GSON to convert to a JSON payload * @return The GSON converted to a JSON payload */ default byte[] toPayload(final Gson gson) { final String payloadString = gson.toJson(this); if (payloadString == null || payloadString.isEmpty() || payloadString.equals("null")) { return "{}".getBytes(StandardCharsets.UTF_8); } return payloadString.getBytes(StandardCharsets.UTF_8); } /** * Converts the given GSON and payload into a EventStreamJsonMessage * @param gson The GSON to convert * @param payload The payload to convert * @return A EventStreamJsonMessage */ default EventStreamJsonMessage fromJson(final Gson gson, byte[] payload) { final String payloadString = new String(payload, StandardCharsets.UTF_8); if (payloadString.equals("null")) { return gson.fromJson("{}", this.getClass()); } return gson.fromJson(payloadString, this.getClass()); } /** * If anything needs to be done in memory after parsing from JSON, override and perform it here */ default void postFromJson() { } /** * Returns the named model type. May be used for a header. * @return the named model type */ public String getApplicationModelType(); /** * Returns whether the EventStreamJsonMessage is void * @return True if the EventStreamJsonMessage is void */ default boolean isVoid() { return false; } }
5,462
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk/eventstreamrpc
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk/eventstreamrpc/model/UnsupportedOperationException.java
package software.amazon.awssdk.eventstreamrpc.model; /** * Thrown when an unsupported operation exception occurs */ public class UnsupportedOperationException extends EventStreamOperationError { /** * The error code associated with a unsupported operation exception */ public static final String ERROR_CODE = "aws#UnsupportedOperation"; /** * Creates a new UnsupportedOperationException from the given service and operation names * @param serviceName The name of the service that caused the exception * @param operationName The name of the operation that caused the exception */ public UnsupportedOperationException(String serviceName, String operationName) { super(serviceName, ERROR_CODE, "UnsupportedOperation: " + operationName); } /** * Returns the named model type. May be used for a header. * * @return the named model type */ @Override public String getApplicationModelType() { return ERROR_CODE; } }
5,463
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk/eventstreamrpc
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-model/src/main/java/software/amazon/awssdk/eventstreamrpc/model/EventStreamOperationError.java
package software.amazon.awssdk.eventstreamrpc.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; /** * Root error type returned by any continuation error message * * TODO: To mimic public AWS SDK clients, any exception thrown by * a given service should inherit from it's generated model * service exception. */ public abstract class EventStreamOperationError extends RuntimeException implements EventStreamJsonMessage { @SerializedName("_service") @Expose(serialize = true, deserialize = true) private final String _service; @SerializedName("_message") @Expose(serialize = true, deserialize = true) private final String _message; @SerializedName("_errorCode") @Expose(serialize = true, deserialize = true) private final String _errorCode; /** * Creates a new EventStreamOperationError from the given service name, error code, and message * @param serviceName The service that caused the error * @param errorCode The error code associated with the error * @param message The message to show alongside the error */ public EventStreamOperationError(final String serviceName, final String errorCode, final String message) { super(String.format("%s[%s]: %s", errorCode, serviceName, message)); this._service = serviceName; this._errorCode = errorCode; this._message = message; } /** * Returns the name of the service that caused the error * @return the name of the service that caused the error */ public String getService() { return _service; } /** * Likely overridden by a specific field defined in service-operation model * @return The message associated with the error */ public String getMessage() { return _message; } /** * Likely subclasses will have a more limited set of valid error codes * @return The error code associated with the error */ public String getErrorCode() { return _errorCode; } }
5,464
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/test/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/test/java/software/amazon/awssdk/eventstreamrpc/EventStreamRPCClientTests.java
package software.amazon.awssdk.eventstreamrpc; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.opentest4j.AssertionFailedError; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.Log; import software.amazon.awssdk.crt.eventstream.Header; import software.amazon.awssdk.crt.io.ClientBootstrap; import software.amazon.awssdk.crt.io.EventLoopGroup; import software.amazon.awssdk.crt.io.HostResolver; import software.amazon.awssdk.crt.io.SocketOptions; import software.amazon.awssdk.eventstreamrpc.model.AccessDeniedException; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; import software.amazon.awssdk.eventstreamrpc.test.TestAuthNZHandlers; import software.amazon.awssdk.eventstreamrpc.test.TestIpcServiceHandler; import java.util.LinkedList; import java.util.List; import java.util.Random; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Consumer; public class EventStreamRPCClientTests { private static final Random RANDOM = new Random(); //default instantiation uses time public static int randomPort() { return RANDOM.nextInt(65535-1024) + 1024; } static { Log.initLoggingToFile(Log.LogLevel.Trace, "crt-EventStreamRPCClientTests.log"); } @Test public void testConnectionEstablished() { final int port = randomPort(); //below class is generated and just gets instantiated for what it is final TestIpcServiceHandler service = new TestIpcServiceHandler(false, request -> request, EventStreamJsonMessage.class, EventStreamJsonMessage.class, EventStreamJsonMessage.class, EventStreamJsonMessage.class); //handlers aren't relevant since no request will be made service.setAuthenticationHandler(TestAuthNZHandlers.getAuthNHandler()); service.setAuthorizationHandler(TestAuthNZHandlers.getAuthZHandler()); final CompletableFuture<Void> disconnectFuture = new CompletableFuture<>(); final CompletableFuture<Void> connectedFuture = new CompletableFuture<>(); try(final EventLoopGroup elGroup = new EventLoopGroup(1); final HostResolver hostResolver = new HostResolver(elGroup, 64); final ClientBootstrap clientBootstrap = new ClientBootstrap(elGroup, hostResolver); SocketOptions socketOptions = new SocketOptions()) { socketOptions.connectTimeoutMs = 3000; socketOptions.domain = SocketOptions.SocketDomain.IPv4; socketOptions.type = SocketOptions.SocketType.STREAM; try (final RpcServer ipcServer = new RpcServer(elGroup, socketOptions, null, "127.0.0.1", port, service)) { ipcServer.runServer(); final EventStreamRPCConnectionConfig config = new EventStreamRPCConnectionConfig( clientBootstrap, elGroup, socketOptions, null, "127.0.0.1", port, () -> { final List<Header> headers = new LinkedList<>(); headers.add(Header.createHeader("client-name", "accepted.foo")); return CompletableFuture.completedFuture(new MessageAmendInfo(headers, null)); } ); final EventStreamRPCConnection connection = new EventStreamRPCConnection(config); final EventStreamRPCConnection.LifecycleHandler lifecycleHandler = new EventStreamRPCConnection.LifecycleHandler() { @Override public void onConnect() { connectedFuture.complete(null); } @Override public void onDisconnect(int errorCode) { disconnectFuture.complete(null); } @Override public boolean onError(Throwable t) { if (!connectedFuture.isDone()) { connectedFuture.completeExceptionally(t); } if (!disconnectFuture.isDone()) { disconnectFuture.completeExceptionally(t); } return true; } }; final CompletableFuture<Void> initialConnect = connection.connect(lifecycleHandler); //highly likely above line is establishing connection Assertions.assertThrows(IllegalStateException.class, () -> connection.connect(lifecycleHandler)); connectedFuture.get(2, TimeUnit.SECONDS); Assertions.assertTrue(initialConnect.isDone() && !initialConnect.isCompletedExceptionally()); //connection is fully established Assertions.assertThrows(IllegalStateException.class, () -> connection.connect(lifecycleHandler)); connection.disconnect(); } catch (ExecutionException | TimeoutException | InterruptedException e) { throw new RuntimeException(e); } finally { try { disconnectFuture.get(5, TimeUnit.SECONDS); } catch (ExecutionException | TimeoutException | InterruptedException e) { throw new RuntimeException(e); } } } CrtResource.waitForNoResources(); } @Test public void testClientClosedThrowsInitialFutureException() { final int port = randomPort(); //below class is generated and just gets instantiated for what it is final TestIpcServiceHandler service = new TestIpcServiceHandler(false, request -> request, EventStreamJsonMessage.class, EventStreamJsonMessage.class, EventStreamJsonMessage.class, EventStreamJsonMessage.class); //handlers aren't relevant since no request will be made service.setAuthenticationHandler(TestAuthNZHandlers.getAuthNHandler()); service.setAuthorizationHandler(TestAuthNZHandlers.getAuthZHandler()); try(final EventLoopGroup elGroup = new EventLoopGroup(1); final HostResolver hostResolver = new HostResolver(elGroup, 64); final ClientBootstrap clientBootstrap = new ClientBootstrap(elGroup, hostResolver); SocketOptions socketOptions = new SocketOptions()) { socketOptions.connectTimeoutMs = 3000; socketOptions.domain = SocketOptions.SocketDomain.IPv4; socketOptions.type = SocketOptions.SocketType.STREAM; try (final RpcServer ipcServer = new RpcServer(elGroup, socketOptions, null, "127.0.0.1", port, service)) { ipcServer.runServer(); final EventStreamRPCConnectionConfig config = new EventStreamRPCConnectionConfig( clientBootstrap, elGroup, socketOptions, null, "127.0.0.1", port, () -> { final List<Header> headers = new LinkedList<>(); headers.add(Header.createHeader("client-name", "accepted.foo")); return CompletableFuture.completedFuture(new MessageAmendInfo(headers, null)); } ); final EventStreamRPCConnection connection = new EventStreamRPCConnection(config); final CompletableFuture<Void> initialConnect = connection.connect(new EventStreamRPCConnection.LifecycleHandler() { @Override public void onConnect() { } @Override public void onDisconnect(int errorCode) { } @Override public boolean onError(Throwable t) { return true; } }); connection.disconnect(); try { initialConnect.get(15, TimeUnit.SECONDS); } catch (ExecutionException e) { Assertions.assertEquals(EventStreamClosedException.class, e.getCause().getClass()); } } } catch (InterruptedException | TimeoutException e) { Assertions.fail(e); } CrtResource.waitForNoResources(); } @Test public void testConnectionVersionMismatch() { final int port = randomPort(); //below class is generated and just gets instantiated for what it is final TestIpcServiceHandler service = new TestIpcServiceHandler(false, request -> request, EventStreamJsonMessage.class, EventStreamJsonMessage.class, EventStreamJsonMessage.class, EventStreamJsonMessage.class); //handlers aren't relevant since no request will be made service.setAuthenticationHandler(TestAuthNZHandlers.getAuthNHandler()); service.setAuthorizationHandler(TestAuthNZHandlers.getAuthZHandler()); try (final EventLoopGroup elGroup = new EventLoopGroup(1); final HostResolver hostResolver = new HostResolver(elGroup, 64); final ClientBootstrap clientBootstrap = new ClientBootstrap(elGroup, hostResolver); SocketOptions socketOptions = new SocketOptions()) { socketOptions.connectTimeoutMs = 3000; socketOptions.domain = SocketOptions.SocketDomain.IPv4; socketOptions.type = SocketOptions.SocketType.STREAM; try (final RpcServer ipcServer = new RpcServer(elGroup, socketOptions, null, "127.0.0.1", port, service)) { ipcServer.runServer(); final EventStreamRPCConnectionConfig config = new EventStreamRPCConnectionConfig( clientBootstrap, elGroup, socketOptions, null, "127.0.0.1", port, () -> { final List<Header> headers = new LinkedList<>(); headers.add(Header.createHeader("client-name", "accepted.foo")); return CompletableFuture.completedFuture(new MessageAmendInfo(headers, null)); } ); try (final EventStreamRPCConnection connection = new EventStreamRPCConnection(config) { @Override protected String getVersionString() { return "19.19.19"; } }) { final CompletableFuture<Throwable> futureAccessDenied = new CompletableFuture<>(); final CompletableFuture<Void> initialConnect = connection.connect(new EventStreamRPCConnection.LifecycleHandler() { @Override public void onConnect() { futureAccessDenied.completeExceptionally(new AssertionFailedError("onConnect lifecycle handler method should not be called!")); } @Override public void onDisconnect(int errorCode) { futureAccessDenied.completeExceptionally(new AssertionFailedError("onDisconnect lifecycle handler method should not be called!")); } @Override public boolean onError(Throwable t) { futureAccessDenied.complete(t); return true; } }); try { initialConnect.get(5, TimeUnit.SECONDS); } catch (ExecutionException e) { Assertions.assertEquals(AccessDeniedException.class, e.getCause().getClass()); } } } } catch (InterruptedException | TimeoutException e) { Assertions.fail(e); } CrtResource.waitForNoResources(); } @Test public void testConnectionAccessDenied() { final int port = randomPort(); //below class is generated and just gets instantiated for what it is final TestIpcServiceHandler service = new TestIpcServiceHandler(false, request -> request, EventStreamJsonMessage.class, EventStreamJsonMessage.class, EventStreamJsonMessage.class, EventStreamJsonMessage.class); //handlers aren't relevant since no request will be made service.setAuthenticationHandler(TestAuthNZHandlers.getAuthNHandler()); service.setAuthorizationHandler(TestAuthNZHandlers.getAuthZHandler()); final Semaphore semaphore = new Semaphore(1); try(final EventLoopGroup elGroup = new EventLoopGroup(1); final HostResolver hostResolver = new HostResolver(elGroup, 64); final ClientBootstrap clientBootstrap = new ClientBootstrap(elGroup, hostResolver); SocketOptions socketOptions = new SocketOptions()) { socketOptions.connectTimeoutMs = 3000; socketOptions.domain = SocketOptions.SocketDomain.IPv4; socketOptions.type = SocketOptions.SocketType.STREAM; try (final RpcServer ipcServer = new RpcServer(elGroup, socketOptions, null, "127.0.0.1", port, service)) { ipcServer.runServer(); semaphore.acquire(); final EventStreamRPCConnectionConfig config = new EventStreamRPCConnectionConfig( clientBootstrap, elGroup, socketOptions, null, "127.0.0.1", port, () -> { final List<Header> headers = new LinkedList<>(); headers.add(Header.createHeader("client-name", "rejected.foo")); return CompletableFuture.completedFuture(new MessageAmendInfo(headers, null)); } ); try (final EventStreamRPCConnection connection = new EventStreamRPCConnection(config)) { final CompletableFuture<Void> initialConnect = connection.connect(new EventStreamRPCConnection.LifecycleHandler() { @Override public void onConnect() { Assertions.fail("Full connection expected to be rejected"); semaphore.release(); } @Override public void onDisconnect(int errorCode) { Assertions.fail("Disconnect callback should not be invoked on access denied"); } @Override public boolean onError(Throwable t) { Assertions.assertEquals(t.getClass(), AccessDeniedException.class, "Expected access denied exception type!"); semaphore.release(); return false; } }); semaphore.acquire(); Assertions.assertTrue(initialConnect.isDone()); try { initialConnect.get(); } catch (ExecutionException e) { Assertions.assertTrue(e.getCause() instanceof AccessDeniedException); } } } } catch (InterruptedException e) { throw new RuntimeException(e); } CrtResource.waitForNoResources(); } /** * Runs a dummy service on a random port and creates a connection for it so a test can do whatever on the connection. * Assumes the particular operation invocations don't matter. * @param lifecycleHandler * @param testCode */ public static void runDummyService(EventStreamRPCConnection.LifecycleHandler lifecycleHandler, Consumer<EventStreamRPCConnection> testCode) { final int port = randomPort(); final TestIpcServiceHandler service = new TestIpcServiceHandler(false, request -> request, EventStreamJsonMessage.class, EventStreamJsonMessage.class, EventStreamJsonMessage.class, EventStreamJsonMessage.class); service.setAuthenticationHandler(TestAuthNZHandlers.getAuthNHandler()); service.setAuthorizationHandler(TestAuthNZHandlers.getAuthZHandler()); try(final EventLoopGroup elGroup = new EventLoopGroup(1); final HostResolver hostResolver = new HostResolver(elGroup, 64); final ClientBootstrap clientBootstrap = new ClientBootstrap(elGroup, hostResolver); SocketOptions socketOptions = new SocketOptions()) { socketOptions.connectTimeoutMs = 3000; socketOptions.domain = SocketOptions.SocketDomain.IPv4; socketOptions.type = SocketOptions.SocketType.STREAM; try (final RpcServer ipcServer = new RpcServer(elGroup, socketOptions, null, "127.0.0.1", port, service)) { ipcServer.runServer(); final EventStreamRPCConnectionConfig config = new EventStreamRPCConnectionConfig( clientBootstrap, elGroup, socketOptions, null, "127.0.0.1", port, () -> { final List<Header> headers = new LinkedList<>(); headers.add(Header.createHeader("client-name", "accepted.foo")); return CompletableFuture.completedFuture(new MessageAmendInfo(headers, null)); } ); final EventStreamRPCConnection connection = new EventStreamRPCConnection(config); final CompletableFuture<Void> initialConnect = connection.connect(lifecycleHandler); initialConnect.get(2, TimeUnit.SECONDS); testCode.accept(connection); } } catch (ExecutionException | TimeoutException | InterruptedException e) { Assertions.fail(e); } } }
5,465
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/test/java/software/amazon/awssdk/eventstreamrpc
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/test/java/software/amazon/awssdk/eventstreamrpc/test/TestAuthNZHandlers.java
package software.amazon.awssdk.eventstreamrpc.test; import software.amazon.awssdk.crt.eventstream.Header; import software.amazon.awssdk.crt.eventstream.HeaderType; import software.amazon.awssdk.eventstreamrpc.AuthenticationData; import software.amazon.awssdk.eventstreamrpc.AuthenticationHandler; import software.amazon.awssdk.eventstreamrpc.Authorization; import software.amazon.awssdk.eventstreamrpc.AuthorizationHandler; import software.amazon.awssdk.eventstreamrpc.MessageAmendInfo; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; /** * Example */ public class TestAuthNZHandlers { public static CompletableFuture<MessageAmendInfo> getClientAuth(String clientName) { final List<Header> headers = new ArrayList<>(1); headers.add(Header.createHeader("client-name", clientName)); return CompletableFuture.completedFuture(new MessageAmendInfo(headers, null)); } public static class ClientNameAuthenicationData implements AuthenticationData { private static String clientName; public ClientNameAuthenicationData(String clientName) { this.clientName = clientName; } /** * Return a human readable string for who the identity of the client/caller is. This * string must be appropriate for audit logs and enable tracing specific callers/clients * to relevant decision and operations executed * * @return */ @Override public String getIdentityLabel() { return clientName; } } public static AuthenticationHandler getAuthNHandler() { /** * AuthN handler is privy to looking into the connect message and extracting whatever it needs/wants * from the headers and/or payload and populating whatever/however it wants into the AuthenticationData * type it decides is appropriate. The only restriction is that the associated Authorization handler * should understand the authentication produced. */ return (List<Header> headers, byte[] bytes) -> { final Optional<Header> nameHeader = headers.stream() .filter(header -> header.getName().equals("client-name")).findFirst(); if (nameHeader.isPresent() && nameHeader.get().getHeaderType().equals(HeaderType.String)) { return new ClientNameAuthenicationData(nameHeader.get().getValueAsString()); } throw new RuntimeException("Authentication failed to find client-name string header!"); }; } public static AuthorizationHandler getAuthZHandler() { return (AuthenticationData authN) -> { try { //framework checks for null authN so this shouldn't happen if (authN == null) { throw new RuntimeException("Null AuthN data passed in!"); } //check if the authN data type matches is a good idea, and necessary if there are other fields //to open/inspect if (authN instanceof ClientNameAuthenicationData) { final ClientNameAuthenicationData data = (ClientNameAuthenicationData) authN; //WARNING!!! this logic is for demonstration purposes final String identityLabel = data.getIdentityLabel(); return identityLabel.startsWith("accepted.") ? Authorization.ACCEPT : Authorization.REJECT; } //good idea to log reasons for rejection with the authentication label so testers/users can understand System.err.println("AuthN data type is not expected object type!"); return Authorization.REJECT; } catch (Exception e) { return Authorization.REJECT; } }; } }
5,466
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/test/java/software/amazon/awssdk/eventstreamrpc
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/test/java/software/amazon/awssdk/eventstreamrpc/test/TestIpcServiceHandler.java
package software.amazon.awssdk.eventstreamrpc.test; import software.amazon.awssdk.crt.eventstream.ServerConnectionContinuationHandler; import software.amazon.awssdk.eventstreamrpc.EventStreamRPCServiceHandler; import software.amazon.awssdk.eventstreamrpc.EventStreamRPCServiceModel; import software.amazon.awssdk.eventstreamrpc.OperationContinuationHandler; import software.amazon.awssdk.eventstreamrpc.OperationContinuationHandlerContext; import software.amazon.awssdk.eventstreamrpc.OperationModelContext; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; import java.util.AbstractMap; import java.util.Collection; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.Optional; import java.util.Queue; import java.util.Set; import java.util.function.Function; /** * Test server handler operates on all operations and simply stores what it recieves in a way that's publicly * retrievable for verifiable IO behavior */ public class TestIpcServiceHandler extends EventStreamRPCServiceHandler { private final Queue<Map.Entry<String, TestOperationContinuationHandler>> continuationHandlerQueue; private boolean streamClosed; private final boolean isStreaming; private Function<EventStreamJsonMessage, EventStreamJsonMessage> requestHandler; private Class requestClass; private Class responseClass; private Class streamingRequestClass; private Class streamingResponseClass; private EventStreamRPCServiceModel serviceModel; public TestIpcServiceHandler(boolean isStreaming, Function<EventStreamJsonMessage, EventStreamJsonMessage> requestHandler, Class requestClass, Class responseClass, Class streamingRequestClass, Class streamingResponseClass) { this.isStreaming = isStreaming; this.requestHandler = requestHandler; this.requestClass = requestClass; this.responseClass = responseClass; this.streamingRequestClass = streamingRequestClass; this.streamingResponseClass = streamingResponseClass; this.continuationHandlerQueue = new LinkedList<>(); this.serviceModel = new EventStreamRPCServiceModel() { @Override public String getServiceName() { return "TestIpcService"; } @Override public Collection<String> getAllOperations() { return new HashSet<>(); } @Override protected Optional<Class<? extends EventStreamJsonMessage>> getServiceClassType(String applicationModelType) { return Optional.empty(); } @Override public OperationModelContext getOperationModelContext(String operationName) { return new OperationModelContext() { @Override public EventStreamRPCServiceModel getServiceModel() { return serviceModel; } @Override public String getOperationName() { return operationName; } @Override public Class getRequestTypeClass() { return requestClass; } @Override public String getRequestApplicationModelType() { return "aws.greengrass#" + requestClass.getSimpleName(); } @Override public Class getResponseTypeClass() { return responseClass; } @Override public String getResponseApplicationModelType() { return "aws.greengrass#" + responseClass.getSimpleName(); } @Override public Optional<Class> getStreamingRequestTypeClass() { return Optional.of(streamingRequestClass); } @Override public Optional<String> getStreamingRequestApplicationModelType() { return Optional.of("aws.greengrass#" + streamingRequestClass.getSimpleName()); } @Override public Optional<Class> getStreamingResponseTypeClass() { return Optional.of(streamingResponseClass); } @Override public Optional<String> getStreamingResponseApplicationModelType() { return Optional.of("aws.greengrass#" + streamingResponseClass.getSimpleName()); } @Override public boolean isStreamingOperation() { return isStreaming; } }; } }; } @Override protected EventStreamRPCServiceModel getServiceModel() { return serviceModel; } /** * Probably only useful for logging * * @return Returns the service name for the set of RPC operations */ @Override public String getServiceName() { return "TestIpcServiceHandler"; } /** * Exposes some things so tests can verify */ public static abstract class TestOperationContinuationHandler extends OperationContinuationHandler { public TestOperationContinuationHandler(OperationContinuationHandlerContext context) { super(context); } public OperationContinuationHandlerContext getContextForTest() { return getContext(); } } @Override public Function<OperationContinuationHandlerContext, ? extends ServerConnectionContinuationHandler> getOperationHandler(final String operationName) { final EventStreamRPCServiceModel svcModel = this.serviceModel; System.out.println("Operation handler retrieved for operation name: " + operationName); return (context) -> { final TestOperationContinuationHandler handler = new TestOperationContinuationHandler(context) { @Override public OperationModelContext getOperationModelContext() { return svcModel.getOperationModelContext(operationName); } @Override protected void onStreamClosed() { streamClosed = true; } @Override public EventStreamJsonMessage handleRequest(EventStreamJsonMessage request) { System.out.println("Handling request..."); return requestHandler.apply(request); } @Override public void handleStreamEvent(EventStreamJsonMessage streamRequestEvent) { System.out.println("Handling request stream event..."); } }; continuationHandlerQueue.offer(new AbstractMap.SimpleImmutableEntry<>(operationName, handler)); return handler; }; } @Override public Set<String> getAllOperations() { //return no operations, IpcServer doesn't actually care about that //only that validating all operations are set before start up return new HashSet<>(); } @Override public boolean hasHandlerForOperation(String operation) { return true; } public Map.Entry<String, TestOperationContinuationHandler> popHandler() { return continuationHandlerQueue.poll(); } }
5,467
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/test/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/test/java/software/amazon/awssdk/awstest/CauseServiceErrorResponseHandler.java
package software.amazon.awssdk.awstest; import java.lang.Override; import java.lang.Void; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.awstest.model.CauseServiceErrorResponse; import software.amazon.awssdk.eventstreamrpc.OperationResponse; import software.amazon.awssdk.eventstreamrpc.StreamResponse; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public final class CauseServiceErrorResponseHandler implements StreamResponse<CauseServiceErrorResponse, EventStreamJsonMessage> { private final OperationResponse<CauseServiceErrorResponse, EventStreamJsonMessage> operationResponse; public CauseServiceErrorResponseHandler( final OperationResponse<CauseServiceErrorResponse, EventStreamJsonMessage> operationResponse) { this.operationResponse = operationResponse; } @Override public CompletableFuture<Void> getRequestFlushFuture() { return operationResponse.getRequestFlushFuture(); } @Override public CompletableFuture<CauseServiceErrorResponse> getResponse() { return operationResponse.getResponse(); } @Override public CompletableFuture<Void> sendStreamEvent(final EventStreamJsonMessage event) { return operationResponse.sendStreamEvent(event); } @Override public CompletableFuture<Void> closeStream() { return operationResponse.closeStream(); } @Override public boolean isClosed() { return operationResponse.isClosed(); } }
5,468
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/test/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/test/java/software/amazon/awssdk/awstest/GetAllCustomersResponseHandler.java
package software.amazon.awssdk.awstest; import java.lang.Override; import java.lang.Void; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.awstest.model.GetAllCustomersResponse; import software.amazon.awssdk.eventstreamrpc.OperationResponse; import software.amazon.awssdk.eventstreamrpc.StreamResponse; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public final class GetAllCustomersResponseHandler implements StreamResponse<GetAllCustomersResponse, EventStreamJsonMessage> { private final OperationResponse<GetAllCustomersResponse, EventStreamJsonMessage> operationResponse; public GetAllCustomersResponseHandler( final OperationResponse<GetAllCustomersResponse, EventStreamJsonMessage> operationResponse) { this.operationResponse = operationResponse; } @Override public CompletableFuture<Void> getRequestFlushFuture() { return operationResponse.getRequestFlushFuture(); } @Override public CompletableFuture<GetAllCustomersResponse> getResponse() { return operationResponse.getResponse(); } @Override public CompletableFuture<Void> sendStreamEvent(final EventStreamJsonMessage event) { return operationResponse.sendStreamEvent(event); } @Override public CompletableFuture<Void> closeStream() { return operationResponse.closeStream(); } @Override public boolean isClosed() { return operationResponse.isClosed(); } }
5,469
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/test/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/test/java/software/amazon/awssdk/awstest/EchoStreamMessagesResponseHandler.java
package software.amazon.awssdk.awstest; import java.lang.Override; import java.lang.Void; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.awstest.model.EchoStreamingMessage; import software.amazon.awssdk.awstest.model.EchoStreamingResponse; import software.amazon.awssdk.eventstreamrpc.OperationResponse; import software.amazon.awssdk.eventstreamrpc.StreamResponse; public final class EchoStreamMessagesResponseHandler implements StreamResponse<EchoStreamingResponse, EchoStreamingMessage> { private final OperationResponse<EchoStreamingResponse, EchoStreamingMessage> operationResponse; public EchoStreamMessagesResponseHandler( final OperationResponse<EchoStreamingResponse, EchoStreamingMessage> operationResponse) { this.operationResponse = operationResponse; } @Override public CompletableFuture<Void> getRequestFlushFuture() { return operationResponse.getRequestFlushFuture(); } @Override public CompletableFuture<EchoStreamingResponse> getResponse() { return operationResponse.getResponse(); } @Override public CompletableFuture<Void> sendStreamEvent(final EchoStreamingMessage event) { return operationResponse.sendStreamEvent(event); } @Override public CompletableFuture<Void> closeStream() { return operationResponse.closeStream(); } @Override public boolean isClosed() { return operationResponse.isClosed(); } }
5,470
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/test/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/test/java/software/amazon/awssdk/awstest/CauseStreamServiceToErrorResponseHandler.java
package software.amazon.awssdk.awstest; import java.lang.Override; import java.lang.Void; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.awstest.model.EchoStreamingMessage; import software.amazon.awssdk.awstest.model.EchoStreamingResponse; import software.amazon.awssdk.eventstreamrpc.OperationResponse; import software.amazon.awssdk.eventstreamrpc.StreamResponse; public final class CauseStreamServiceToErrorResponseHandler implements StreamResponse<EchoStreamingResponse, EchoStreamingMessage> { private final OperationResponse<EchoStreamingResponse, EchoStreamingMessage> operationResponse; public CauseStreamServiceToErrorResponseHandler( final OperationResponse<EchoStreamingResponse, EchoStreamingMessage> operationResponse) { this.operationResponse = operationResponse; } @Override public CompletableFuture<Void> getRequestFlushFuture() { return operationResponse.getRequestFlushFuture(); } @Override public CompletableFuture<EchoStreamingResponse> getResponse() { return operationResponse.getResponse(); } @Override public CompletableFuture<Void> sendStreamEvent(final EchoStreamingMessage event) { return operationResponse.sendStreamEvent(event); } @Override public CompletableFuture<Void> closeStream() { return operationResponse.closeStream(); } @Override public boolean isClosed() { return operationResponse.isClosed(); } }
5,471
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/test/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/test/java/software/amazon/awssdk/awstest/GetAllProductsResponseHandler.java
package software.amazon.awssdk.awstest; import java.lang.Override; import java.lang.Void; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.awstest.model.GetAllProductsResponse; import software.amazon.awssdk.eventstreamrpc.OperationResponse; import software.amazon.awssdk.eventstreamrpc.StreamResponse; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public final class GetAllProductsResponseHandler implements StreamResponse<GetAllProductsResponse, EventStreamJsonMessage> { private final OperationResponse<GetAllProductsResponse, EventStreamJsonMessage> operationResponse; public GetAllProductsResponseHandler( final OperationResponse<GetAllProductsResponse, EventStreamJsonMessage> operationResponse) { this.operationResponse = operationResponse; } @Override public CompletableFuture<Void> getRequestFlushFuture() { return operationResponse.getRequestFlushFuture(); } @Override public CompletableFuture<GetAllProductsResponse> getResponse() { return operationResponse.getResponse(); } @Override public CompletableFuture<Void> sendStreamEvent(final EventStreamJsonMessage event) { return operationResponse.sendStreamEvent(event); } @Override public CompletableFuture<Void> closeStream() { return operationResponse.closeStream(); } @Override public boolean isClosed() { return operationResponse.isClosed(); } }
5,472
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/test/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/test/java/software/amazon/awssdk/awstest/EchoTestRPCClient.java
package software.amazon.awssdk.awstest; import java.lang.Override; import java.util.Optional; import software.amazon.awssdk.awstest.model.CauseServiceErrorRequest; import software.amazon.awssdk.awstest.model.EchoMessageRequest; import software.amazon.awssdk.awstest.model.EchoStreamingMessage; import software.amazon.awssdk.awstest.model.EchoStreamingRequest; import software.amazon.awssdk.awstest.model.GetAllCustomersRequest; import software.amazon.awssdk.awstest.model.GetAllProductsRequest; import software.amazon.awssdk.eventstreamrpc.EventStreamRPCClient; import software.amazon.awssdk.eventstreamrpc.EventStreamRPCConnection; import software.amazon.awssdk.eventstreamrpc.StreamResponseHandler; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public class EchoTestRPCClient extends EventStreamRPCClient implements EchoTestRPC { public EchoTestRPCClient(final EventStreamRPCConnection connection) { super(connection); } @Override public CauseServiceErrorResponseHandler causeServiceError(final CauseServiceErrorRequest request, final Optional<StreamResponseHandler<EventStreamJsonMessage>> streamResponseHandler) { final CauseServiceErrorOperationContext operationContext = EchoTestRPCServiceModel.getCauseServiceErrorModelContext(); return new CauseServiceErrorResponseHandler(doOperationInvoke(operationContext, request, streamResponseHandler)); } @Override public CauseStreamServiceToErrorResponseHandler causeStreamServiceToError( final EchoStreamingRequest request, final Optional<StreamResponseHandler<EchoStreamingMessage>> streamResponseHandler) { final CauseStreamServiceToErrorOperationContext operationContext = EchoTestRPCServiceModel.getCauseStreamServiceToErrorModelContext(); return new CauseStreamServiceToErrorResponseHandler(doOperationInvoke(operationContext, request, streamResponseHandler)); } @Override public EchoMessageResponseHandler echoMessage(final EchoMessageRequest request, final Optional<StreamResponseHandler<EventStreamJsonMessage>> streamResponseHandler) { final EchoMessageOperationContext operationContext = EchoTestRPCServiceModel.getEchoMessageModelContext(); return new EchoMessageResponseHandler(doOperationInvoke(operationContext, request, streamResponseHandler)); } @Override public EchoStreamMessagesResponseHandler echoStreamMessages(final EchoStreamingRequest request, final Optional<StreamResponseHandler<EchoStreamingMessage>> streamResponseHandler) { final EchoStreamMessagesOperationContext operationContext = EchoTestRPCServiceModel.getEchoStreamMessagesModelContext(); return new EchoStreamMessagesResponseHandler(doOperationInvoke(operationContext, request, streamResponseHandler)); } @Override public GetAllCustomersResponseHandler getAllCustomers(final GetAllCustomersRequest request, final Optional<StreamResponseHandler<EventStreamJsonMessage>> streamResponseHandler) { final GetAllCustomersOperationContext operationContext = EchoTestRPCServiceModel.getGetAllCustomersModelContext(); return new GetAllCustomersResponseHandler(doOperationInvoke(operationContext, request, streamResponseHandler)); } @Override public GetAllProductsResponseHandler getAllProducts(final GetAllProductsRequest request, final Optional<StreamResponseHandler<EventStreamJsonMessage>> streamResponseHandler) { final GetAllProductsOperationContext operationContext = EchoTestRPCServiceModel.getGetAllProductsModelContext(); return new GetAllProductsResponseHandler(doOperationInvoke(operationContext, request, streamResponseHandler)); } }
5,473
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/test/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/test/java/software/amazon/awssdk/awstest/EchoMessageResponseHandler.java
package software.amazon.awssdk.awstest; import java.lang.Override; import java.lang.Void; import java.util.concurrent.CompletableFuture; import software.amazon.awssdk.awstest.model.EchoMessageResponse; import software.amazon.awssdk.eventstreamrpc.OperationResponse; import software.amazon.awssdk.eventstreamrpc.StreamResponse; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public final class EchoMessageResponseHandler implements StreamResponse<EchoMessageResponse, EventStreamJsonMessage> { private final OperationResponse<EchoMessageResponse, EventStreamJsonMessage> operationResponse; public EchoMessageResponseHandler( final OperationResponse<EchoMessageResponse, EventStreamJsonMessage> operationResponse) { this.operationResponse = operationResponse; } @Override public CompletableFuture<Void> getRequestFlushFuture() { return operationResponse.getRequestFlushFuture(); } @Override public CompletableFuture<EchoMessageResponse> getResponse() { return operationResponse.getResponse(); } @Override public CompletableFuture<Void> sendStreamEvent(final EventStreamJsonMessage event) { return operationResponse.sendStreamEvent(event); } @Override public CompletableFuture<Void> closeStream() { return operationResponse.closeStream(); } @Override public boolean isClosed() { return operationResponse.isClosed(); } }
5,474
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/test/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/test/java/software/amazon/awssdk/awstest/EchoTestRPC.java
package software.amazon.awssdk.awstest; import java.util.Optional; import software.amazon.awssdk.awstest.model.CauseServiceErrorRequest; import software.amazon.awssdk.awstest.model.EchoMessageRequest; import software.amazon.awssdk.awstest.model.EchoStreamingMessage; import software.amazon.awssdk.awstest.model.EchoStreamingRequest; import software.amazon.awssdk.awstest.model.GetAllCustomersRequest; import software.amazon.awssdk.awstest.model.GetAllProductsRequest; import software.amazon.awssdk.eventstreamrpc.StreamResponseHandler; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; public interface EchoTestRPC { CauseServiceErrorResponseHandler causeServiceError(final CauseServiceErrorRequest request, final Optional<StreamResponseHandler<EventStreamJsonMessage>> streamResponseHandler); CauseStreamServiceToErrorResponseHandler causeStreamServiceToError( final EchoStreamingRequest request, final Optional<StreamResponseHandler<EchoStreamingMessage>> streamResponseHandler); EchoMessageResponseHandler echoMessage(final EchoMessageRequest request, final Optional<StreamResponseHandler<EventStreamJsonMessage>> streamResponseHandler); EchoStreamMessagesResponseHandler echoStreamMessages(final EchoStreamingRequest request, final Optional<StreamResponseHandler<EchoStreamingMessage>> streamResponseHandler); GetAllCustomersResponseHandler getAllCustomers(final GetAllCustomersRequest request, final Optional<StreamResponseHandler<EventStreamJsonMessage>> streamResponseHandler); GetAllProductsResponseHandler getAllProducts(final GetAllProductsRequest request, final Optional<StreamResponseHandler<EventStreamJsonMessage>> streamResponseHandler); }
5,475
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/main/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/main/java/software/amazon/awssdk/eventstreamrpc/StreamResponseHandler.java
package software.amazon.awssdk.eventstreamrpc; /** * Operation response handler is needed to invoke an operation that has a streaming * response element to it. * * @param <StreamEventType> The stream event type */ public interface StreamResponseHandler<StreamEventType> { /** * Called when there is a stream event to process * @param streamEvent The stream event to process */ void onStreamEvent(final StreamEventType streamEvent); /** * Called when there's an error in the stream. Return value of this function * suggests whether or not the client handling will keep the stream open * or close it. * * There are conditions when onStreamError() may be triggered but the client handling will * close the connection anyways. * * @param error The error that occurred * @return true if the stream should be closed on this error, false if stream should remain open */ boolean onStreamError(final Throwable error); /** * Called when stream is closed */ void onStreamClosed(); }
5,476
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/main/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/main/java/software/amazon/awssdk/eventstreamrpc/GreengrassEventStreamConnectMessage.java
package software.amazon.awssdk.eventstreamrpc; /** * A Greengrass EventStream connection message */ public class GreengrassEventStreamConnectMessage { private String authToken; /** * Sets the authorization token in the connect message * @param authToken the authorization token to use */ public void setAuthToken(String authToken) { this.authToken = authToken; } /** * Returns the authorization token in the connect message * @return authorization token in the connect message */ public String getAuthToken() { return this.authToken; } }
5,477
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/main/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/main/java/software/amazon/awssdk/eventstreamrpc/GreengrassConnectMessageSupplier.java
package software.amazon.awssdk.eventstreamrpc; import com.google.gson.Gson; import software.amazon.awssdk.crt.eventstream.Header; import java.nio.charset.StandardCharsets; import java.util.LinkedList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; /** * The connect message supplier for Greengrass */ public class GreengrassConnectMessageSupplier { /** * Returns a new connect message supplier using the given token * @param authToken The auth token to use * @return A new connect message supplier */ public static Supplier<CompletableFuture<MessageAmendInfo>> connectMessageSupplier(String authToken) { return () -> { final List<Header> headers = new LinkedList<>(); GreengrassEventStreamConnectMessage connectMessage = new GreengrassEventStreamConnectMessage(); connectMessage.setAuthToken(authToken); String payload = new Gson().toJson(connectMessage); return CompletableFuture.completedFuture(new MessageAmendInfo(headers, payload.getBytes(StandardCharsets.UTF_8))); }; } }
5,478
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/main/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/main/java/software/amazon/awssdk/eventstreamrpc/EventStreamRPCConnection.java
package software.amazon.awssdk.eventstreamrpc; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.CrtRuntimeException; import software.amazon.awssdk.crt.eventstream.ClientConnection; import software.amazon.awssdk.crt.eventstream.ClientConnectionContinuation; import software.amazon.awssdk.crt.eventstream.ClientConnectionContinuationHandler; import software.amazon.awssdk.crt.eventstream.ClientConnectionHandler; import software.amazon.awssdk.crt.eventstream.Header; import software.amazon.awssdk.crt.eventstream.MessageFlags; import software.amazon.awssdk.crt.eventstream.MessageType; import software.amazon.awssdk.eventstreamrpc.model.AccessDeniedException; import software.amazon.awssdk.eventstreamrpc.model.EventStreamError; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.logging.Logger; import java.util.stream.Collectors; /** * A connection for an EventStreamRPC client */ public class EventStreamRPCConnection implements AutoCloseable { /** * Class containing the possible connection states of the EventStreamRPCConnection */ protected static class ConnectionState { enum Phase { DISCONNECTED, CONNECTING_SOCKET, WAITING_CONNACK, CONNECTED, CLOSING }; Phase connectionPhase; ClientConnection connection; Throwable closeReason; boolean onConnectCalled; protected ConnectionState(Phase phase, ClientConnection connection) { this.connectionPhase = phase; this.connection = connection; this.closeReason = null; this.onConnectCalled = false; } }; private static final Logger LOGGER = Logger.getLogger(EventStreamRPCConnection.class.getName()); private final EventStreamRPCConnectionConfig config; /** * The connection state of the EventStreamRPCConnection */ protected ConnectionState connectionState; /** * Constructs a new EventStreamRPCConnection from the given configuration * @param config The configuration used to construct the EventStreamRPCConnection */ public EventStreamRPCConnection(final EventStreamRPCConnectionConfig config) { this.config = config; this.connectionState = new ConnectionState(ConnectionState.Phase.DISCONNECTED, null); } /** * Separate method to allow override for testing mismatch. May have external use * @return returns the event-stream-rpc version string to check against server compatibility */ protected String getVersionString() { return Version.getInstance().getVersionString(); } /** * Connects to the event stream RPC server asynchronously * * @return A future that completes when connected */ public CompletableFuture<Void> connect(final LifecycleHandler lifecycleHandler) { synchronized (connectionState) { if (connectionState.connectionPhase == ConnectionState.Phase.DISCONNECTED) { connectionState.connectionPhase = ConnectionState.Phase.CONNECTING_SOCKET; connectionState.onConnectCalled = false; } else { throw new IllegalStateException("Connection is already established"); } } final CompletableFuture<Void> initialConnectFuture = new CompletableFuture<>(); ClientConnection.connect(config.getHost(), (short) config.getPort(), config.getSocketOptions(), config.getTlsContext(), config.getClientBootstrap(), new ClientConnectionHandler() { @Override protected void onConnectionSetup(final ClientConnection clientConnection, int errorCode) { LOGGER.info(String.format("Socket connection %s:%d to server result [%s]", config.getHost(), config.getPort(), CRT.awsErrorName(errorCode))); synchronized (connectionState) { connectionState.connection = clientConnection; if (CRT.AWS_CRT_SUCCESS != errorCode) { connectionState.connectionPhase = ConnectionState.Phase.DISCONNECTED; initialConnectFuture.completeExceptionally(new CrtRuntimeException(errorCode, CRT.awsErrorName(errorCode))); } else if (connectionState.connectionPhase == ConnectionState.Phase.CLOSING) { connectionState.closeReason = new EventStreamClosedException("Event stream closed by client"); disconnect(); } else { connectionState.connectionPhase = ConnectionState.Phase.WAITING_CONNACK; config.getConnectMessageAmender().get() .whenComplete((messageAmendInfo, ex) -> { synchronized (connectionState) { if (clientConnection != connectionState.connection) { LOGGER.warning("MessageAmender completed with different connection than initial"); return; } if (connectionState.connectionPhase == ConnectionState.Phase.CLOSING) { connectionState.closeReason = new EventStreamClosedException("Event stream closed by client"); } else { try { final List<Header> headers = new ArrayList<>(messageAmendInfo.getHeaders().size() + 1); headers.add(Header.createHeader(EventStreamRPCServiceModel.VERSION_HEADER, getVersionString())); headers.addAll(messageAmendInfo.getHeaders().stream() .filter(header -> !header.getName().equals(EventStreamRPCServiceModel.VERSION_HEADER)) .collect(Collectors.toList())); LOGGER.fine("Waiting for connect ack message back from event stream RPC server"); clientConnection.sendProtocolMessage(headers, messageAmendInfo.getPayload(), MessageType.Connect, 0); } catch (Exception e) { connectionState.connectionPhase = ConnectionState.Phase.CLOSING; connectionState.closeReason = e; disconnect(); } } } }); } } } @Override protected void onProtocolMessage(List<Header> headers, byte[] payload, MessageType messageType, int messageFlags) { if (MessageType.ConnectAck.equals(messageType)) { synchronized (connectionState) { if ((messageFlags & MessageFlags.ConnectionAccepted.getByteValue()) != 0) { connectionState.connectionPhase = ConnectionState.Phase.CONNECTED; //now the client is open for business to invoke operations LOGGER.info("Connection established with event stream RPC server"); if (!initialConnectFuture.isDone()) { initialConnectFuture.complete(null); } connectionState.onConnectCalled = true; doOnConnect(lifecycleHandler); } else { //This is access denied, implied due to not having ConnectionAccepted msg flag LOGGER.warning("AccessDenied to event stream RPC server"); connectionState.connectionPhase = ConnectionState.Phase.CLOSING; connectionState.connection.closeConnection(0); final AccessDeniedException ade = new AccessDeniedException("Connection access denied to event stream RPC server"); if (!initialConnectFuture.isDone()) { initialConnectFuture.completeExceptionally(ade); } doOnError(lifecycleHandler, ade); } } } else if (MessageType.PingResponse.equals(messageType)) { LOGGER.finer("Ping response received"); } else if (MessageType.Ping.equals(messageType)) { sendPingResponse(Optional.of(new MessageAmendInfo( headers.stream().filter(header -> !header.getName().startsWith(":")) .collect(Collectors.toList()), payload))) .whenComplete((res, ex) -> { LOGGER.finer("Ping response sent"); }); } else if (MessageType.Connect.equals(messageType)) { LOGGER.severe("Erroneous connect message type received by client. Closing"); //TODO: client sends protocol error here? disconnect(); } else if (MessageType.ProtocolError.equals(messageType) || MessageType.ServerError.equals(messageType)) { LOGGER.severe("Received " + messageType.name() + ": " + CRT.awsErrorName(CRT.awsLastError())); connectionState.closeReason = EventStreamError.create(headers, payload, messageType); doOnError(lifecycleHandler, connectionState.closeReason); disconnect(); } else { LOGGER.severe("Unprocessed message type: " + messageType.name()); doOnError(lifecycleHandler, new EventStreamError("Unprocessed message type: " + messageType.name())); } } @Override protected void onConnectionClosed(int errorCode) { LOGGER.finer("Socket connection closed: " + CRT.awsErrorName(errorCode)); Throwable closeReason; boolean callOnDisconnect; synchronized (connectionState) { if (connectionState.connection != null) { connectionState.connection.close(); connectionState.connection = null; } connectionState.connectionPhase = ConnectionState.Phase.DISCONNECTED; closeReason = connectionState.closeReason; connectionState.closeReason = null; callOnDisconnect = connectionState.onConnectCalled; connectionState.onConnectCalled = false; } if (!initialConnectFuture.isDone()) { if (closeReason != null) { initialConnectFuture.completeExceptionally(closeReason); } else { initialConnectFuture.complete(null); } } if (callOnDisconnect) { doOnDisconnect(lifecycleHandler, errorCode); } } }); return initialConnectFuture; } /** * Creates a new stream with the given continuation handler. * Trhows an exception if not connected * * @param continuationHandler The continuation handler to use * @return A new ClientConnectionContinuation containing the new stream. */ public ClientConnectionContinuation newStream(ClientConnectionContinuationHandler continuationHandler) { synchronized (connectionState) { if (connectionState.connectionPhase == ConnectionState.Phase.CONNECTED) { return connectionState.connection.newStream(continuationHandler); } else { throw new EventStreamClosedException("EventStream connection is not open!"); } } } /** * Disconnects the EventStreamRPCConnection */ public void disconnect() { synchronized (connectionState) { if (connectionState.connectionPhase != ConnectionState.Phase.CLOSING && connectionState.connectionPhase != ConnectionState.Phase.DISCONNECTED) { connectionState.connectionPhase = ConnectionState.Phase.CLOSING; } if (connectionState.connection != null) { connectionState.connection.closeConnection(0); } if (connectionState.closeReason == null) { connectionState.closeReason = new EventStreamClosedException("Event stream closed by client"); } } } private void doOnConnect(LifecycleHandler lifecycleHandler) { try { lifecycleHandler.onConnect(); } catch (Exception ex) { LOGGER.warning(String.format("LifecycleHandler::onConnect() threw %s : %s", ex.getClass().getCanonicalName(), ex.getMessage())); doOnError(lifecycleHandler, ex); } } private void doOnError(LifecycleHandler lifecycleHandler, Throwable t) { try { if (lifecycleHandler.onError(t)) { LOGGER.fine("Closing connection due to LifecycleHandler::onError() returning true"); disconnect(); } } catch (Exception ex) { LOGGER.warning(String.format("Closing connection due to LifecycleHandler::onError() throwing %s : %s", ex.getClass().getCanonicalName(), ex.getMessage())); disconnect(); } } private void doOnDisconnect(LifecycleHandler lifecycleHandler, int errorCode) { try { lifecycleHandler.onDisconnect(errorCode); } catch (Exception ex) { LOGGER.warning(String.format("LifecycleHandler::onDisconnect(" + CRT.awsErrorName(errorCode) + ") threw %s : %s", ex.getClass().getCanonicalName(), ex.getMessage())); } } /** * Interface to send ping. Optional MessageAmendInfo will use the headers and payload * for the ping message verbatim. Should trigger a pong response and server copies back * @param pingData The ping data to send * @return A future that completes when the pong response is receieved */ public CompletableFuture<Void> sendPing(Optional<MessageAmendInfo> pingData) { ClientConnection connection; synchronized (connectionState) { if (connectionState.connectionPhase != ConnectionState.Phase.CONNECTED) { throw new EventStreamClosedException("EventStream connection not established"); } connection = connectionState.connection; if (pingData.isPresent()) { return connection.sendProtocolMessage(pingData.get().getHeaders(), pingData.get().getPayload(), MessageType.Ping, 0); } else { return connection.sendProtocolMessage(null, null, MessageType.Ping, 0); } } } /** * Interface to send pingResponse. Optional MessageAmendInfo will use the headers and payload * for the ping message verbatim. Should trigger a pong response and server copies back * @param pingResponseData The ping response data to send * @return A future that completes when the pong response is receieved */ public CompletableFuture<Void> sendPingResponse(Optional<MessageAmendInfo> pingResponseData) { ClientConnection connection; synchronized (connectionState) { if (connectionState.connectionPhase != ConnectionState.Phase.CONNECTED) { throw new EventStreamClosedException("EventStream connection not established"); } connection = connectionState.connection; if (pingResponseData.isPresent()) { return connection.sendProtocolMessage(pingResponseData.get().getHeaders(), pingResponseData.get().getPayload(), MessageType.Ping, 0); } else { return connection.sendProtocolMessage(null, null, MessageType.PingResponse, 0); } } } @Override public void close() { disconnect(); } /** * Lifecycle handler is how a client can react and respond to connectivity interruptions. Connectivity * interruptions are isolated from operation availability issues. */ public interface LifecycleHandler { /** * Invoked only if there is a successful connection. Leaves out the error code since it will have * already been compared to AWS_OP_SUCCESS */ void onConnect(); /** * Invoked for both connect failures and disconnects from a healthy state * * @param errorCode A code indicating the reason for the disconnect */ void onDisconnect(int errorCode); /** * Used to communicate errors that occur on the connection during any phase of its lifecycle that may * not appropriately or easily attach to onConnect() or onDisconnect(). Return value of this indicates * whether or not the client should stay connected or terminate the connection. Returning true indicates * the connection should terminate as a result of the error, and false indicates that the connection * should not. If the handler throws, is the same as returning true. * * Note: Some conditions when onError() is called will not care about the return value and always * result in closing the connection. AccessDeniedException is such an example * * @param t Exception * @return true if the connection should be terminated as a result of handling the error */ boolean onError(Throwable t); /** * Do nothing on ping by default. Inform handler of ping data * * TODO: Could use boolean return here as a hint on whether a pong reply should be sent? * * @param headers The ping headers * @param payload The ping payload */ default void onPing(List<Header> headers, byte[] payload) { }; } }
5,479
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/main/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/main/java/software/amazon/awssdk/eventstreamrpc/EventStreamRPCClient.java
package software.amazon.awssdk.eventstreamrpc; import software.amazon.awssdk.crt.eventstream.ClientConnectionContinuation; import software.amazon.awssdk.crt.eventstream.ClientConnectionContinuationHandler; import software.amazon.awssdk.crt.eventstream.Header; import software.amazon.awssdk.crt.eventstream.HeaderType; import software.amazon.awssdk.crt.eventstream.MessageFlags; import software.amazon.awssdk.crt.eventstream.MessageType; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; import software.amazon.awssdk.eventstreamrpc.model.EventStreamOperationError; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Logger; /** * Not sure how public we need to make this class */ public class EventStreamRPCClient { private static final Logger LOGGER = Logger.getLogger(EventStreamRPCClient.class.getName()); private final EventStreamRPCConnection connection; /** * Creates a new EventStreamRPCClient * @param connection The connection for the EventStreamRPCClient to use */ public EventStreamRPCClient(EventStreamRPCConnection connection) { if (connection == null) { throw new IllegalArgumentException("Cannot create eventstream RPC client with null connection"); } this.connection = connection; } /** * Work horse of all operations, streaming or otherwise. * @param <ReqType> The request type * @param <RespType> The response type * @param <StrReqType> The streaming request type * @param <StrRespType> The streaming response type * @param operationModelContext The operation context * @param request The request * @param streamResponseHandler The streaming handler * @return The operation result */ public <ReqType extends EventStreamJsonMessage, RespType extends EventStreamJsonMessage, StrReqType extends EventStreamJsonMessage, StrRespType extends EventStreamJsonMessage> OperationResponse<RespType, StrReqType> doOperationInvoke( OperationModelContext<ReqType, RespType, StrReqType, StrRespType> operationModelContext, final ReqType request, Optional<StreamResponseHandler<StrRespType>> streamResponseHandler) { if (operationModelContext.isStreamingOperation() && !streamResponseHandler.isPresent()) { //Even if an operation does not have a streaming response (has streaming input), a //stream is physically bidirectional, and even if a streaming response isn't allowed //the other side may still send an error through the open stream. throw new IllegalArgumentException(operationModelContext.getOperationName() + " is a streaming operation. Must have a streaming response handler!"); } final CompletableFuture<RespType> responseFuture = new CompletableFuture<>(); final AtomicBoolean isContinuationClosed = new AtomicBoolean(true); final ClientConnectionContinuation continuation = connection.newStream(new ClientConnectionContinuationHandler() { boolean initialResponseReceived = false; @Override protected void onContinuationMessage(List<Header> headers, byte[] payload, MessageType messageType, int messageFlags) { final Optional<String> applicationModelType = headers.stream() .filter(header -> header.getName().equals(EventStreamRPCServiceModel.SERVICE_MODEL_TYPE_HEADER) && header.getHeaderType().equals(HeaderType.String)) .map(header -> header.getValueAsString()) .findFirst(); //first message back must parse into immediate response unless it's an error //follow on messages are stream response handler intended if (messageType.equals(MessageType.ApplicationMessage)) { //important following not else if if (applicationModelType.isPresent()) { handleData(applicationModelType.get(), payload, !initialResponseReceived, responseFuture, streamResponseHandler, operationModelContext, continuation, isContinuationClosed); } //intentionally not else if here. We can have data, and the terminate flag set if ((messageFlags & MessageFlags.TerminateStream.getByteValue()) != 0) { this.close(); handleClose(initialResponseReceived, responseFuture, streamResponseHandler); } else if (!applicationModelType.isPresent()) { handleError(new UnmappedDataException(initialResponseReceived ? operationModelContext.getResponseApplicationModelType() : operationModelContext.getStreamingResponseApplicationModelType().get()), initialResponseReceived, responseFuture, streamResponseHandler, continuation, isContinuationClosed); } initialResponseReceived = true; } else if (messageType.equals(MessageType.ApplicationError)) { final Optional<Class<? extends EventStreamJsonMessage>> errorClass = operationModelContext.getServiceModel().getApplicationModelClass(applicationModelType.orElse("")); if (!errorClass.isPresent()) { LOGGER.severe(String.format("Could not map error from service. Incoming error type: " + applicationModelType.orElse("null"))); handleError(new UnmappedDataException(applicationModelType.orElse("null")), !initialResponseReceived, responseFuture, streamResponseHandler, continuation, isContinuationClosed); } else { try { final EventStreamOperationError error = (EventStreamOperationError) operationModelContext.getServiceModel().fromJson(errorClass.get(), payload); handleError(error, !initialResponseReceived, responseFuture, streamResponseHandler, continuation, isContinuationClosed); } catch (Exception e) { //shouldn't be possible, but this is an error on top of an error } } //TODO: application errors always have TerminateStream flag set? //first close the stream immediately if the other side hasn't already done so if ((messageFlags & MessageFlags.TerminateStream.getByteValue()) != 0) { try { this.close(); //is this call needed? handleClose(initialResponseReceived, responseFuture, streamResponseHandler); } catch (Exception e) { LOGGER.warning(String.format("Exception thrown closing stream on application error received %s: %s", e.getClass().getName(), e.getMessage())); } } } else if (messageType == MessageType.Ping) { //echo back ping messages to be nice to server, can these happen on continuations? continuation.sendMessage(headers, payload, MessageType.PingResponse, messageFlags); } else if (messageType == MessageType.PingResponse) { //do nothing on ping response } else if (messageType == MessageType.ServerError) { //TODO: exception should route to response handler here, also is or will be "InternalError" soon LOGGER.severe(operationModelContext.getOperationName() + " server error received"); this.close(); //underlying connection callbacks should handle things appropriately } else if (messageType == MessageType.ProtocolError) { //do nothing on ping response LOGGER.severe(operationModelContext.getOperationName() + " protocol error received"); this.close(); //underlying connection callbacks should handle things appropriately but close continuation either way } else { //unexpected message type received on stream handleError(new InvalidDataException(messageType), !initialResponseReceived, responseFuture, streamResponseHandler, continuation, isContinuationClosed); try { sendClose(continuation, isContinuationClosed).whenComplete((res, ex) -> { if (ex != null) { LOGGER.warning(String.format("Sending close on invalid message threw %s: %s", ex.getClass().getCanonicalName(), ex.getMessage())); } }); } catch (Exception e) { LOGGER.warning(String.format("Sending close on invalid message threw %s: %s", e.getClass().getCanonicalName(), e.getMessage())); } } } @Override protected void onContinuationClosed() { super.onContinuationClosed(); handleClose(initialResponseReceived, responseFuture, streamResponseHandler); } }); isContinuationClosed.compareAndSet(false, true); final List<Header> headers = new LinkedList<>(); headers.add(Header.createHeader(EventStreamRPCServiceModel.CONTENT_TYPE_HEADER, EventStreamRPCServiceModel.CONTENT_TYPE_APPLICATION_JSON)); headers.add(Header.createHeader(EventStreamRPCServiceModel.SERVICE_MODEL_TYPE_HEADER, operationModelContext.getRequestApplicationModelType())); final byte[] payload = operationModelContext.getServiceModel().toJson(request); final CompletableFuture<Void> messageFlushFuture = continuation.activate(operationModelContext.getOperationName(), headers, payload, MessageType.ApplicationMessage, 0); final OperationResponse<RespType, StrReqType> response = new OperationResponse(operationModelContext, continuation, responseFuture, messageFlushFuture); return response; } /** * Sends an empty close message on the open stream. * @param continuation continuation to send the close message on * @return CompletableFuture indicating flush of the close message. */ private CompletableFuture<Void> sendClose(final ClientConnectionContinuation continuation, final AtomicBoolean isClosed) { if (isClosed.compareAndSet(false, true)) { return continuation.sendMessage(null, null, MessageType.ApplicationMessage, MessageFlags.TerminateStream.getByteValue()); } else { LOGGER.warning("Stream already closed"); //May help debug extra closes? May remove to avoid noise return CompletableFuture.completedFuture(null); } } private <RespType extends EventStreamJsonMessage, StrRespType extends EventStreamJsonMessage> void handleClose(boolean isInitial, CompletableFuture<RespType> responseFuture, final Optional<StreamResponseHandler<StrRespType>> streamResponseHandler) { if (isInitial && !responseFuture.isDone()) { //response future should have completed because either an error has already been thrown using it, //or the data has already come back. This combination is a problem state that suggests we're closing //before having any server response responseFuture.completeExceptionally(new RuntimeException("Closed received before any service operation response!")); } else if (streamResponseHandler.isPresent()) { //The only valid way to respond to a close after request-response is via stream handler. //This is a strange detail where a request->response operation doesn't really care or see //the stream closing unless it uses a stream response handler. try { streamResponseHandler.get().onStreamClosed(); } catch (Exception e) { LOGGER.warning(String.format("Client handler onStreamClosed() threw %s: %s", e.getClass().getCanonicalName(), e.getMessage())); } } } private <RespType extends EventStreamJsonMessage, StrRespType extends EventStreamJsonMessage> void handleData(String applicationModelType, byte[] payload, boolean isInitial, CompletableFuture<RespType> responseFuture, final Optional<StreamResponseHandler<StrRespType>> streamResponseHandler, final OperationModelContext<?, RespType, ?, StrRespType> operationModelContext, ClientConnectionContinuation continuation, final AtomicBoolean isClosed) { if (isInitial) { //mismatch between type on the wire and type expected by the operation if (!applicationModelType.equals(operationModelContext.getResponseApplicationModelType())) { handleError(new UnmappedDataException(applicationModelType, operationModelContext.getResponseTypeClass()), isInitial, responseFuture, streamResponseHandler, continuation, isClosed); return; } RespType responseObj = null; try { responseObj = operationModelContext.getServiceModel().fromJson(operationModelContext.getResponseTypeClass(), payload); } catch (Exception e) { handleError(new DeserializationException(payload, e), isInitial, responseFuture, streamResponseHandler, continuation, isClosed); return; //we're done if we can't deserialize } //complete normally responseFuture.complete(responseObj); } else { //mismatch between type on the wire and type expected by the operation if (!applicationModelType.equals(operationModelContext.getStreamingResponseApplicationModelType().get())) { handleError(new UnmappedDataException(applicationModelType, operationModelContext.getStreamingResponseTypeClass().get()), isInitial, responseFuture, streamResponseHandler, continuation, isClosed); return; } StrRespType strResponseObj = null; try { strResponseObj = operationModelContext.getServiceModel().fromJson( operationModelContext.getStreamingResponseTypeClass().get(), payload); } catch (Exception e) { handleError(new DeserializationException(payload, e), isInitial, responseFuture, streamResponseHandler, continuation, isClosed); return; //we're done if we can't deserialize } try { streamResponseHandler.get().onStreamEvent(strResponseObj); } catch (Exception e) { handleError(e, isInitial, responseFuture, streamResponseHandler, continuation, isClosed); } } } /** * Handle error and based on result may close stream */ private <RespType extends EventStreamJsonMessage, StrRespType extends EventStreamJsonMessage> void handleError(Throwable t, boolean isInitial, final CompletableFuture<RespType> responseFuture, final Optional<StreamResponseHandler<StrRespType>> streamResponseHandler, ClientConnectionContinuation continuation, final AtomicBoolean isClosed) { if (!isInitial && !streamResponseHandler.isPresent()) { throw new IllegalArgumentException("Cannot process error handling for stream without a stream response handler set!"); } if (isInitial) { responseFuture.completeExceptionally(t); //failure on initial response future always closes stream } else { try { if (streamResponseHandler.get().onStreamError(t)) { sendClose(continuation, isClosed).whenComplete((res, ex) -> { handleClose(isInitial, responseFuture, streamResponseHandler); }); } } catch (Exception e) { LOGGER.warning(String.format("Stream response handler threw exception %s: %s", e.getClass().getCanonicalName(), e.getMessage())); sendClose(continuation, isClosed).whenComplete((res, ex) -> { handleClose(isInitial, responseFuture, streamResponseHandler); }); } } } }
5,480
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/main/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/main/java/software/amazon/awssdk/eventstreamrpc/StreamResponse.java
package software.amazon.awssdk.eventstreamrpc; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; import java.util.concurrent.CompletableFuture; /** * Interface for stream responses */ public interface StreamResponse<ResponseType extends EventStreamJsonMessage, StreamRequestType extends EventStreamJsonMessage> extends StreamEventPublisher<StreamRequestType> { /** * Completable future indicating flush of the request that initiated the stream operation * * @return Completable future indicating flush of the request that initiated the stream operation */ CompletableFuture<Void> getRequestFlushFuture(); /** * Completable future for retrieving the initial-response of the stream operation * * @return Completable future for retrieving the initial-response of the stream operation */ CompletableFuture<ResponseType> getResponse(); /** * Tests if the stream is closed * @return True if the stream is closed */ boolean isClosed(); }
5,481
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/main/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/main/java/software/amazon/awssdk/eventstreamrpc/EventStreamRPCConnectionConfig.java
package software.amazon.awssdk.eventstreamrpc; import software.amazon.awssdk.crt.io.ClientBootstrap; import software.amazon.awssdk.crt.io.ClientTlsContext; import software.amazon.awssdk.crt.io.EventLoopGroup; import software.amazon.awssdk.crt.io.SocketOptions; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; /** * The closeable elements inside the EventStreamRPCConnectionConfig are not cleaned up when * this config object is done. It is still up to the caller of the constructor to clean up * resources that are associated in the config. * * The connect message transformer is used to supply additional connect message headers * and supply the payload of the connect message. This is to be used to supply authentication * information on the connect */ public class EventStreamRPCConnectionConfig { private final ClientBootstrap clientBootstrap; private final EventLoopGroup eventLoopGroup; private final SocketOptions socketOptions; private final ClientTlsContext tlsContext; private final String host; private final int port; /** * MessageAmendInfo here is used to add supplied headers to the Connect message, and * set the payload of that message as well. */ private final Supplier<CompletableFuture<MessageAmendInfo>> connectMessageAmender; /** * Creates a new EventStreamRPCConnectionConfig with the given data * @param clientBootstrap The ClientBootstrap to use * @param eventLoopGroup The EventLoopGroup to use * @param socketOptions The SocketOptions to use * @param tlsContext The TlsContext to use * @param host The host name to use * @param port The host port to use * @param connectMessageAmender The connect message amender to use */ public EventStreamRPCConnectionConfig(ClientBootstrap clientBootstrap, EventLoopGroup eventLoopGroup, SocketOptions socketOptions, ClientTlsContext tlsContext, String host, int port, Supplier<CompletableFuture<MessageAmendInfo>> connectMessageAmender) { this.clientBootstrap = clientBootstrap; this.eventLoopGroup = eventLoopGroup; this.socketOptions = socketOptions; this.tlsContext = tlsContext; this.host = host; this.port = port; this.connectMessageAmender = connectMessageAmender; //perform cast to throw exception here if port value is out of short value range final short shortPort = (short)port; //bit of C++ RAII here, validate what we can if (clientBootstrap == null || eventLoopGroup == null || socketOptions == null || host == null || host.isEmpty() || port < 0) { throw new IllegalArgumentException("EventStreamRPCConnectionConfig values are invalid!"); } } /** * Returns the ClientBootstrap associated with the EventStreamRPCConnectionConfig * @return the ClientBootstrap associated with the EventStreamRPCConnectionConfig */ public ClientBootstrap getClientBootstrap() { return clientBootstrap; } /** * Returns the EventLoopGroup associated with the EventStreamRPCConnectionConfig * @return the EventLoopGroup associated with the EventStreamRPCConnectionConfig */ public EventLoopGroup getEventLoopGroup() { return eventLoopGroup; } /** * Returns the SocketOptions associated with the EventStreamRPCConnectionConfig * @return The SocketOptions associated with the EventStreamRPCConnectionConfig */ public SocketOptions getSocketOptions() { return socketOptions; } /** * Returns the TlsContext associated with the EventStreamRPCConnectionConfig * @return The TlsContext associated with the EventStreamRPCConnectionConfig */ public ClientTlsContext getTlsContext() { return tlsContext; } /** * Returns the host name associated with the EventStreamRPCConnectionConfig * @return The host name associated with the EventStreamRPCConnectionConfig */ public String getHost() { return host; } /** * Returns the port associated with the EventStreamRPCConnectionConfig * @return The port associated with the EventStreamRPCConnectionConfig */ public int getPort() { return port; } /** * Returns the connect message amender associated with the EventStreamRPCConnectionConfig * @return The connect message amender associated with the EventStreamRPCConnectionConfig */ public Supplier<CompletableFuture<MessageAmendInfo>> getConnectMessageAmender() { return connectMessageAmender; } }
5,482
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/main/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/greengrass/event-stream-rpc-client/src/main/java/software/amazon/awssdk/eventstreamrpc/OperationResponse.java
package software.amazon.awssdk.eventstreamrpc; import software.amazon.awssdk.crt.eventstream.ClientConnectionContinuation; import software.amazon.awssdk.crt.eventstream.Header; import software.amazon.awssdk.crt.eventstream.MessageFlags; import software.amazon.awssdk.crt.eventstream.MessageType; import software.amazon.awssdk.eventstreamrpc.model.EventStreamJsonMessage; import java.util.LinkedList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Logger; /** * Underlying type for operation response handling. Enables publishing on stream operations from * client, closing of any open stream, and retrieval of response. Specific generated operation response * handlers are usually simple wrappers with the generic types specified * * @param <ResponseType> The response type * @param <StreamRequestType> The stream response type */ public class OperationResponse<ResponseType extends EventStreamJsonMessage, StreamRequestType extends EventStreamJsonMessage> implements StreamResponse<ResponseType, StreamRequestType>, AutoCloseable { private static final Logger LOGGER = Logger.getLogger(OperationResponse.class.getName()); private final OperationModelContext operationModelContext; private final ClientConnectionContinuation continuation; private final CompletableFuture<ResponseType> responseFuture; private final CompletableFuture<Void> requestFlushFuture; private final AtomicBoolean isClosed; /** * Creates a new OperationResponse from the given data * @param operationModelContext The operation model context to use * @param continuation The continuation to use * @param responseFuture The response future to use * @param requestFlushFuture The request flush future to use */ public OperationResponse(OperationModelContext<ResponseType, ?, StreamRequestType, ?> operationModelContext, ClientConnectionContinuation continuation, CompletableFuture<ResponseType> responseFuture, CompletableFuture<Void> requestFlushFuture) { this.operationModelContext = operationModelContext; this.continuation = continuation; this.responseFuture = responseFuture; this.requestFlushFuture = requestFlushFuture; this.isClosed = new AtomicBoolean(continuation != null && !continuation.isNull()); } /** * Returns the request flush future to use * @return The request flush future to use */ final public CompletableFuture<Void> getRequestFlushFuture() { return requestFlushFuture; } /** * Get the response completable future to wait on the initial response * if there is one. * * May throw exception if requestFlushFuture throws an exception and will * block if requestFlush has not completed. * * @return the response completable future to wait on the initial response * if there is one. */ public CompletableFuture<ResponseType> getResponse() { //semantics here are: if the request was never successfully sent //then the request flush future holds the exception thrown so that //must be made visible of the caller waits for the response directly. //It is impossible to have a successful response future completed //with a request flush never having completed or having thrown an //exception. return requestFlushFuture.thenCompose((v) -> responseFuture); } /** * Publish stream events on an open operation's event stream. * @param streamEvent event to publish */ @Override public CompletableFuture<Void> sendStreamEvent(final StreamRequestType streamEvent) { try { final List<Header> headers = new LinkedList<>(); headers.add(Header.createHeader(EventStreamRPCServiceModel.SERVICE_MODEL_TYPE_HEADER, (String) operationModelContext.getStreamingRequestApplicationModelType().get())); headers.add(Header.createHeader(EventStreamRPCServiceModel.CONTENT_TYPE_HEADER, EventStreamRPCServiceModel.CONTENT_TYPE_APPLICATION_JSON)); final byte[] payload = operationModelContext.getServiceModel() .toJson(streamEvent); return continuation.sendMessage(headers, payload, MessageType.ApplicationMessage, 0) .whenComplete((res, ex) -> { if (ex != null) { LOGGER.warning(String.format("%s caught %s while sending message the event stream: %s", operationModelContext.getOperationName(), ex.getClass().getName(), ex.getMessage())); closeStream(); } }); } catch (Exception e) { final CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(e); return future; } } /** * Initiate a close on the event stream from the client side. * * @return A future that completes when the event stream is closed */ @Override public CompletableFuture<Void> closeStream() { if (continuation != null && !continuation.isNull()) { return continuation.sendMessage(null, null, MessageType.ApplicationMessage, MessageFlags.TerminateStream.getByteValue()) .whenComplete((res, ex) -> { LOGGER.info(operationModelContext.getOperationName() + " operation stream closed"); continuation.close(); if (ex != null) { LOGGER.warning(String.format("%s threw %s while closing the event stream: %s", operationModelContext.getOperationName(), ex.getClass().getName(), ex.getMessage())); } }); } return CompletableFuture.completedFuture(null); } /** * Checks if the stream is closed * @return True if the stream is closed */ public boolean isClosed() { return isClosed.get(); } @Override public void close() throws Exception { if (isClosed.compareAndSet(false, true)) { closeStream(); } } }
5,483
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/AwsIotMqttConnectionBuilder.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package software.amazon.awssdk.iot; import software.amazon.awssdk.crt.utils.PackageInfo; import java.io.UnsupportedEncodingException; import java.util.function.Consumer; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.CrtRuntimeException; import software.amazon.awssdk.crt.Log; import software.amazon.awssdk.crt.Log.LogLevel; import software.amazon.awssdk.crt.Log.LogSubject; import software.amazon.awssdk.crt.auth.credentials.CredentialsProvider; import software.amazon.awssdk.crt.auth.credentials.DefaultChainCredentialsProvider; import software.amazon.awssdk.crt.auth.signing.AwsSigningConfig; import software.amazon.awssdk.crt.http.HttpProxyOptions; import software.amazon.awssdk.crt.io.ClientBootstrap; import software.amazon.awssdk.crt.io.ClientTlsContext; import software.amazon.awssdk.crt.io.SocketOptions; import software.amazon.awssdk.crt.io.TlsContextCustomKeyOperationOptions; import software.amazon.awssdk.crt.io.TlsContextOptions; import software.amazon.awssdk.crt.io.TlsContextPkcs11Options; import software.amazon.awssdk.crt.mqtt.MqttClient; import software.amazon.awssdk.crt.mqtt.MqttClientConnection; import software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents; import software.amazon.awssdk.crt.mqtt.MqttConnectionConfig; import software.amazon.awssdk.crt.mqtt.MqttException; import software.amazon.awssdk.crt.mqtt.MqttMessage; import software.amazon.awssdk.crt.mqtt.QualityOfService; import software.amazon.awssdk.crt.mqtt.WebsocketHandshakeTransformArgs; /** * A central class for building Mqtt connections without manually managing a large variety of native objects (some * still need to be created though). */ public final class AwsIotMqttConnectionBuilder extends CrtResource { private static String IOT_SIGNING_SERVICE = "iotdevicegateway"; private static String AMZ_DATE_HEADER = "x-amz-date"; private static String AMZ_SECURITY_TOKEN_HEADER = "x-amz-security-token"; MqttConnectionConfig config; /* Internal config and state */ private MqttClient client; // Lazy create, cached private CredentialsProvider websocketCredentialsProvider; private String websocketSigningRegion; private ClientTlsContext tlsContext; // Lazy create, cached private TlsContextOptions tlsOptions; private ClientBootstrap bootstrap; private boolean resetLazilyCreatedResources = true; // Used to detect if we need to set the ALPN list for custom authorizer private boolean isUsingCustomAuthorizer = false; private void resetDefaultPort() { if (TlsContextOptions.isAlpnSupported()) { this.tlsOptions.withAlpnList("x-amzn-mqtt-ca"); this.config.setPort(443); } else { this.config.setPort(8883); } } private AwsIotMqttConnectionBuilder(TlsContextOptions tlsOptions) { try (MqttConnectionConfig connectionConfig = new MqttConnectionConfig()) { addReferenceTo(connectionConfig); config = connectionConfig; } this.tlsOptions = tlsOptions; addReferenceTo(tlsOptions); resetDefaultPort(); } /** * Required override method that must begin the release process of the acquired native handle */ @Override protected void releaseNativeHandle() {} /** * Override that determines whether a resource releases its dependencies at the same time the native handle is released or if it waits. * Resources with asynchronous shutdown processes should override this with false, and establish a callback from native code that * invokes releaseReferences() when the asynchronous shutdown process has completed. See HttpClientConnectionManager for an example. */ @Override protected boolean canReleaseReferencesImmediately() { return true; } /** * Create a new builder with mTLS file paths * * @param certPath - Path to certificate, in PEM format * @param privateKeyPath - Path to private key, in PEM format * @return {@link AwsIotMqttConnectionBuilder} */ public static AwsIotMqttConnectionBuilder newMtlsBuilderFromPath(String certPath, String privateKeyPath) { try (TlsContextOptions tlsContextOptions = TlsContextOptions.createWithMtlsFromPath(certPath, privateKeyPath)) { return new AwsIotMqttConnectionBuilder(tlsContextOptions); } } /** * Create a new builder with mTLS cert pair in memory * * @param certificate - Certificate, in PEM format * @param privateKey - Private key, in PEM format * @return {@link AwsIotMqttConnectionBuilder} */ public static AwsIotMqttConnectionBuilder newMtlsBuilder(String certificate, String privateKey) { try (TlsContextOptions tlsContextOptions = TlsContextOptions.createWithMtls(certificate, privateKey)) { return new AwsIotMqttConnectionBuilder(tlsContextOptions); } } /** * Create a new builder with mTLS cert pair in memory * * @param certificate - Certificate, in PEM format * @param privateKey - Private key, in PEM format * @return {@link AwsIotMqttConnectionBuilder} * @throws UnsupportedEncodingException if encoding is unsupported */ public static AwsIotMqttConnectionBuilder newMtlsBuilder(byte[] certificate, byte[] privateKey) throws UnsupportedEncodingException { return newMtlsBuilder(new String(certificate, "UTF8"), new String(privateKey, "UTF8")); } /** * Create a new builder with mTLS, using a PKCS#11 library for private key operations. * * NOTE: Unix only * * @param pkcs11Options PKCS#11 options * @return {@link AwsIotMqttConnectionBuilder} */ public static AwsIotMqttConnectionBuilder newMtlsPkcs11Builder(TlsContextPkcs11Options pkcs11Options) { try (TlsContextOptions tlsContextOptions = TlsContextOptions.createWithMtlsPkcs11(pkcs11Options)) { return new AwsIotMqttConnectionBuilder(tlsContextOptions); } } /** * Create a new builder with mTLS, using a custom handler for private key operations. * * @param operationOptions options for using a custom handler * @return {@link AwsIotMqttConnectionBuilder} */ public static AwsIotMqttConnectionBuilder newMtlsCustomKeyOperationsBuilder(TlsContextCustomKeyOperationOptions operationOptions) { try (TlsContextOptions tlsContextOptions = TlsContextOptions.createWithMtlsCustomKeyOperations(operationOptions)) { return new AwsIotMqttConnectionBuilder(tlsContextOptions); } } /** * Create a new builder with mTLS, using a certificate in a Windows certificate store. * * NOTE: Windows only * * @param certificatePath Path to certificate in a Windows certificate store. * The path must use backslashes and end with the * certificate's thumbprint. Example: * {@code CurrentUser\MY\A11F8A9B5DF5B98BA3508FBCA575D09570E0D2C6} * @return {@link AwsIotMqttConnectionBuilder} */ public static AwsIotMqttConnectionBuilder newMtlsWindowsCertStorePathBuilder(String certificatePath) { try (TlsContextOptions tlsContextOptions = TlsContextOptions .createWithMtlsWindowsCertStorePath(certificatePath)) { return new AwsIotMqttConnectionBuilder(tlsContextOptions); } } /** * Create a new builder with mTLS, using a certificate and key stored in the passed-in Java keystore. * * Note: function assumes the passed keystore has already been loaded from a file by calling "keystore.load(file, password)" * * @param keyStore The Java keystore to use. Assumed to be loaded with certificates and keys * @param certificateAlias The alias of the certificate and key to use with the builder. * @param certificatePassword The password of the certificate and key to use with the builder. * @throws CrtRuntimeException if an error occurs, like the keystore cannot be opened or the certificate is not found. * @return {@link AwsIotMqttConnectionBuilder} */ public static AwsIotMqttConnectionBuilder newJavaKeystoreBuilder( java.security.KeyStore keyStore, String certificateAlias, String certificatePassword) throws CrtRuntimeException { try (TlsContextOptions tlsContextOptions = TlsContextOptions .createWithMtlsJavaKeystore(keyStore, certificateAlias, certificatePassword)) { return new AwsIotMqttConnectionBuilder(tlsContextOptions); } } /** * Create a new builder with mTLS, using a PKCS12 library for private key operations. * * NOTE: MacOS only * * @param pkcs12Path Path to the PKCS12 file to use with the builder. * @param pkcs12Password The password of the PKCS12 file to use with the builder. * @return {@link AwsIotMqttConnectionBuilder} */ public static AwsIotMqttConnectionBuilder newMtlsPkcs12Builder( String pkcs12Path, String pkcs12Password) { try (TlsContextOptions tlsContextOptions = TlsContextOptions.createWithMtlsPkcs12(pkcs12Path, pkcs12Password)) { return new AwsIotMqttConnectionBuilder(tlsContextOptions); } } /** * Create a new builder with no default Tls options * * @return a new builder with default Tls options * @throws UnsupportedEncodingException if encoding is unsupported */ public static AwsIotMqttConnectionBuilder newDefaultBuilder() throws UnsupportedEncodingException { try (TlsContextOptions tlsContextOptions = TlsContextOptions.createDefaultClient()) { return new AwsIotMqttConnectionBuilder(tlsContextOptions); } } /** * Overrides the default system trust store. * * @param caDirPath - Only used on Unix-style systems where all trust anchors * are stored in a directory (e.g. /etc/ssl/certs). * @param caFilePath - Single file containing all trust CAs, in PEM format * @return {@link AwsIotMqttConnectionBuilder} */ public AwsIotMqttConnectionBuilder withCertificateAuthorityFromPath(String caDirPath, String caFilePath) { this.tlsOptions.overrideDefaultTrustStoreFromPath(caDirPath, caFilePath); resetLazilyCreatedResources = true; return this; } /** * Overrides the default system trust store. * * @param caRoot - Buffer containing all trust CAs, in PEM format * @return {@link AwsIotMqttConnectionBuilder} */ public AwsIotMqttConnectionBuilder withCertificateAuthority(String caRoot) { this.tlsOptions.overrideDefaultTrustStore(caRoot); resetLazilyCreatedResources = true; return this; } /** * Configures the IoT endpoint for connections from this builder. * * @param endpoint The IoT endpoint to connect to * @return {@link AwsIotMqttConnectionBuilder} */ public AwsIotMqttConnectionBuilder withEndpoint(String endpoint) { this.config.setEndpoint(endpoint); return this; } /** * Configures the port to connect to for connections from this builder. If not set, 443 will be used for * a websocket connection or where ALPN support is available. Otherwise the default is 8883. * * @param port The port to connect to on the IoT endpoint. Usually 8883 for * MQTT, or 443 for websockets * @return {@link AwsIotMqttConnectionBuilder} */ public AwsIotMqttConnectionBuilder withPort(short port) { this.config.setPort(port); return this; } /** * Configures the client id to use to connect to the IoT Core service. * * @param clientId The client id for connections from this builder. Needs to be unique across * all devices/clients. * @return {@link AwsIotMqttConnectionBuilder} */ public AwsIotMqttConnectionBuilder withClientId(String clientId) { this.config.setClientId(clientId); return this; } /** * Configures whether or not the service should try to resume prior * subscriptions, if it has any * * @param cleanSession true if the session should drop prior subscriptions when * a connection from this builder is established, false to resume the session * @return {@link AwsIotMqttConnectionBuilder} */ public AwsIotMqttConnectionBuilder withCleanSession(boolean cleanSession) { this.config.setCleanSession(cleanSession); return this; } /** * @deprecated Configures MQTT keep-alive via PING messages. Note that this is not TCP * keepalive. * * @param keepAliveMs How often in milliseconds to send an MQTT PING message to the * service to keep connections alive * @return {@link AwsIotMqttConnectionBuilder} */ @Deprecated public AwsIotMqttConnectionBuilder withKeepAliveMs(int keepAliveMs) { this.config.setKeepAliveSecs(keepAliveMs/1000); return this; } /** * Configures MQTT keep-alive via PING messages. Note that this is not TCP * keepalive. * * @param keepAliveSecs How often in seconds to send an MQTT PING message to the * service to keep connections alive * @return {@link AwsIotMqttConnectionBuilder} */ public AwsIotMqttConnectionBuilder withKeepAliveSecs(int keepAliveSecs) { this.config.setKeepAliveSecs(keepAliveSecs); return this; } /** * Controls ping timeout value. If a response is not received within this * interval, the connection will be reestablished. * * @param pingTimeoutMs How long to wait for a ping response before resetting a connection built from this * builder. * @return {@link AwsIotMqttConnectionBuilder} */ public AwsIotMqttConnectionBuilder withPingTimeoutMs(int pingTimeoutMs) { this.config.setPingTimeoutMs(pingTimeoutMs); return this; } /** * Controls timeout value for requests that response is required on healthy connection. * If a response is not received within this interval, the request will fail as server not receiving it. * Applied to publish (QoS greater than 0) and unsubscribe * * @param protocolOperationTimeoutMs How long to wait for a request response (in milliseconds) before failing * @return {@link AwsIotMqttConnectionBuilder} */ public AwsIotMqttConnectionBuilder withProtocolOperationTimeoutMs(int protocolOperationTimeoutMs) { this.config.setProtocolOperationTimeoutMs(protocolOperationTimeoutMs); return this; } /** * Configures the TCP socket connect timeout (in milliseconds) * * @param timeoutMs TCP socket timeout * @return {@link AwsIotMqttConnectionBuilder} */ public AwsIotMqttConnectionBuilder withTimeoutMs(int timeoutMs) { if (this.config.getSocketOptions() == null) { this.withSocketOptions(new SocketOptions()); } this.config.getSocketOptions().connectTimeoutMs = timeoutMs; return this; } /** * Configures the minimum and maximum reconnect timeouts. * * The time between reconnect attempts will start at min and multiply by 2 until max is reached. * * @param minTimeoutSecs The timeout to start with * @param maxTimeoutSecs The highest allowable wait time between reconnect attempts * @return {@link AwsIotMqttConnectionBuilder} */ public AwsIotMqttConnectionBuilder withReconnectTimeoutSecs(long minTimeoutSecs, long maxTimeoutSecs) { this.config.setReconnectTimeoutSecs(minTimeoutSecs, maxTimeoutSecs); return this; } /** * Configures the common settings for the socket to use for connections created by this builder * * @param socketOptions The socket settings * @return {@link AwsIotMqttConnectionBuilder} */ public AwsIotMqttConnectionBuilder withSocketOptions(SocketOptions socketOptions) { this.config.setSocketOptions(socketOptions); return this; } /** * Configures the username to include in the initial CONNECT mqtt packet for connections created by this builder. * * @param username username to use in CONNECT * @return {@link AwsIotMqttConnectionBuilder} */ public AwsIotMqttConnectionBuilder withUsername(String username) { this.config.setUsername(username); return this; } /** * Configures the password to include in the initial CONNECT mqtt packet for connections created by this builder. * * @param password password to use in CONNECT * @return {@link AwsIotMqttConnectionBuilder} */ public AwsIotMqttConnectionBuilder withPassword(String password) { this.config.setPassword(password); return this; } /** * Configures the connection-related callbacks to use for connections created by this builder * * @param callbacks connection event callbacks to use * @return {@link AwsIotMqttConnectionBuilder} */ public AwsIotMqttConnectionBuilder withConnectionEventCallbacks(MqttClientConnectionEvents callbacks) { this.config.setConnectionCallbacks(callbacks); return this; } /** * Sets the last will and testament message to be delivered to a topic when a connection created by this builder * disconnects * * @param message The message to publish as the will. The message contains the * topic that the message will be published to on disconnect, * along with the {@link QualityOfService} that it will be * published with and whether it will be retained when it is published. * @return {@link AwsIotMqttConnectionBuilder} */ public AwsIotMqttConnectionBuilder withWill(MqttMessage message) throws MqttException { this.config.setWillMessage(message); return this; } /** * @deprecated Use alternate withWill(). QoS and retain are now set directly on the {@link MqttMessage} * @param message deprecated * @param qos deprecated * @param retain depricated * @return {@link AwsIotMqttConnectionBuilder} */ @Deprecated public AwsIotMqttConnectionBuilder withWill(MqttMessage message, QualityOfService qos, boolean retain) throws MqttException { return withWill(new MqttMessage(message.getTopic(), message.getPayload(), qos, retain)); } /** * Configures the client bootstrap to use for connections created by this builder * * @param bootstrap client bootstrap to use for created connections * @return {@link AwsIotMqttConnectionBuilder} */ public AwsIotMqttConnectionBuilder withBootstrap(ClientBootstrap bootstrap) { swapReferenceTo(this.bootstrap, bootstrap); this.bootstrap = bootstrap; resetLazilyCreatedResources = true; return this; } /** * Configures whether or not to the connection uses websockets * * @param useWebsockets whether or not to use websockets * @return {@link AwsIotMqttConnectionBuilder} */ public AwsIotMqttConnectionBuilder withWebsockets(boolean useWebsockets) { this.config.setUseWebsockets(useWebsockets); if (useWebsockets) { this.tlsOptions.alpnList.clear(); this.config.setPort(443); } else { resetDefaultPort(); } resetLazilyCreatedResources = true; return this; } /** * Configures handshake transform used when establishing a connection via websockets. If no transform has been * set then a default transform is used that adds AWS IoT authentication parameters and signs the request via * Sigv4. * * When done mutating the request, complete MUST be called on the future contained within the * transform args parameter. * * @param handshakeTransform handshake request transformation function * @return {@link AwsIotMqttConnectionBuilder} */ public AwsIotMqttConnectionBuilder withWebsocketHandshakeTransform(Consumer<WebsocketHandshakeTransformArgs> handshakeTransform) { this.config.setWebsocketHandshakeTransform(handshakeTransform); return this; } /** * @deprecated use withHttpProxyOptions instead * Configures any http proxy options to use if the connection uses websockets * * @param proxyOptions http proxy options to use when establishing a websockets-based connection * @return {@link AwsIotMqttConnectionBuilder} */ public AwsIotMqttConnectionBuilder withWebsocketProxyOptions(HttpProxyOptions proxyOptions) { this.config.setHttpProxyOptions(proxyOptions); return this; } /** * Configures any http proxy options to use * * @param proxyOptions http proxy options to use when establishing a connection * @return {@link AwsIotMqttConnectionBuilder} */ public AwsIotMqttConnectionBuilder withHttpProxyOptions(HttpProxyOptions proxyOptions) { this.config.setHttpProxyOptions(proxyOptions); return this; } /** * Configures the region to use when signing (via Sigv4) the websocket upgrade request. Only applicable * if the handshake transform is null (enabling the default sigv4 transform injection). * * @param region region to use when signing the websocket upgrade request * @return {@link AwsIotMqttConnectionBuilder} */ public AwsIotMqttConnectionBuilder withWebsocketSigningRegion(String region) { this.websocketSigningRegion = region; return this; } /** * Configures the credentials provider to use for websocket handshake signing. Only applicable to sigv4 * based authentication. If provider is null, the default provider chain will be used. * * @param provider credentials provider to pull Aws credentials from. * @return {@link AwsIotMqttConnectionBuilder} */ public AwsIotMqttConnectionBuilder withWebsocketCredentialsProvider(CredentialsProvider provider) { swapReferenceTo(this.websocketCredentialsProvider, provider); this.websocketCredentialsProvider = provider; return this; } /** * A helper function to add parameters to the username in the withCustomAuthorizer function */ private String addUsernameParameter(String inputString, String parameterValue, String parameterPreText, Boolean addedStringToUsername) { String return_string = inputString; if (addedStringToUsername == false) { return_string += "?"; } else { return_string += "&"; } if (parameterValue.contains(parameterPreText)) { return return_string + parameterValue; } else { return return_string + parameterPreText + parameterValue; } } /** * Configures the MQTT connection so it can use a custom authorizer. * This function will modify the username, port, and TLS options. * * @deprecated Please use the full withCustomAuthorizer function that includes `tokenKeyName` and * `tokenValue`. This version is left for backwards compatibility purposes. * * Note: All arguments are optional and can have "null" as valid input. * See the description for each argument for information on what happens if null is passed. * @param username The username to use with the custom authorizer. If null is passed, it will check to * see if a username has already been set (via withUsername function). If no username is set then * no username will be passed with the MQTT connection. * @param authorizerName The name of the custom authorizer. If null is passed, then 'x-amz-customauthorizer-name' * will not be added with the MQTT connection. * @param authorizerSignature The signature of the custom authorizer. * NOTE: This will NOT work without the token key name and token value, which requires * using the non-depreciated API. * @param password The password to use with the custom authorizer. If null is passed, then no password will be set. * @return {@link AwsIotMqttConnectionBuilder} */ public AwsIotMqttConnectionBuilder withCustomAuthorizer(String username, String authorizerName, String authorizerSignature, String password) { return this.withCustomAuthorizer(username, authorizerName, authorizerSignature, password, null, null); } /** * Configures the MQTT connection so it can use a custom authorizer. * This function will modify the username, port, and TLS options. * * Note: All arguments are optional and can have "null" as valid input. * See the description for each argument for information on what happens if null is passed. * @param username The username to use with the custom authorizer. If null is passed, it will check to * see if a username has already been set (via withUsername function). If no username is set then * no username will be passed with the MQTT connection. * @param authorizerName The name of the custom authorizer. If null is passed, then 'x-amz-customauthorizer-name' * will not be added with the MQTT connection. * @param authorizerSignature The signature of the custom authorizer. If null is passed, then * 'x-amz-customauthorizer-signature' will not be added with the MQTT connection. * The signature must be based on the private key associated with the custom authorizer. * The signature must be base64 encoded. Required if the custom authorizer has signing * enabled. It is strongly suggested to URL-encode this value; the SDK will not do * so for you. * @param password The password to use with the custom authorizer. If null is passed, then no password will be set. * @param tokenKeyName Key used to extract the custom authorizer token from MQTT username query-string properties. * Required if the custom authorizer has signing enabled. It is strongly suggested to URL-encode * this value; the SDK will not do so for you. * @param tokenValue An opaque token value. * Required if the custom authorizer has signing enabled. This value must be signed by the private * key associated with the custom authorizer and the result placed in the authorizerSignature argument. * @return {@link AwsIotMqttConnectionBuilder} */ public AwsIotMqttConnectionBuilder withCustomAuthorizer(String username, String authorizerName, String authorizerSignature, String password, String tokenKeyName, String tokenValue) { isUsingCustomAuthorizer = true; String usernameString = ""; Boolean addedStringToUsername = false; if (username == null) { if (config.getUsername() != null) { usernameString += config.getUsername(); } } else { usernameString += username; } if (authorizerName != null) { usernameString = addUsernameParameter(usernameString, authorizerName, "x-amz-customauthorizer-name=", addedStringToUsername); addedStringToUsername = true; } if (authorizerSignature != null) { usernameString = addUsernameParameter(usernameString, authorizerSignature, "x-amz-customauthorizer-signature=", addedStringToUsername); if (tokenKeyName == null || tokenValue == null) { Log.log( LogLevel.Warn, LogSubject.MqttClient, "Signed custom authorizers with signature will not work without a token key name and " + "token value. Your connection may be rejected/stalled on the IoT Core side due to this. Please " + "use the non-deprecate API and pass both the token key name and token value to connect to a " + "signed custom authorizer"); } } if (authorizerSignature != null || tokenKeyName != null || tokenValue != null) { if (tokenKeyName == null || tokenValue == null) { throw new RuntimeException("Token-based custom authentication requires all token-related properties to be set"); } usernameString = addUsernameParameter(usernameString, tokenValue, tokenKeyName + "=", addedStringToUsername); } config.setUsername(usernameString); if (password != null) { config.setPassword(password); } if (config.getUseWebsockets() == false) { tlsOptions.alpnList.clear(); tlsOptions.alpnList.add("mqtt"); } config.setPort(443); return this; } /** * Converts a AwsIotMqttConnectionBuilder to a AwsIotMqtt5ClientBuilder, converting as much as possible. * See AwsIotMqtt5ClientBuilder.newMqttBuilderFromMqtt311ConnectionConfig for more information on what can * be converted, the quirks, etc. * * @return A AwsIotMqtt5ClientBuilder using AwsIotMqttConnectionBuilder settings * @throws Exception If an unsupported option is present */ public AwsIotMqtt5ClientBuilder toAwsIotMqtt5ClientBuilder() throws Exception { return AwsIotMqtt5ClientBuilder.newMqttBuilderFromMqtt311ConnectionConfig(config, tlsOptions); } /** * Builds a new mqtt connection from the configuration stored in the builder. Because some objects are created * lazily, certain properties should not be modified after this is first invoked (tls options, bootstrap). * * @return a new mqtt connection */ public MqttClientConnection build() { // Validate if (bootstrap == null) { bootstrap = ClientBootstrap.getOrCreateStaticDefault(); } // Lazy create // This does mean that once you call build() once, modifying the tls context options or client bootstrap // has no affect on subsequently-created connections. synchronized(this) { // Check to see if a custom authorizer is being used but not through the builder. if (isUsingCustomAuthorizer == false) { if (config.getUsername() != null) { if (config.getUsername().contains("x-amz-customauthorizer-name=") || config.getUsername().contains("x-amz-customauthorizer-signature=")) { isUsingCustomAuthorizer = true; } } } // Is the user trying to connect using a custom authorizer? if (isUsingCustomAuthorizer == true) { if (config.getPort() != 443) { Log.log(LogLevel.Warn, LogSubject.MqttClient,"Attempting to connect to authorizer with unsupported port. Port is not 443..."); } if (config.getUseWebsockets() == false) { if (tlsOptions.alpnList.size() == 1) { if (tlsOptions.alpnList.get(0) != "mqtt") { tlsOptions.alpnList.clear(); tlsOptions.alpnList.add("mqtt"); } } else { tlsOptions.alpnList.clear(); tlsOptions.alpnList.add("mqtt"); } } } if (tlsOptions != null && (tlsContext == null || resetLazilyCreatedResources)) { try (ClientTlsContext clientTlsContext = new ClientTlsContext(tlsOptions)) { swapReferenceTo(tlsContext, clientTlsContext); tlsContext = clientTlsContext; } } if (client == null || resetLazilyCreatedResources) { try (MqttClient mqttClient = (tlsContext == null) ? new MqttClient(bootstrap) : new MqttClient(bootstrap, tlsContext)) { swapReferenceTo(client, mqttClient); client = mqttClient; config.setMqttClient(client); } } } resetLazilyCreatedResources = false; // Connection create try (MqttConnectionConfig connectionConfig = config.clone()) { // Whether or not a username has been added, append our metrics tokens String usernameOrEmpty = ""; if (connectionConfig.getUsername() != null) { usernameOrEmpty = connectionConfig.getUsername(); } String queryStringConcatenation = "?"; if (usernameOrEmpty.contains("?")) { queryStringConcatenation = "&"; } connectionConfig.setUsername(String.format("%s%sSDK=JavaV2&Version=%s", usernameOrEmpty, queryStringConcatenation, new PackageInfo().version.toString())); if (connectionConfig.getUseWebsockets() && connectionConfig.getWebsocketHandshakeTransform() == null) { if (websocketCredentialsProvider == null) { DefaultChainCredentialsProvider.DefaultChainCredentialsProviderBuilder providerBuilder = new DefaultChainCredentialsProvider.DefaultChainCredentialsProviderBuilder(); providerBuilder.withClientBootstrap(bootstrap); try (CredentialsProvider defaultProvider = providerBuilder.build()) { withWebsocketCredentialsProvider(defaultProvider); } } try (AwsSigningConfig signingConfig = new AwsSigningConfig()) { signingConfig.setAlgorithm(AwsSigningConfig.AwsSigningAlgorithm.SIGV4); signingConfig.setSignatureType(AwsSigningConfig.AwsSignatureType.HTTP_REQUEST_VIA_QUERY_PARAMS); signingConfig.setRegion(websocketSigningRegion); signingConfig.setService(IOT_SIGNING_SERVICE); signingConfig.setCredentialsProvider(websocketCredentialsProvider); signingConfig.setOmitSessionToken(true); try (AwsSigv4HandshakeTransformer transformer = new AwsSigv4HandshakeTransformer(signingConfig)) { connectionConfig.setWebsocketHandshakeTransform(transformer); /* * transformer is actually a CrtResource since we track a SigningConfig (which tracks a Credentials Provider * But the MqttConnectionConfig only knows of the transformer as a Consumer function, so it's not * able to properly add a forward reference to the transformer. So we do it manually here after setting. */ connectionConfig.addReferenceTo(transformer); } } } return new MqttClientConnection(connectionConfig); } } }
5,484
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/Timestamp.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package software.amazon.awssdk.iot; import com.google.gson.JsonParseException; import com.google.gson.JsonSerializer; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonPrimitive; import java.lang.reflect.Type; import java.util.Date; /** * Extension of Java date class to support Json serialization. Used in IoT service models. */ public class Timestamp extends java.util.Date { public static class Serializer implements JsonSerializer<Timestamp> { public JsonElement serialize(Timestamp src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src.getTime() / 1000); // convert from ms to seconds } } public static class Deserializer implements JsonDeserializer<Timestamp> { public Timestamp deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return new Timestamp(new Date(json.getAsJsonPrimitive().getAsLong() * 1000)); } } public Timestamp(Date date) { super(date.getTime()); } }
5,485
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/AwsIotMqtt5ClientBuilder.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package software.amazon.awssdk.iot; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import java.util.regex.Matcher; import java.util.regex.Pattern; import software.amazon.awssdk.crt.auth.credentials.CredentialsProvider; import software.amazon.awssdk.crt.auth.credentials.DefaultChainCredentialsProvider; import software.amazon.awssdk.crt.auth.signing.AwsSigningConfig; import software.amazon.awssdk.crt.auth.signing.AwsSigningConfig.AwsSignatureType; import software.amazon.awssdk.crt.auth.signing.AwsSigningConfig.AwsSigningAlgorithm; import software.amazon.awssdk.crt.http.HttpProxyOptions; import software.amazon.awssdk.crt.io.ClientBootstrap; import software.amazon.awssdk.crt.io.SocketOptions; import software.amazon.awssdk.crt.io.TlsContext; import software.amazon.awssdk.crt.io.TlsContextCustomKeyOperationOptions; import software.amazon.awssdk.crt.io.TlsContextOptions; import software.amazon.awssdk.crt.io.TlsContextPkcs11Options; import software.amazon.awssdk.crt.io.ExponentialBackoffRetryOptions.JitterMode; import software.amazon.awssdk.crt.mqtt.MqttConnectionConfig; import software.amazon.awssdk.crt.mqtt5.Mqtt5Client; import software.amazon.awssdk.crt.mqtt5.Mqtt5ClientOptions; import software.amazon.awssdk.crt.mqtt5.Mqtt5WebsocketHandshakeTransformArgs; import software.amazon.awssdk.crt.mqtt5.Mqtt5ClientOptions.Mqtt5ClientOptionsBuilder; import software.amazon.awssdk.crt.mqtt5.packets.ConnectPacket.ConnectPacketBuilder; import software.amazon.awssdk.crt.utils.PackageInfo; /** * Builders for making MQTT5 clients with different connection methods for AWS IoT Core. * * MQTT5 support is currently in <b>developer preview</b>. We encourage feedback at all times, but feedback during the * preview window is especially valuable in shaping the final product. During the preview period we may make * backwards-incompatible changes to the public API, but in general, this is something we will try our best to avoid. */ public class AwsIotMqtt5ClientBuilder extends software.amazon.awssdk.crt.CrtResource { private static Long DEFAULT_WEBSOCKET_MQTT_PORT = 443L; private static Long DEFAULT_DIRECT_MQTT_PORT = 8883L; private static Long DEFAULT_KEEP_ALIVE = 1200L; private Mqtt5ClientOptionsBuilder config; private ConnectPacketBuilder configConnect; private TlsContextOptions configTls; private MqttConnectCustomAuthConfig configCustomAuth; private AwsIotMqtt5ClientBuilder(String hostName, Long port, TlsContextOptions tlsContext) { config = new Mqtt5ClientOptionsBuilder(hostName, port); configTls = tlsContext; configConnect = new ConnectPacketBuilder(); configConnect.withKeepAliveIntervalSeconds(DEFAULT_KEEP_ALIVE); config.withExtendedValidationAndFlowControlOptions(Mqtt5ClientOptions.ExtendedValidationAndFlowControlOptions.AWS_IOT_CORE_DEFAULTS); addReferenceTo(configTls); } protected boolean canReleaseReferencesImmediately() { return true; } protected void releaseNativeHandle() {} /** * Creates a new MQTT5 client builder with mTLS file paths. * * @param hostName - AWS IoT endpoint to connect to * @param certificatePath - Path to certificate, in PEM format * @param privateKeyPath - Path to private key, in PEM format * @return - A new AwsIotMqtt5ClientBuilder */ public static AwsIotMqtt5ClientBuilder newDirectMqttBuilderWithMtlsFromPath(String hostName, String certificatePath, String privateKeyPath) { TlsContextOptions options = TlsContextOptions.createWithMtlsFromPath(certificatePath, privateKeyPath); AwsIotMqtt5ClientBuilder builder = new AwsIotMqtt5ClientBuilder(hostName, DEFAULT_DIRECT_MQTT_PORT, options); options.close(); if (TlsContextOptions.isAlpnSupported()) { builder.configTls.withAlpnList("x-amzn-mqtt-ca"); } return builder; } /** * Creates a new MQTT5 client builder with mTLS cert pair in memory * * @param hostName - AWS IoT endpoint to connect to * @param certificate - Certificate, in PEM format * @param privateKey - Private key, in PEM format * @return - A new AwsIotMqtt5ClientBuilder */ public static AwsIotMqtt5ClientBuilder newDirectMqttBuilderWithMtlsFromMemory(String hostName, String certificate, String privateKey) { TlsContextOptions options = TlsContextOptions.createWithMtls(certificate, privateKey); AwsIotMqtt5ClientBuilder builder = new AwsIotMqtt5ClientBuilder(hostName, DEFAULT_DIRECT_MQTT_PORT, options); options.close(); if (TlsContextOptions.isAlpnSupported()) { builder.configTls.withAlpnList("x-amzn-mqtt-ca"); } return builder; } /** * Creates a new MQTT5 client builder with mTLS using a PKCS#11 library for private key operations * * NOTE: This configuration only works on Unix devices. * * @param hostName - AWS IoT endpoint to connect to * @param pkcs11Options - PKCS#11 options * @return - A new AwsIotMqtt5ClientBuilder */ public static AwsIotMqtt5ClientBuilder newDirectMqttBuilderWithMtlsFromPkcs11(String hostName, TlsContextPkcs11Options pkcs11Options) { TlsContextOptions options = TlsContextOptions.createWithMtlsPkcs11(pkcs11Options); AwsIotMqtt5ClientBuilder builder = new AwsIotMqtt5ClientBuilder(hostName, DEFAULT_DIRECT_MQTT_PORT, options); options.close(); if (TlsContextOptions.isAlpnSupported()) { builder.configTls.withAlpnList("x-amzn-mqtt-ca"); } return builder; } /** * Creates a new MQTT5 client builder with mTLS using a custom handler for private key operations * * NOTE: This configuration only works on Unix devices. * * @param hostName - AWS IoT endpoint to connect to * @param operationOptions - Options for using a custom handler * @return - A new AwsIotMqtt5ClientBuilder */ public static AwsIotMqtt5ClientBuilder newDirectMtlsCustomKeyOperationsBuilder(String hostName, TlsContextCustomKeyOperationOptions operationOptions) { TlsContextOptions options = TlsContextOptions.createWithMtlsCustomKeyOperations(operationOptions); AwsIotMqtt5ClientBuilder builder = new AwsIotMqtt5ClientBuilder(hostName, DEFAULT_DIRECT_MQTT_PORT, options); options.close(); if (TlsContextOptions.isAlpnSupported()) { builder.configTls.withAlpnList("x-amzn-mqtt-ca"); } return builder; } /** * Creates a new MQTT5 client builder with mTLS using a certificate in a Windows certificate store. * * NOTE: This configuration only works on Windows devices. * * @param hostName - AWS IoT endpoint to connect to * @param certificatePath - Path to certificate in a Windows certificate store. * The path must use backslashes and end with the certificate's thumbprint. * Example: `CurrentUser\MY\A11F8A9B5DF5B98BA3508FBCA575D09570E0D2C6` * @return - A new AwsIotMqtt5ClientBuilder */ public static AwsIotMqtt5ClientBuilder newDirectMqttBuilderWithMtlsFromWindowsCertStorePath(String hostName, String certificatePath) { TlsContextOptions options = TlsContextOptions.createWithMtlsWindowsCertStorePath(certificatePath); AwsIotMqtt5ClientBuilder builder = new AwsIotMqtt5ClientBuilder(hostName, DEFAULT_DIRECT_MQTT_PORT, options); options.close(); if (TlsContextOptions.isAlpnSupported()) { builder.configTls.withAlpnList("x-amzn-mqtt-ca"); } return builder; } /** * Creates a new MQTT5 client builder that will use direct MQTT and a custom authenticator controlled by the * username and password values. * * @param hostName - AWS IoT endpoint to connect to * @param customAuthConfig - AWS IoT custom auth configuration * @return - A new AwsIotMqtt5ClientBuilder */ public static AwsIotMqtt5ClientBuilder newDirectMqttBuilderWithCustomAuth(String hostName, MqttConnectCustomAuthConfig customAuthConfig) { TlsContextOptions options = TlsContextOptions.createDefaultClient(); options.alpnList.clear(); options.alpnList.add("mqtt"); AwsIotMqtt5ClientBuilder builder = new AwsIotMqtt5ClientBuilder(hostName, DEFAULT_WEBSOCKET_MQTT_PORT, options); builder.configCustomAuth = customAuthConfig; options.close(); return builder; } /** * Create a new builder with mTLS, using a PKCS12 library for private key operations. * * NOTE: MacOS only * * @param hostName - AWS IoT endpoint to connect to * @param pkcs12Path Path to the PKCS12 file to use with the builder. * @param pkcs12Password The password of the PKCS12 file to use with the builder. * @return - A new AwsIotMqtt5ClientBuilder */ public static AwsIotMqtt5ClientBuilder newDirectMqttBuilderWithMtlsFromPkcs11(String hostName, String pkcs12Path, String pkcs12Password) { TlsContextOptions options = TlsContextOptions.createWithMtlsPkcs12(pkcs12Path, pkcs12Password); AwsIotMqtt5ClientBuilder builder = new AwsIotMqtt5ClientBuilder(hostName, DEFAULT_DIRECT_MQTT_PORT, options); options.close(); if (TlsContextOptions.isAlpnSupported()) { builder.configTls.withAlpnList("x-amzn-mqtt-ca"); } return builder; } /** * Create a new MQTT5 client builder that will use websockets and AWS Sigv4 signing to establish * mutually-authenticated (mTLS) connections. * * @param hostName - AWS IoT endpoint to connect to * @param config - Additional Sigv4-oriented options to use * @return - A new AwsIotMqtt5ClientBuilder */ public static AwsIotMqtt5ClientBuilder newWebsocketMqttBuilderWithSigv4Auth(String hostName, WebsocketSigv4Config config) { TlsContextOptions options = TlsContextOptions.createDefaultClient(); options.alpnList.clear(); AwsIotMqtt5ClientBuilder builder = new AwsIotMqtt5ClientBuilder(hostName, DEFAULT_WEBSOCKET_MQTT_PORT, options); options.close(); CredentialsProvider provider = null; if (config != null) { provider = config.credentialsProvider; } try (AwsSigningConfig signingConfig = new AwsSigningConfig()) { signingConfig.setAlgorithm(AwsSigningAlgorithm.SIGV4); signingConfig.setSignatureType(AwsSignatureType.HTTP_REQUEST_VIA_QUERY_PARAMS); if (provider != null) { signingConfig.setCredentialsProvider(provider); } else { DefaultChainCredentialsProvider.DefaultChainCredentialsProviderBuilder providerBuilder = new DefaultChainCredentialsProvider.DefaultChainCredentialsProviderBuilder(); providerBuilder.withClientBootstrap(ClientBootstrap.getOrCreateStaticDefault()); try (CredentialsProvider defaultProvider = providerBuilder.build()) { signingConfig.setCredentialsProvider(defaultProvider); } } if (config != null) { if (config.region != null) { signingConfig.setRegion(config.region); } else { signingConfig.setRegion(extractRegionFromEndpoint(hostName)); } } else { signingConfig.setRegion(extractRegionFromEndpoint(hostName)); } signingConfig.setService("iotdevicegateway"); signingConfig.setOmitSessionToken(true); // Needs to stay alive as long as the MQTT5 client, which we can allow by pinning // the resource to the signingConfig options.addReferenceTo(signingConfig); try (AwsMqtt5Sigv4HandshakeTransformer transformer = new AwsMqtt5Sigv4HandshakeTransformer(signingConfig)) { builder.config.withWebsocketHandshakeTransform(transformer); // Needs to stay alive as long as the MQTT5 client, which we can allow by pinning // the resource to the signingConfig options.addReferenceTo(transformer); } } catch (Exception ex) { System.out.println("Error - exception occurred while making Websocket Sigv4 builder: " + ex.toString()); ex.printStackTrace(); return null; } return builder; } /** * Creates a new MQTT5 client builder that will use websocket connection and a custom authenticator controlled by the * username and password values. * * @param hostName - AWS IoT endpoint to connect to * @param customAuthConfig - AWS IoT custom auth configuration * @return - A new AwsIotMqtt5ClientBuilder */ public static AwsIotMqtt5ClientBuilder newWebsocketMqttBuilderWithCustomAuth(String hostName, MqttConnectCustomAuthConfig customAuthConfig) { TlsContextOptions options = TlsContextOptions.createDefaultClient(); AwsIotMqtt5ClientBuilder builder = new AwsIotMqtt5ClientBuilder(hostName, DEFAULT_WEBSOCKET_MQTT_PORT, options); builder.configCustomAuth = customAuthConfig; options.close(); Consumer<Mqtt5WebsocketHandshakeTransformArgs> websocketTransform = new Consumer<Mqtt5WebsocketHandshakeTransformArgs>() { @Override public void accept(Mqtt5WebsocketHandshakeTransformArgs t) { t.complete(t.getHttpRequest()); } }; builder.config.withWebsocketHandshakeTransform(websocketTransform); return builder; } /** * Creates a new MQTT5 client builder using a certificate and key stored in the passed-in Java keystore. * * Note: This function assumes the passed-in keystore has already been loaded from a * file by calling <code>keystore.load(file, password)</code>. * * @param hostName AWS IoT endpoint to connect to * @param keyStore The Java keystore to use. Assumed to be loaded with certificates and keys * @param certificateAlias The alias of the certificate and key to use with the builder. * @param certificatePassword The password of the certificate and key to use with the builder. * @return A new AwsIotMqtt5ClientBuilder */ public static AwsIotMqtt5ClientBuilder newDirectMqttBuilderWithJavaKeystore( String hostName, java.security.KeyStore keyStore, String certificateAlias, String certificatePassword) { TlsContextOptions options = TlsContextOptions.createWithMtlsJavaKeystore(keyStore, certificateAlias, certificatePassword); AwsIotMqtt5ClientBuilder builder = new AwsIotMqtt5ClientBuilder(hostName, DEFAULT_DIRECT_MQTT_PORT, options); options.close(); if (TlsContextOptions.isAlpnSupported()) { builder.configTls.withAlpnList("x-amzn-mqtt-ca"); } return builder; } /** * Creates a new MQTT5 client builder with default TLS options. This requires setting all connection details manually. * Default port to direct MQTT. * * @param hostName - AWS IoT endpoint to connect to * @return - A new AwsIotMqtt5ClientBuilder */ public static AwsIotMqtt5ClientBuilder newMqttBuilder(String hostName) { TlsContextOptions options = TlsContextOptions.createDefaultClient(); AwsIotMqtt5ClientBuilder builder = new AwsIotMqtt5ClientBuilder(hostName, DEFAULT_DIRECT_MQTT_PORT, options); options.close(); if (TlsContextOptions.isAlpnSupported()) { builder.configTls.withAlpnList("x-amzn-mqtt-ca"); } return builder; } /** * Creates a new MQTT5 client builder using a MqttConnectionConfig. * * This does NOT support all MqttConnectionConfig options and will throw * an exception should it encounter options it does not support. * * Known unsupported options/cases: * <p>- <b>Custom Authorizer</b>: Will not be properly detected nor setup * <p>- <b>Websockets</b>: Is not supported and will throw an exception * <p>- <b>Will Message</b>: Is not supported and will throw an exception * <p>- <b>All Callbacks</b>: Connection callbacks are not supported and will be ignored * * @param mqtt311Config The MqttConnectionConfig to create a MQTT5 client builder from * @param tlsOptions The TLS options to use alongside the MqttConnectionConfig * @return A new AwsIotMqtt5ClientBuilder * @throws Exception If an unsupported option is passed */ public static AwsIotMqtt5ClientBuilder newMqttBuilderFromMqtt311ConnectionConfig(MqttConnectionConfig mqtt311Config, TlsContextOptions tlsOptions) throws Exception { if (mqtt311Config.getEndpoint() == null) { throw new Exception("MQTT311 to MQTT5 builder requires MQTT311 to have a endpoint set"); } if (tlsOptions == null) { throw new Exception("MQTT311 to MQTT5 builder requires MQTT311 to TLS options passed"); } AwsIotMqtt5ClientBuilder builder = new AwsIotMqtt5ClientBuilder(mqtt311Config.getEndpoint(), (long)mqtt311Config.getPort(), tlsOptions); if (tlsOptions.isAlpnSupported()) { builder.configTls.withAlpnList("x-amzn-mqtt-ca"); } if (mqtt311Config.getUseWebsockets() == true) { throw new Exception("MQTT311 to MQTT5 builder does not support MQTT311 websockets"); } if (mqtt311Config.getWillMessage() != null) { throw new Exception("MQTT311 to MQTT5 builder does not support MQTT311 Will messages"); } ConnectPacketBuilder connectPacket = new ConnectPacketBuilder(); if (mqtt311Config.getClientId() != null) { connectPacket.withClientId(mqtt311Config.getClientId()); } connectPacket.withKeepAliveIntervalSeconds((long)mqtt311Config.getKeepAliveSecs()); if (mqtt311Config.getUsername() != null) { connectPacket.withUsername(mqtt311Config.getUsername()); } if (mqtt311Config.getPassword() != null) { connectPacket.withPassword(mqtt311Config.getPassword().getBytes()); } builder.withConnectProperties(connectPacket); builder.withHttpProxyOptions(mqtt311Config.getHttpProxyOptions()); builder.withMaxReconnectDelayMs(mqtt311Config.getMaxReconnectTimeoutSecs() * 1000); // Seconds to milliseconds builder.withMinReconnectDelayMs(mqtt311Config.getMinReconnectTimeoutSecs() * 1000); // Seconds to milliseconds builder.withPingTimeoutMs((long)mqtt311Config.getPingTimeoutMs()); builder.withAckTimeoutSeconds((long)mqtt311Config.getProtocolOperationTimeoutMs() * 1000); // Seconds to milliseconds builder.withSocketOptions(mqtt311Config.getSocketOptions()); return builder; } /* Instance methods for various config overrides */ /** * Overrides the default system trust store. * * @param caDirPath - Only used on Unix-style systems where all trust anchors are * stored in a directory (e.g. /etc/ssl/certs). * @param caFilePath - Single file containing all trust CAs, in PEM format. * @return - The AwsIotMqtt5ClientBuilder */ public AwsIotMqtt5ClientBuilder withCertificateAuthorityFromPath(String caDirPath, String caFilePath) { this.configTls.overrideDefaultTrustStoreFromPath(caDirPath, caFilePath); return this; } /** * Overrides the default trust store. * * @param caRoot - Buffer containing all trust CAs, in PEM format. * @return - The AwsIotMqtt5ClientBuilder */ public AwsIotMqtt5ClientBuilder withCertificateAuthority(String caRoot) { this.configTls.overrideDefaultTrustStore(caRoot); return this; } /** * Overrides the port to connect to on the IoT endpoint * * @param port - The port to connect to on the IoT endpoint. Usually 8883 for MQTT, or 443 for websockets * @return - The AwsIotMqtt5ClientBuilder */ public AwsIotMqtt5ClientBuilder withPort(Long port) { this.config.withPort(port); return this; } /** * Overrides all configurable options with respect to the CONNECT packet sent by the client, including the will. * These connect properties will be used for every connection attempt made by the client. Custom authentication * configuration will override the username and password values in this configuration. * * @param connectPacket - All configurable options with respect to the CONNECT packet sent by the client * @return - The AwsIotMqtt5ClientBuilder */ public AwsIotMqtt5ClientBuilder withConnectProperties(ConnectPacketBuilder connectPacket) { this.configConnect = connectPacket; return this; } /** * Overrides how the MQTT5 client should behave with respect to MQTT sessions. * * @param sessionBehavior - How the MQTT5 client should behave with respect to MQTT sessions. * @return - The AwsIotMqtt5ClientBuilder */ public AwsIotMqtt5ClientBuilder withSessionBehavior(Mqtt5ClientOptions.ClientSessionBehavior sessionBehavior) { this.config.withSessionBehavior(sessionBehavior); return this; } /** * Overrides how the reconnect delay is modified in order to smooth out the distribution of reconnect attempt * time points for a large set of reconnecting clients. * * @param jitterMode - Controls how the reconnect delay is modified in order to smooth out the distribution * of reconnect attempt time points for a large set of reconnecting clients. * @return - The AwsIotMqtt5ClientBuilder */ public AwsIotMqtt5ClientBuilder withRetryJitterMode(JitterMode jitterMode) { this.config.withRetryJitterMode(jitterMode); return this; } /** * Overrides the minimum amount of time to wait to reconnect after a disconnect. Exponential back-off is * performed with controllable jitter after each connection failure. * * @param minReconnectDelayMs - Minimum amount of time to wait to reconnect after a disconnect. * @return - The AwsIotMqtt5ClientBuilder */ public AwsIotMqtt5ClientBuilder withMinReconnectDelayMs(Long minReconnectDelayMs) { this.config.withMinReconnectDelayMs(minReconnectDelayMs); return this; } /** * Overrides the maximum amount of time to wait to reconnect after a disconnect. Exponential back-off is * performed with controllable jitter after each connection failure. * * @param maxReconnectDelayMs - Maximum amount of time to wait to reconnect after a disconnect. * @return - The AwsIotMqtt5ClientBuilder */ public AwsIotMqtt5ClientBuilder withMaxReconnectDelayMs(Long maxReconnectDelayMs) { this.config.withMaxReconnectDelayMs(maxReconnectDelayMs); return this; } /** * Overrides the amount of time that must elapse with an established connection before the reconnect delay is * reset to the minimum. This helps alleviate bandwidth-waste in fast reconnect cycles due to permission * failures on operations. * * @param minConnectedTimeToResetReconnectDelayMs - The amount of time that must elapse with an established * connection before the reconnect delay is reset to the minimum. * @return - The AwsIotMqtt5ClientBuilder */ public AwsIotMqtt5ClientBuilder withMinConnectedTimeToResetReconnectDelayMs(Long minConnectedTimeToResetReconnectDelayMs) { this.config.withMinConnectedTimeToResetReconnectDelayMs(minConnectedTimeToResetReconnectDelayMs); return this; } /** * Overrides the time interval to wait after sending a CONNECT request for a CONNACK to arrive. If one does not * arrive, the connection will be shut down. * * @param connackTimeoutMs - The time interval to wait after sending a CONNECT request for a CONNACK to arrive. * @return - The AwsIotMqtt5ClientBuilder */ public AwsIotMqtt5ClientBuilder withConnackTimeoutMs(Long connackTimeoutMs) { this.config.withConnackTimeoutMs(connackTimeoutMs); return this; } /** * Overrides how disconnects affect the queued and in-progress operations tracked by the client. Also controls * how new operations are handled while the client is not connected. In particular, if the client is not connected, * then any operation that would be failed on disconnect (according to these rules) will also be rejected. * * @param offlineQueueBehavior - How disconnects affect the queued and in-progress operations tracked by the client. * @return - The AwsIotMqtt5ClientBuilder */ public AwsIotMqtt5ClientBuilder withOfflineQueueBehavior(Mqtt5ClientOptions.ClientOfflineQueueBehavior offlineQueueBehavior) { this.config.withOfflineQueueBehavior(offlineQueueBehavior); return this; } /** * Overrides the time interval to wait after sending a PINGREQ for a PINGRESP to arrive. If one does not arrive, * the client will close the current connection. * * @param pingTimeoutMs - The time interval to wait after sending a PINGREQ for a PINGRESP to arrive. * @return - The AwsIotMqtt5ClientBuilder */ public AwsIotMqtt5ClientBuilder withPingTimeoutMs(Long pingTimeoutMs) { this.config.withPingTimeoutMs(pingTimeoutMs); return this; } /** * Overrides the time interval to wait for an ack after sending a QoS 1+ PUBLISH, SUBSCRIBE, or UNSUBSCRIBE before * failing the operation. Defaults to no timeout. * * @param ackTimeoutSeconds - the time interval to wait for an ack after sending a QoS 1+ PUBLISH, SUBSCRIBE, * or UNSUBSCRIBE before failing the operation * @return - The AwsIotMqtt5ClientBuilder */ public AwsIotMqtt5ClientBuilder withAckTimeoutSeconds(Long ackTimeoutSeconds) { this.config.withAckTimeoutSeconds(ackTimeoutSeconds); return this; } /** * Overrides the socket properties of the underlying MQTT connections made by the client. Leave undefined to use * defaults (no TCP keep alive, 10 second socket timeout). * * @param socketOptions - The socket properties of the underlying MQTT connections made by the client * @return - The AwsIotMqtt5ClientBuilder */ public AwsIotMqtt5ClientBuilder withSocketOptions(SocketOptions socketOptions) { this.config.withSocketOptions(socketOptions); return this; } /** * Overrides (tunneling) HTTP proxy usage when establishing MQTT connections. * * @param httpProxyOptions - HTTP proxy options to use when establishing MQTT connections. * @return - The AwsIotMqtt5ClientBuilder */ public AwsIotMqtt5ClientBuilder withHttpProxyOptions(HttpProxyOptions httpProxyOptions) { this.config.withHttpProxyOptions(httpProxyOptions); return this; } /** * Overrides additional controls for client behavior with respect to operation validation and flow control; these * checks go beyond the base MQTT5 spec to respect limits of specific MQTT brokers. * * @param extendedValidationAndFlowControlOptions - additional controls for client behavior with respect to operation * validation and flow control * @return - The AwsIotMqtt5ClientBuilder */ public AwsIotMqtt5ClientBuilder withExtendedValidationAndFlowControlOptions(Mqtt5ClientOptions.ExtendedValidationAndFlowControlOptions extendedValidationAndFlowControlOptions) { this.config.withExtendedValidationAndFlowControlOptions(extendedValidationAndFlowControlOptions); return this; } /** * Sets the LifeCycleEvents that will be called by the client when receives a life cycle events. Examples of * life cycle events are: Connection success, connection failure, disconnection, etc. * * @param lifecycleEvents - The LifeCycleEvents to be called * @return - The AwsIotMqtt5ClientBuilder */ public AwsIotMqtt5ClientBuilder withLifeCycleEvents(Mqtt5ClientOptions.LifecycleEvents lifecycleEvents) { this.config.withLifecycleEvents(lifecycleEvents); return this; } /** * Sets the PublishEvents that will be called by the client when it receives a publish packet. * * @param publishEvents The PublishEvents to be called * @return - The AwsIotMqtt5ClientBuilder */ public AwsIotMqtt5ClientBuilder withPublishEvents(Mqtt5ClientOptions.PublishEvents publishEvents) { this.config.withPublishEvents(publishEvents); return this; } /** * Constructs an MQTT5 client object configured with the options set. * @return A MQTT5ClientOptions */ public Mqtt5Client build() { if (this.configTls == null) { this.configTls = TlsContextOptions.createDefaultClient(); addReferenceTo(this.configTls); this.configTls.close(); } TlsContext tlsContext = new TlsContext(this.configTls); this.config.withTlsContext(tlsContext); addReferenceTo(tlsContext); tlsContext.close(); try { this.configConnect.withUsername(buildMqtt5FinalUsername(this.configCustomAuth)); if (this.configCustomAuth != null) { if (this.configCustomAuth.password != null) { this.configConnect.withPassword(this.configCustomAuth.password); } } } catch (Exception ex) { System.out.println("Error - exception occurred while building MQTT5 client options builder: " + ex.toString()); ex.printStackTrace(); return null; } this.config.withConnectOptions(this.configConnect.build()); Mqtt5Client returnClient = new Mqtt5Client(this.config.build()); // Keep a reference to the TLS configuration so any possible Websockets-related CrtResources are kept alive returnClient.addReferenceTo(this.configTls); return returnClient; } /* Helper functions and structs */ /** * Websocket-specific MQTT5 connection AWS IoT configuration options */ public static final class WebsocketSigv4Config { /** * Sources the AWS Credentials used to sign the websocket connection handshake. If not provided, * the default credentials provider chain is used. */ public CredentialsProvider credentialsProvider; /** * The AWS region the websocket connection is being established in. Must match the region embedded in the * endpoint. If not provided, pattern-matching logic is used to extract the region from the endpoint. * Use this option if the pattern-matching logic has not yet been updated to handle new endpoint formats. */ public String region; } /** * Attempts to determine the AWS region associated with an endpoint. * Will throw an exception if it cannot find the region. * * @param endpoint - The endpoint to compute the region for. * @return The region associated with the endpoint. * @throws Exception When AWS region cannot be extracted from endpoint. */ public static String extractRegionFromEndpoint(String endpoint) throws Exception { Pattern regexPattern = Pattern.compile("^[\\w\\-]+\\.[\\w\\-]+\\.([\\w+\\-]+)\\."); Matcher regexMatcher = regexPattern.matcher(endpoint); try { if (regexMatcher.find()) { String result = regexMatcher.group(1); if (result != null) { return result; } } } catch (Exception ex) { throw new Exception("AWS region could not be extracted from endpoint. Use 'region' property on WebsocketConfig to set manually."); } throw new Exception("AWS region could not be extracted from endpoint. Use 'region' property on WebsocketConfig to set manually."); } /** * Configuration options specific to * <a href="https://docs.aws.amazon.com/iot/latest/developerguide/custom-authentication.html">AWS IoT Core custom authentication</a> * features. For clients constructed by an AwsIotMqtt5ClientBuilder, all parameters associated * with AWS IoT custom authentication are passed via the username and password properties in the CONNECT packet. */ public static final class MqttConnectCustomAuthConfig { /** * Name of the custom authorizer to use. * * Required if the endpoint does not have a default custom authorizer associated with it. * It is strongly suggested to URL-encode this value; the SDK will not do so for you. */ public String authorizerName; /** * The username to use with the custom authorizer. Query-string elements of this property value will be unioned * with the query-string elements implied by other properties in this object. * * For example, if you set this to: * * <code>{@literal MyUsername?someKey=someValue}</code> * * and use authorizerName to specify the authorizer, the final username would look like: * * <code>{@literal MyUsername?someKey=someValue&x-amz-customauthorizer-name=<your authorizer's name >&...}</code> */ public String username; /** * The password to use with the custom authorizer. Becomes the MQTT5 CONNECT packet's password property. * AWS IoT Core will base64 encode this binary data before passing it to the authorizer's lambda function. */ public byte[] password; /** * Key used to extract the custom authorizer token from MQTT username query-string properties. * * Required if the custom authorizer has signing enabled. It is strongly suggested to URL-encode this value; the * SDK will not do so for you. */ public String tokenKeyName; /** * An opaque token value. This value must be signed by the private key associated with the custom authorizer and * the result placed in the tokenSignature property. * * Required if the custom authorizer has signing enabled. */ public String tokenValue; /** * The digital signature of the token value in the tokenValue property. The signature must be based on * the private key associated with the custom authorizer. The signature must be base64 encoded. * * Required if the custom authorizer has signing enabled. It is strongly suggested to URL-encode this value; the * SDK will not do so for you. */ public String tokenSignature; } /** * Adds a username parameter to the given list. Will only add to the list if the paramValue is not null. * Always adds both values in pair. Set the key to null if you need to only add a single value. * * @param paramList The parameter list to use * @param paramName The new parameter name * @param paramValue The new parameter value */ private void addToUsernameParam(List<String> paramList, String paramName, String paramValue) { if (paramValue != null) { paramList.add(paramName); paramList.add(paramValue); } } /** * Takes a list of strings and returns a formatted username. Will correctly handle adding * <code>?</code> or <code>&</code> to append the strings together. * * Note: The paramList is expected to have either zero elements or an even amount. Will throw if uneven. * Will correctly handle if the parameter name is null but the parameter value is not null. * * @param paramList The parameter list to use for creating the username. * @return A string formatted from the parameter list. * @throws Exception When parameters cannot be added to username due to parameters list being uneven */ private String formUsernameFromParam(List<String> paramList) throws Exception { boolean firstAddition = true; boolean useAmp = false; String result = ""; // If there are no params, end early if (paramList.size() == 0) { return result; } // We only allow pairs, so make sure it is even if (paramList.size() % 2 != 0) { throw new Exception("Username parameters are not an even number!"); } for (int i = 0; i < paramList.size(); i++) { String key = paramList.get(i); String value = paramList.get(i+1); if (firstAddition == true) { firstAddition = false; } else { if (useAmp == false) { result += "?"; useAmp = true; } else { result += "&"; } } if (key != null && value != null) { result += key + "=" + value; } else if (value != null) { // Needed for the initial username and other value-only items result += value; } i = i+1; } return result; } /** * Builds the final value for the CONNECT packet's username property based on AWS IoT custom auth configuration * and SDK metrics properties. * * @param config - The intended AWS IoT custom auth client configuration (optional - leave null if not used) * @return The final username string */ private String buildMqtt5FinalUsername(MqttConnectCustomAuthConfig config) throws Exception { ArrayList<String> paramList = new ArrayList<String>(); if (config != null) { boolean usingSigning = false; if (config.tokenValue != null || config.tokenKeyName != null || config.tokenSignature != null) { usingSigning = true; if (config.tokenValue == null || config.tokenKeyName == null || config.tokenSignature == null) { throw new Exception("Token-based custom authentication requires all token-related properties to be set"); } } String username = config.username; if (username != null) { if (username.contains("?")) { // split and process String[] questionSplit = username.split("?"); if (questionSplit.length > 1) { throw new Exception("Custom auth username property value is invalid"); } else { // Add the username: addToUsernameParam(paramList, null, questionSplit[0]); // Is there multiple key-value pairs or just one? If multiple, split on the & if (questionSplit[1].contains("&")) { String[] ampSplit = questionSplit[1].split("&"); for (int i = 0; i < ampSplit.length; i++) { // We only want pairs String[] keyValueSplit = ampSplit[i].split("="); if (keyValueSplit.length == 1) { addToUsernameParam(paramList, keyValueSplit[0], keyValueSplit[1]); } } } else { // We only want pairs String[] keyValueSplit = questionSplit[1].split("="); if (keyValueSplit.length == 1) { addToUsernameParam(paramList, keyValueSplit[0], keyValueSplit[1]); } } } } else { addToUsernameParam(paramList, null, username); } } addToUsernameParam(paramList, "x-amz-customauthorizer-name", config.authorizerName); if (usingSigning == true) { addToUsernameParam(paramList, config.tokenKeyName, config.tokenValue); addToUsernameParam(paramList, "x-amz-customauthorizer-signature", config.tokenSignature); } } addToUsernameParam(paramList, "SDK", "JavaV2"); addToUsernameParam(paramList, "Version", new PackageInfo().version.toString()); return formUsernameFromParam(paramList); } }
5,486
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/AwsMqtt5Sigv4HandshakeTransformer.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package software.amazon.awssdk.iot; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.auth.signing.AwsSigner; import software.amazon.awssdk.crt.auth.signing.AwsSigningConfig; import software.amazon.awssdk.crt.http.HttpRequest; import software.amazon.awssdk.crt.mqtt5.Mqtt5WebsocketHandshakeTransformArgs; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; /** * A websocket handshake transformer that adds a sigv4 signature for the handshake to the request. * Required in order to connect to Aws IoT via websockets using sigv4 authentication. */ public class AwsMqtt5Sigv4HandshakeTransformer extends CrtResource implements Consumer<Mqtt5WebsocketHandshakeTransformArgs> { AwsSigningConfig signingConfig; /** * * @param signingConfig sigv4 configuration for the signing process */ public AwsMqtt5Sigv4HandshakeTransformer(AwsSigningConfig signingConfig) { addReferenceTo(signingConfig); this.signingConfig = signingConfig; } /** * Required override method that must begin the release process of the acquired native handle */ @Override protected void releaseNativeHandle() {} /** * Override that determines whether a resource releases its dependencies at the same time the native handle is released or if it waits. * Resources with asynchronous shutdown processes should override this with false, and establish a callback from native code that * invokes releaseReferences() when the asynchronous shutdown process has completed. See HttpClientConnectionManager for an example. */ @Override protected boolean canReleaseReferencesImmediately() { return true; } /** * Modifies the handshake request to include its sigv4 signature * @param handshakeArgs handshake transformation completion object */ public void accept(Mqtt5WebsocketHandshakeTransformArgs handshakeArgs) { try (AwsSigningConfig config = signingConfig.clone()) { config.setTime(System.currentTimeMillis()); CompletableFuture<HttpRequest> signingFuture = AwsSigner.signRequest(handshakeArgs.getHttpRequest(), config); signingFuture.whenComplete((HttpRequest request, Throwable error) -> { if (error != null) { handshakeArgs.completeExceptionally(error); } else { handshakeArgs.complete(request); }}); } } }
5,487
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/ShadowStateFactory.java
package software.amazon.awssdk.iot; import software.amazon.awssdk.iot.iotshadow.model.ShadowState; import java.io.IOException; import java.util.HashMap; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; public class ShadowStateFactory implements TypeAdapterFactory { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { Class<T> rawType = (Class<T>)type.getRawType(); if (rawType != ShadowState.class) { return null; } final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); return new TypeAdapter<T>() { public void write(JsonWriter out, T shadowValue) throws IOException { // Are null values present? If so, we need to process this differently ShadowState shadow = (ShadowState)shadowValue; if (shadow.desiredIsNullable == true || shadow.reportedIsNullable == true) { out.setSerializeNulls(true); // If a property is null but null is not valid for it, then just send an empty HashMap if (shadow.desired == null && shadow.desiredIsNullable == false) { shadow.desired = new HashMap<String, Object>(); } if (shadow.reported == null && shadow.reportedIsNullable == false) { shadow.reported = new HashMap<String, Object>(); } delegate.write(out, shadowValue); out.setSerializeNulls(false); } else { delegate.write(out, shadowValue); } } public T read(JsonReader in) throws IOException { T returnType = delegate.read(in); return returnType; } }; } }
5,488
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/EnumSerializer.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package software.amazon.awssdk.iot; import com.google.gson.JsonSerializer; import com.google.gson.JsonDeserializer; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonElement; import com.google.gson.JsonPrimitive; import com.google.gson.JsonParseException; import java.lang.reflect.Method; import java.lang.reflect.Type; /** * Custom JSON serializer for enumerated types within IoT service models * @param <E> the enumeration type the serializer should work with */ public class EnumSerializer<E> implements JsonSerializer<E>, JsonDeserializer<E> { public JsonElement serialize(E enumValue, Type typeOfEnum, JsonSerializationContext context) { return new JsonPrimitive(enumValue.toString()); } private Method fromString; public E deserialize(JsonElement json, Type typeOfEnum, JsonDeserializationContext context) throws JsonParseException { if (fromString == null) { Class<?> c = (Class<?>)typeOfEnum; for (Method m : c.getDeclaredMethods()) { if (m.getName() == "fromString") { fromString = m; fromString.setAccessible(true); break; } } } try { @SuppressWarnings("unchecked") E value = (E) fromString.invoke(null, json.getAsJsonPrimitive().getAsString()); return value; } catch (Exception ex) { @SuppressWarnings("unchecked") Class<E> c = (Class<E>)typeOfEnum; return c.getEnumConstants()[0]; } } }
5,489
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/AwsSigv4HandshakeTransformer.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package software.amazon.awssdk.iot; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.auth.signing.AwsSigner; import software.amazon.awssdk.crt.auth.signing.AwsSigningConfig; import software.amazon.awssdk.crt.http.HttpRequest; import software.amazon.awssdk.crt.mqtt.WebsocketHandshakeTransformArgs; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; /** * A websocket handshake transformer that adds a sigv4 signature for the handshake to the request. * Required in order to connect to Aws IoT via websockets using sigv4 authentication. */ public class AwsSigv4HandshakeTransformer extends CrtResource implements Consumer<WebsocketHandshakeTransformArgs> { AwsSigningConfig signingConfig; /** * * @param signingConfig sigv4 configuration for the signing process */ public AwsSigv4HandshakeTransformer(AwsSigningConfig signingConfig) { addReferenceTo(signingConfig); this.signingConfig = signingConfig; } /** * Required override method that must begin the release process of the acquired native handle */ @Override protected void releaseNativeHandle() {} /** * Override that determines whether a resource releases its dependencies at the same time the native handle is released or if it waits. * Resources with asynchronous shutdown processes should override this with false, and establish a callback from native code that * invokes releaseReferences() when the asynchronous shutdown process has completed. See HttpClientConnectionManager for an example. */ @Override protected boolean canReleaseReferencesImmediately() { return true; } /** * Modifies the handshake request to include its sigv4 signature * @param handshakeArgs handshake transformation completion object */ public void accept(WebsocketHandshakeTransformArgs handshakeArgs) { try (AwsSigningConfig config = signingConfig.clone()) { config.setTime(System.currentTimeMillis()); CompletableFuture<HttpRequest> signingFuture = AwsSigner.signRequest(handshakeArgs.getHttpRequest(), config); signingFuture.whenComplete((HttpRequest request, Throwable error) -> { if (error != null) { handshakeArgs.completeExceptionally(error); } else { handshakeArgs.complete(request); }}); } } }
5,490
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs/IotJobsClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.iot.iotjobs; import java.util.HashMap; import software.amazon.awssdk.iot.iotjobs.model.DescribeJobExecutionRequest; import software.amazon.awssdk.iot.iotjobs.model.DescribeJobExecutionResponse; import software.amazon.awssdk.iot.iotjobs.model.DescribeJobExecutionSubscriptionRequest; import software.amazon.awssdk.iot.iotjobs.model.GetPendingJobExecutionsRequest; import software.amazon.awssdk.iot.iotjobs.model.GetPendingJobExecutionsResponse; import software.amazon.awssdk.iot.iotjobs.model.GetPendingJobExecutionsSubscriptionRequest; import software.amazon.awssdk.iot.iotjobs.model.JobExecutionData; import software.amazon.awssdk.iot.iotjobs.model.JobExecutionState; import software.amazon.awssdk.iot.iotjobs.model.JobExecutionSummary; import software.amazon.awssdk.iot.iotjobs.model.JobExecutionsChangedEvent; import software.amazon.awssdk.iot.iotjobs.model.JobExecutionsChangedSubscriptionRequest; import software.amazon.awssdk.iot.iotjobs.model.JobStatus; import software.amazon.awssdk.iot.iotjobs.model.NextJobExecutionChangedEvent; import software.amazon.awssdk.iot.iotjobs.model.NextJobExecutionChangedSubscriptionRequest; import software.amazon.awssdk.iot.iotjobs.model.RejectedError; import software.amazon.awssdk.iot.iotjobs.model.RejectedErrorCode; import software.amazon.awssdk.iot.iotjobs.model.StartNextJobExecutionResponse; import software.amazon.awssdk.iot.iotjobs.model.StartNextPendingJobExecutionRequest; import software.amazon.awssdk.iot.iotjobs.model.StartNextPendingJobExecutionSubscriptionRequest; import software.amazon.awssdk.iot.iotjobs.model.UpdateJobExecutionRequest; import software.amazon.awssdk.iot.iotjobs.model.UpdateJobExecutionResponse; import software.amazon.awssdk.iot.iotjobs.model.UpdateJobExecutionSubscriptionRequest; import java.nio.charset.StandardCharsets; import software.amazon.awssdk.crt.mqtt.MqttClientConnection; import software.amazon.awssdk.crt.mqtt.QualityOfService; import software.amazon.awssdk.crt.mqtt.MqttException; import software.amazon.awssdk.crt.mqtt.MqttMessage; import software.amazon.awssdk.iot.Timestamp; import software.amazon.awssdk.iot.EnumSerializer; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; /** * The AWS IoT jobs service can be used to define a set of remote operations that are sent to and executed on one or more devices connected to AWS IoT. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#jobs-mqtt-api * */ public class IotJobsClient { private MqttClientConnection connection = null; private final Gson gson = getGson(); /** * Constructs a new IotJobsClient * @param connection The connection to use */ public IotJobsClient(MqttClientConnection connection) { this.connection = connection; } private Gson getGson() { GsonBuilder gson = new GsonBuilder(); gson.disableHtmlEscaping(); gson.registerTypeAdapter(Timestamp.class, new Timestamp.Serializer()); gson.registerTypeAdapter(Timestamp.class, new Timestamp.Deserializer()); addTypeAdapters(gson); return gson.create(); } private void addTypeAdapters(GsonBuilder gson) { gson.registerTypeAdapter(JobStatus.class, new EnumSerializer<JobStatus>()); gson.registerTypeAdapter(RejectedErrorCode.class, new EnumSerializer<RejectedErrorCode>()); } /** * Subscribes to JobExecutionsChanged notifications for a given IoT thing. * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-jobexecutionschanged * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * @param exceptionHandler callback function to invoke if an exception occurred deserializing a message * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToJobExecutionsChangedEvents( JobExecutionsChangedSubscriptionRequest request, QualityOfService qos, Consumer<JobExecutionsChangedEvent> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/jobs/notify"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("JobExecutionsChangedSubscriptionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); JobExecutionsChangedEvent response = gson.fromJson(payload, JobExecutionsChangedEvent.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * Subscribes to JobExecutionsChanged notifications for a given IoT thing. * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-jobexecutionschanged * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToJobExecutionsChangedEvents( JobExecutionsChangedSubscriptionRequest request, QualityOfService qos, Consumer<JobExecutionsChangedEvent> handler) { return SubscribeToJobExecutionsChangedEvents(request, qos, handler, null); } /** * Subscribes to the accepted topic for the StartNextPendingJobExecution operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-startnextpendingjobexecution * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * @param exceptionHandler callback function to invoke if an exception occurred deserializing a message * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToStartNextPendingJobExecutionAccepted( StartNextPendingJobExecutionSubscriptionRequest request, QualityOfService qos, Consumer<StartNextJobExecutionResponse> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/jobs/start-next/accepted"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("StartNextPendingJobExecutionSubscriptionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); StartNextJobExecutionResponse response = gson.fromJson(payload, StartNextJobExecutionResponse.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * Subscribes to the accepted topic for the StartNextPendingJobExecution operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-startnextpendingjobexecution * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToStartNextPendingJobExecutionAccepted( StartNextPendingJobExecutionSubscriptionRequest request, QualityOfService qos, Consumer<StartNextJobExecutionResponse> handler) { return SubscribeToStartNextPendingJobExecutionAccepted(request, qos, handler, null); } /** * Subscribes to the rejected topic for the DescribeJobExecution operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-describejobexecution * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * @param exceptionHandler callback function to invoke if an exception occurred deserializing a message * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToDescribeJobExecutionRejected( DescribeJobExecutionSubscriptionRequest request, QualityOfService qos, Consumer<RejectedError> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/jobs/{jobId}/get/rejected"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("DescribeJobExecutionSubscriptionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); if (request.jobId == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("DescribeJobExecutionSubscriptionRequest must have a non-null jobId")); return result; } topic = topic.replace("{jobId}", request.jobId); Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); RejectedError response = gson.fromJson(payload, RejectedError.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * Subscribes to the rejected topic for the DescribeJobExecution operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-describejobexecution * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToDescribeJobExecutionRejected( DescribeJobExecutionSubscriptionRequest request, QualityOfService qos, Consumer<RejectedError> handler) { return SubscribeToDescribeJobExecutionRejected(request, qos, handler, null); } /** * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-nextjobexecutionchanged * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * @param exceptionHandler callback function to invoke if an exception occurred deserializing a message * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToNextJobExecutionChangedEvents( NextJobExecutionChangedSubscriptionRequest request, QualityOfService qos, Consumer<NextJobExecutionChangedEvent> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/jobs/notify-next"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("NextJobExecutionChangedSubscriptionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); NextJobExecutionChangedEvent response = gson.fromJson(payload, NextJobExecutionChangedEvent.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-nextjobexecutionchanged * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToNextJobExecutionChangedEvents( NextJobExecutionChangedSubscriptionRequest request, QualityOfService qos, Consumer<NextJobExecutionChangedEvent> handler) { return SubscribeToNextJobExecutionChangedEvents(request, qos, handler, null); } /** * Subscribes to the rejected topic for the UpdateJobExecution operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-updatejobexecution * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * @param exceptionHandler callback function to invoke if an exception occurred deserializing a message * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToUpdateJobExecutionRejected( UpdateJobExecutionSubscriptionRequest request, QualityOfService qos, Consumer<RejectedError> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/jobs/{jobId}/update/rejected"; if (request.jobId == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("UpdateJobExecutionSubscriptionRequest must have a non-null jobId")); return result; } topic = topic.replace("{jobId}", request.jobId); if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("UpdateJobExecutionSubscriptionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); RejectedError response = gson.fromJson(payload, RejectedError.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * Subscribes to the rejected topic for the UpdateJobExecution operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-updatejobexecution * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToUpdateJobExecutionRejected( UpdateJobExecutionSubscriptionRequest request, QualityOfService qos, Consumer<RejectedError> handler) { return SubscribeToUpdateJobExecutionRejected(request, qos, handler, null); } /** * Subscribes to the accepted topic for the UpdateJobExecution operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-updatejobexecution * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * @param exceptionHandler callback function to invoke if an exception occurred deserializing a message * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToUpdateJobExecutionAccepted( UpdateJobExecutionSubscriptionRequest request, QualityOfService qos, Consumer<UpdateJobExecutionResponse> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/jobs/{jobId}/update/accepted"; if (request.jobId == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("UpdateJobExecutionSubscriptionRequest must have a non-null jobId")); return result; } topic = topic.replace("{jobId}", request.jobId); if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("UpdateJobExecutionSubscriptionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); UpdateJobExecutionResponse response = gson.fromJson(payload, UpdateJobExecutionResponse.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * Subscribes to the accepted topic for the UpdateJobExecution operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-updatejobexecution * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToUpdateJobExecutionAccepted( UpdateJobExecutionSubscriptionRequest request, QualityOfService qos, Consumer<UpdateJobExecutionResponse> handler) { return SubscribeToUpdateJobExecutionAccepted(request, qos, handler, null); } /** * Updates the status of a job execution. You can optionally create a step timer by setting a value for the stepTimeoutInMinutes property. If you don't update the value of this property by running UpdateJobExecution again, the job execution times out when the step timer expires. * * If the device is offline, the PUBLISH packet will be sent once the connection resumes. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-updatejobexecution * * @param request Message to be serialized and sent * @param qos Quality of Service for delivering this message * @return a future containing the MQTT packet id used to perform the publish operation * * * For QoS 0, completes as soon as the packet is sent. * * For QoS 1, completes when PUBACK is received. * * QoS 2 is not supported by AWS IoT. */ public CompletableFuture<Integer> PublishUpdateJobExecution( UpdateJobExecutionRequest request, QualityOfService qos) { String topic = "$aws/things/{thingName}/jobs/{jobId}/update"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("UpdateJobExecutionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); if (request.jobId == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("UpdateJobExecutionRequest must have a non-null jobId")); return result; } topic = topic.replace("{jobId}", request.jobId); String payloadJson = gson.toJson(request); MqttMessage message = new MqttMessage(topic, payloadJson.getBytes(StandardCharsets.UTF_8)); return connection.publish(message, qos, false); } /** * Subscribes to the accepted topic for the DescribeJobExecution operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-describejobexecution * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * @param exceptionHandler callback function to invoke if an exception occurred deserializing a message * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToDescribeJobExecutionAccepted( DescribeJobExecutionSubscriptionRequest request, QualityOfService qos, Consumer<DescribeJobExecutionResponse> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/jobs/{jobId}/get/accepted"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("DescribeJobExecutionSubscriptionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); if (request.jobId == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("DescribeJobExecutionSubscriptionRequest must have a non-null jobId")); return result; } topic = topic.replace("{jobId}", request.jobId); Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); DescribeJobExecutionResponse response = gson.fromJson(payload, DescribeJobExecutionResponse.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * Subscribes to the accepted topic for the DescribeJobExecution operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-describejobexecution * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToDescribeJobExecutionAccepted( DescribeJobExecutionSubscriptionRequest request, QualityOfService qos, Consumer<DescribeJobExecutionResponse> handler) { return SubscribeToDescribeJobExecutionAccepted(request, qos, handler, null); } /** * Gets the list of all jobs for a thing that are not in a terminal state. * * If the device is offline, the PUBLISH packet will be sent once the connection resumes. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-getpendingjobexecutions * * @param request Message to be serialized and sent * @param qos Quality of Service for delivering this message * @return a future containing the MQTT packet id used to perform the publish operation * * * For QoS 0, completes as soon as the packet is sent. * * For QoS 1, completes when PUBACK is received. * * QoS 2 is not supported by AWS IoT. */ public CompletableFuture<Integer> PublishGetPendingJobExecutions( GetPendingJobExecutionsRequest request, QualityOfService qos) { String topic = "$aws/things/{thingName}/jobs/get"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("GetPendingJobExecutionsRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); String payloadJson = gson.toJson(request); MqttMessage message = new MqttMessage(topic, payloadJson.getBytes(StandardCharsets.UTF_8)); return connection.publish(message, qos, false); } /** * Subscribes to the accepted topic for the GetPendingJobsExecutions operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-getpendingjobexecutions * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * @param exceptionHandler callback function to invoke if an exception occurred deserializing a message * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToGetPendingJobExecutionsAccepted( GetPendingJobExecutionsSubscriptionRequest request, QualityOfService qos, Consumer<GetPendingJobExecutionsResponse> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/jobs/get/accepted"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("GetPendingJobExecutionsSubscriptionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); GetPendingJobExecutionsResponse response = gson.fromJson(payload, GetPendingJobExecutionsResponse.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * Subscribes to the accepted topic for the GetPendingJobsExecutions operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-getpendingjobexecutions * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToGetPendingJobExecutionsAccepted( GetPendingJobExecutionsSubscriptionRequest request, QualityOfService qos, Consumer<GetPendingJobExecutionsResponse> handler) { return SubscribeToGetPendingJobExecutionsAccepted(request, qos, handler, null); } /** * Subscribes to the rejected topic for the StartNextPendingJobExecution operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-startnextpendingjobexecution * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * @param exceptionHandler callback function to invoke if an exception occurred deserializing a message * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToStartNextPendingJobExecutionRejected( StartNextPendingJobExecutionSubscriptionRequest request, QualityOfService qos, Consumer<RejectedError> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/jobs/start-next/rejected"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("StartNextPendingJobExecutionSubscriptionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); RejectedError response = gson.fromJson(payload, RejectedError.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * Subscribes to the rejected topic for the StartNextPendingJobExecution operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-startnextpendingjobexecution * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToStartNextPendingJobExecutionRejected( StartNextPendingJobExecutionSubscriptionRequest request, QualityOfService qos, Consumer<RejectedError> handler) { return SubscribeToStartNextPendingJobExecutionRejected(request, qos, handler, null); } /** * Subscribes to the rejected topic for the GetPendingJobsExecutions operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-getpendingjobexecutions * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * @param exceptionHandler callback function to invoke if an exception occurred deserializing a message * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToGetPendingJobExecutionsRejected( GetPendingJobExecutionsSubscriptionRequest request, QualityOfService qos, Consumer<RejectedError> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/jobs/get/rejected"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("GetPendingJobExecutionsSubscriptionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); RejectedError response = gson.fromJson(payload, RejectedError.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * Subscribes to the rejected topic for the GetPendingJobsExecutions operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-getpendingjobexecutions * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToGetPendingJobExecutionsRejected( GetPendingJobExecutionsSubscriptionRequest request, QualityOfService qos, Consumer<RejectedError> handler) { return SubscribeToGetPendingJobExecutionsRejected(request, qos, handler, null); } /** * Gets and starts the next pending job execution for a thing (status IN_PROGRESS or QUEUED). * * If the device is offline, the PUBLISH packet will be sent once the connection resumes. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-startnextpendingjobexecution * * @param request Message to be serialized and sent * @param qos Quality of Service for delivering this message * @return a future containing the MQTT packet id used to perform the publish operation * * * For QoS 0, completes as soon as the packet is sent. * * For QoS 1, completes when PUBACK is received. * * QoS 2 is not supported by AWS IoT. */ public CompletableFuture<Integer> PublishStartNextPendingJobExecution( StartNextPendingJobExecutionRequest request, QualityOfService qos) { String topic = "$aws/things/{thingName}/jobs/start-next"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("StartNextPendingJobExecutionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); String payloadJson = gson.toJson(request); MqttMessage message = new MqttMessage(topic, payloadJson.getBytes(StandardCharsets.UTF_8)); return connection.publish(message, qos, false); } /** * Gets detailed information about a job execution. * * If the device is offline, the PUBLISH packet will be sent once the connection resumes. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-describejobexecution * * @param request Message to be serialized and sent * @param qos Quality of Service for delivering this message * @return a future containing the MQTT packet id used to perform the publish operation * * * For QoS 0, completes as soon as the packet is sent. * * For QoS 1, completes when PUBACK is received. * * QoS 2 is not supported by AWS IoT. */ public CompletableFuture<Integer> PublishDescribeJobExecution( DescribeJobExecutionRequest request, QualityOfService qos) { String topic = "$aws/things/{thingName}/jobs/{jobId}/get"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("DescribeJobExecutionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); if (request.jobId == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("DescribeJobExecutionRequest must have a non-null jobId")); return result; } topic = topic.replace("{jobId}", request.jobId); String payloadJson = gson.toJson(request); MqttMessage message = new MqttMessage(topic, payloadJson.getBytes(StandardCharsets.UTF_8)); return connection.publish(message, qos, false); } }
5,491
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs/model/GetPendingJobExecutionsResponse.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.iot.iotjobs.model; import java.util.List; import software.amazon.awssdk.iot.Timestamp; import software.amazon.awssdk.iot.iotjobs.model.JobExecutionSummary; /** * Response payload to a GetPendingJobExecutions request. * */ public class GetPendingJobExecutionsResponse { /** * A list of JobExecutionSummary objects with status QUEUED. * */ public List<software.amazon.awssdk.iot.iotjobs.model.JobExecutionSummary> queuedJobs; /** * The time when the message was sent. * */ public Timestamp timestamp; /** * A client token used to correlate requests and responses. * */ public String clientToken; /** * A list of JobExecutionSummary objects with status IN_PROGRESS. * */ public List<software.amazon.awssdk.iot.iotjobs.model.JobExecutionSummary> inProgressJobs; }
5,492
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs/model/DescribeJobExecutionSubscriptionRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.iot.iotjobs.model; /** * Data needed to subscribe to DescribeJobExecution responses. * */ public class DescribeJobExecutionSubscriptionRequest { /** * Name of the IoT Thing that you want to subscribe to DescribeJobExecution response events for. * */ public String thingName; /** * Job ID that you want to subscribe to DescribeJobExecution response events for. * */ public String jobId; }
5,493
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs/model/JobExecutionData.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.iot.iotjobs.model; import java.util.HashMap; import software.amazon.awssdk.iot.Timestamp; import software.amazon.awssdk.iot.iotjobs.model.JobStatus; /** * Data about a job execution. * */ public class JobExecutionData { /** * The unique identifier you assigned to this job when it was created. * */ public String jobId; /** * The content of the job document. * */ public HashMap<String, Object> jobDocument; /** * The status of the job execution. Can be one of: QUEUED, IN_PROGRESS, FAILED, SUCCEEDED, CANCELED, TIMED_OUT, REJECTED, or REMOVED. * */ public JobStatus status; /** * The version of the job execution. Job execution versions are incremented each time they are updated by a device. * */ public Integer versionNumber; /** * The time when the job execution was enqueued. * */ public Timestamp queuedAt; /** * The name of the thing that is executing the job. * */ public String thingName; /** * A number that identifies a job execution on a device. It can be used later in commands that return or update job execution information. * */ public Long executionNumber; /** * A collection of name-value pairs that describe the status of the job execution. * */ public HashMap<String, String> statusDetails; /** * The time when the job execution started. * */ public Timestamp lastUpdatedAt; /** * The time when the job execution started. * */ public Timestamp startedAt; }
5,494
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs/model/DescribeJobExecutionRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.iot.iotjobs.model; /** * Data needed to make a DescribeJobExecution request. * */ public class DescribeJobExecutionRequest { /** * Optional. A number that identifies a job execution on a device. If not specified, the latest job execution is returned. * */ public Long executionNumber; /** * The name of the thing associated with the device. * */ public String thingName; /** * Optional. Unless set to false, the response contains the job document. The default is true. * */ public Boolean includeJobDocument; /** * The unique identifier assigned to this job when it was created. Or use $next to return the next pending job execution for a thing (status IN_PROGRESS or QUEUED). In this case, any job executions with status IN_PROGRESS are returned first. Job executions are returned in the order in which they were created. * */ public String jobId; /** * An opaque string used to correlate requests and responses. Enter an arbitrary value here and it is reflected in the response. * */ public String clientToken; }
5,495
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs/model/StartNextJobExecutionResponse.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.iot.iotjobs.model; import software.amazon.awssdk.iot.Timestamp; import software.amazon.awssdk.iot.iotjobs.model.JobExecutionData; /** * Response payload to a StartNextJobExecution request. * */ public class StartNextJobExecutionResponse { /** * A client token used to correlate requests and responses. * */ public String clientToken; /** * The time when the message was sent to the device. * */ public Timestamp timestamp; /** * Contains data about a job execution. * */ public JobExecutionData execution; }
5,496
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs/model/StartNextPendingJobExecutionSubscriptionRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.iot.iotjobs.model; /** * Data needed to subscribe to StartNextPendingJobExecution responses. * */ public class StartNextPendingJobExecutionSubscriptionRequest { /** * Name of the IoT Thing that you want to subscribe to StartNextPendingJobExecution response events for. * */ public String thingName; }
5,497
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs/model/RejectedErrorCode.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.iot.iotjobs.model; /** * A value indicating the kind of error encountered while processing an AWS IoT Jobs request * */ public enum RejectedErrorCode { /** * Enum value is an unknown value */ UNKNOWN_ENUM_VALUE("UNKNOWN_ENUM_VALUE"), /** * The request was sent to a topic in the AWS IoT Jobs namespace that does not map to any API. */ INVALID_TOPIC("InvalidTopic"), /** * An update attempted to change the job execution to a state that is invalid because of the job execution's current state. In this case, the body of the error message also contains the executionState field. */ INVALID_STATE_TRANSITION("InvalidStateTransition"), /** * The JobExecution specified by the request topic does not exist. */ RESOURCE_NOT_FOUND("ResourceNotFound"), /** * The contents of the request were invalid. The message contains details about the error. */ INVALID_REQUEST("InvalidRequest"), /** * The request was throttled. */ REQUEST_THROTTLED("RequestThrottled"), /** * There was an internal error during the processing of the request. */ INTERNAL_ERROR("InternalError"), /** * Occurs when a command to describe a job is performed on a job that is in a terminal state. */ TERMINAL_STATE_REACHED("TerminalStateReached"), /** * The contents of the request could not be interpreted as valid UTF-8-encoded JSON. */ INVALID_JSON("InvalidJson"), /** * The expected version specified in the request does not match the version of the job execution in the AWS IoT Jobs service. In this case, the body of the error message also contains the executionState field. */ VERSION_MISMATCH("VersionMismatch"); private String value; private RejectedErrorCode(String value) { this.value = value; } @Override public String toString() { return value; } /** * Returns The enum associated with the given string or UNKNOWN_ENUM_VALUE * if no enum is found. * @param val The string to use * @return The enum associated with the string or UNKNOWN_ENUM_VALUE */ static RejectedErrorCode fromString(String val) { for (RejectedErrorCode e : RejectedErrorCode.class.getEnumConstants()) { if (e.toString().compareTo(val) == 0) { return e; } } return UNKNOWN_ENUM_VALUE; } }
5,498
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs/model/JobExecutionState.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.iot.iotjobs.model; import java.util.HashMap; import software.amazon.awssdk.iot.iotjobs.model.JobStatus; /** * Data about the state of a job execution. * */ public class JobExecutionState { /** * A collection of name-value pairs that describe the status of the job execution. * */ public HashMap<String, String> statusDetails; /** * The version of the job execution. Job execution versions are incremented each time they are updated by a device. * */ public Integer versionNumber; /** * The status of the job execution. Can be one of: QUEUED, IN_PROGRESS, FAILED, SUCCEEDED, CANCELED, TIMED_OUT, REJECTED, or REMOVED. * */ public JobStatus status; }
5,499