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/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/JobExecutionSummary.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; /** * Contains a subset of information about a job execution. * */ public class JobExecutionSummary { /** * The time when the job execution was last updated. * */ public Timestamp lastUpdatedAt; /** * A number that identifies a job execution on a device. * */ public Long executionNumber; /** * The time when the job execution started. * */ public Timestamp startedAt; /** * The version of the job execution. Job execution versions are incremented each time the AWS IoT Jobs service receives an update from a device. * */ public Integer versionNumber; /** * The unique identifier you assigned to this job when it was created. * */ public String jobId; /** * The time when the job execution was enqueued. * */ public Timestamp queuedAt; }
5,500
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/GetPendingJobExecutionsSubscriptionRequest.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 GetPendingJobExecutions responses. * */ public class GetPendingJobExecutionsSubscriptionRequest { /** * Name of the IoT Thing that you want to subscribe to GetPendingJobExecutions response events for. * */ public String thingName; }
5,501
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/JobExecutionsChangedEvent.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; /** * Sent whenever a job execution is added to or removed from the list of pending job executions for a thing. * */ public class JobExecutionsChangedEvent { /** * Map from JobStatus to a list of Jobs transitioning to that status. * */ public HashMap<software.amazon.awssdk.iot.iotjobs.model.JobStatus, java.util.List<software.amazon.awssdk.iot.iotjobs.model.JobExecutionSummary>> jobs; /** * The time when the message was sent. * */ public Timestamp timestamp; }
5,502
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/GetPendingJobExecutionsRequest.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 GetPendingJobExecutions request. * */ public class GetPendingJobExecutionsRequest { /** * IoT Thing the request is relative to. * */ public String thingName; /** * Optional. A client token used to correlate requests and responses. Enter an arbitrary value here and it is reflected in the response. * */ public String clientToken; }
5,503
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/NextJobExecutionChangedSubscriptionRequest.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 NextJobExecutionChanged events. * */ public class NextJobExecutionChangedSubscriptionRequest { /** * Name of the IoT Thing that you want to subscribe to NextJobExecutionChanged events for. * */ public String thingName; }
5,504
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/StartNextPendingJobExecutionRequest.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; /** * Data needed to make a StartNextPendingJobExecution request. * */ public class StartNextPendingJobExecutionRequest { /** * IoT Thing the request is relative to. * */ public String thingName; /** * Specifies the amount of time this device has to finish execution of this job. * */ public Long stepTimeoutInMinutes; /** * Optional. A client token used to correlate requests and responses. Enter an arbitrary value here and it is reflected in the response. * */ public String clientToken; /** * A collection of name-value pairs that describe the status of the job execution. If not specified, the statusDetails are unchanged. * */ public HashMap<String, String> statusDetails; }
5,505
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/JobStatus.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; /** * The status of the job execution. * */ public enum JobStatus { /** * Enum value is an unknown value */ UNKNOWN_ENUM_VALUE("UNKNOWN_ENUM_VALUE"), /** * Enum value for IN_PROGRESS */ IN_PROGRESS("IN_PROGRESS"), /** * Enum value for FAILED */ FAILED("FAILED"), /** * Enum value for QUEUED */ QUEUED("QUEUED"), /** * Enum value for TIMED_OUT */ TIMED_OUT("TIMED_OUT"), /** * Enum value for SUCCEEDED */ SUCCEEDED("SUCCEEDED"), /** * Enum value for CANCELED */ CANCELED("CANCELED"), /** * Enum value for REJECTED */ REJECTED("REJECTED"), /** * Enum value for REMOVED */ REMOVED("REMOVED"); private String value; private JobStatus(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 JobStatus fromString(String val) { for (JobStatus e : JobStatus.class.getEnumConstants()) { if (e.toString().compareTo(val) == 0) { return e; } } return UNKNOWN_ENUM_VALUE; } }
5,506
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/DescribeJobExecutionResponse.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 DescribeJobExecution request. * */ public class DescribeJobExecutionResponse { /** * Contains data about a job execution. * */ public JobExecutionData execution; /** * A client token used to correlate requests and responses. * */ public String clientToken; /** * The time when the message was sent. * */ public Timestamp timestamp; }
5,507
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/RejectedError.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.JobExecutionState; import software.amazon.awssdk.iot.iotjobs.model.RejectedErrorCode; /** * Response document containing details about a failed request. * */ public class RejectedError { /** * The date and time the response was generated by AWS IoT. * */ public Timestamp timestamp; /** * Indicates the type of error. * */ public RejectedErrorCode code; /** * A text message that provides additional information. * */ public String message; /** * Opaque token that can correlate this response to the original request. * */ public String clientToken; /** * A JobExecutionState object. This field is included only when the code field has the value InvalidStateTransition or VersionMismatch. * */ public JobExecutionState executionState; }
5,508
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/UpdateJobExecutionRequest.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 needed to make an UpdateJobExecution request. * */ public class UpdateJobExecutionRequest { /** * The name of the thing associated with the device. * */ public String thingName; /** * Optional. A number that identifies a job execution on a device. If not specified, the latest job execution is used. * */ public Long executionNumber; /** * A collection of name-value pairs that describe the status of the job execution. If not specified, the statusDetails are unchanged. * */ public HashMap<String, String> statusDetails; /** * Optional. When included and set to true, the response contains the JobExecutionState field. The default is false. * */ public Boolean includeJobExecutionState; /** * The unique identifier assigned to this job when it was created. * */ public String jobId; /** * The expected current version of the job execution. Each time you update the job execution, its version is incremented. If the version of the job execution stored in the AWS IoT Jobs service does not match, the update is rejected with a VersionMismatch error, and an ErrorResponse that contains the current job execution status data is returned. * */ public Integer expectedVersion; /** * Optional. When included and set to true, the response contains the JobDocument. The default is false. * */ public Boolean includeJobDocument; /** * The new status for the job execution (IN_PROGRESS, FAILED, SUCCEEDED, or REJECTED). This must be specified on every update. * */ public JobStatus status; /** * Specifies the amount of time this device has to finish execution of this job. If the job execution status is not set to a terminal state before this timer expires, or before the timer is reset (by again calling UpdateJobExecution, setting the status to IN_PROGRESS and specifying a new timeout value in this field) the job execution status is set to TIMED_OUT. Setting or resetting this timeout has no effect on the job execution timeout that might have been specified when the job was created (by using CreateJob with the timeoutConfig). * */ public Long stepTimeoutInMinutes; /** * A client token used to correlate requests and responses. Enter an arbitrary value here and it is reflected in the response. * */ public String clientToken; }
5,509
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/NextJobExecutionChangedEvent.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; /** * Sent whenever there is a change to which job execution is next on the list of pending job executions for a thing, as defined for DescribeJobExecution with jobId $next. This message is not sent when the next job's execution details change, only when the next job that would be returned by DescribeJobExecution with jobId $next has changed. * */ public class NextJobExecutionChangedEvent { /** * Contains data about a job execution. * */ public JobExecutionData execution; /** * The time when the message was sent. * */ public Timestamp timestamp; }
5,510
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/UpdateJobExecutionSubscriptionRequest.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 UpdateJobExecution responses. * */ public class UpdateJobExecutionSubscriptionRequest { /** * Job ID that you want to subscribe to UpdateJobExecution response events for. * */ public String jobId; /** * Name of the IoT Thing that you want to subscribe to UpdateJobExecution response events for. * */ public String thingName; }
5,511
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/UpdateJobExecutionResponse.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.JobExecutionState; /** * Response payload to an UpdateJobExecution request. * */ public class UpdateJobExecutionResponse { /** * A client token used to correlate requests and responses. * */ public String clientToken; /** * The time when the message was sent. * */ public Timestamp timestamp; /** * A UTF-8 encoded JSON document that contains information that your devices need to perform the job. * */ public HashMap<String, Object> jobDocument; /** * Contains data about the state of a job execution. * */ public JobExecutionState executionState; }
5,512
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/JobExecutionsChangedSubscriptionRequest.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 JobExecutionsChanged events. * */ public class JobExecutionsChangedSubscriptionRequest { /** * Name of the IoT Thing that you want to subscribe to JobExecutionsChanged events for. * */ public String thingName; }
5,513
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/iotshadow/IotShadowClient.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.iotshadow; import java.util.HashMap; import software.amazon.awssdk.iot.iotshadow.model.DeleteNamedShadowRequest; import software.amazon.awssdk.iot.iotshadow.model.DeleteNamedShadowSubscriptionRequest; import software.amazon.awssdk.iot.iotshadow.model.DeleteShadowRequest; import software.amazon.awssdk.iot.iotshadow.model.DeleteShadowResponse; import software.amazon.awssdk.iot.iotshadow.model.DeleteShadowSubscriptionRequest; import software.amazon.awssdk.iot.iotshadow.model.ErrorResponse; import software.amazon.awssdk.iot.iotshadow.model.GetNamedShadowRequest; import software.amazon.awssdk.iot.iotshadow.model.GetNamedShadowSubscriptionRequest; import software.amazon.awssdk.iot.iotshadow.model.GetShadowRequest; import software.amazon.awssdk.iot.iotshadow.model.GetShadowResponse; import software.amazon.awssdk.iot.iotshadow.model.GetShadowSubscriptionRequest; import software.amazon.awssdk.iot.iotshadow.model.NamedShadowDeltaUpdatedSubscriptionRequest; import software.amazon.awssdk.iot.iotshadow.model.NamedShadowUpdatedSubscriptionRequest; import software.amazon.awssdk.iot.iotshadow.model.ShadowDeltaUpdatedEvent; import software.amazon.awssdk.iot.iotshadow.model.ShadowDeltaUpdatedSubscriptionRequest; import software.amazon.awssdk.iot.iotshadow.model.ShadowMetadata; import software.amazon.awssdk.iot.iotshadow.model.ShadowState; import software.amazon.awssdk.iot.iotshadow.model.ShadowStateWithDelta; import software.amazon.awssdk.iot.iotshadow.model.ShadowUpdatedEvent; import software.amazon.awssdk.iot.iotshadow.model.ShadowUpdatedSnapshot; import software.amazon.awssdk.iot.iotshadow.model.ShadowUpdatedSubscriptionRequest; import software.amazon.awssdk.iot.iotshadow.model.UpdateNamedShadowRequest; import software.amazon.awssdk.iot.iotshadow.model.UpdateNamedShadowSubscriptionRequest; import software.amazon.awssdk.iot.iotshadow.model.UpdateShadowRequest; import software.amazon.awssdk.iot.iotshadow.model.UpdateShadowResponse; import software.amazon.awssdk.iot.iotshadow.model.UpdateShadowSubscriptionRequest; 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 software.amazon.awssdk.iot.ShadowStateFactory; 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 Device Shadow service adds shadows to AWS IoT thing objects. Shadows are a simple data store for device properties and state. Shadows can make a device’s state available to apps and other services whether the device is connected to AWS IoT or not. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/device-shadow-mqtt.html * */ public class IotShadowClient { private MqttClientConnection connection = null; private final Gson gson = getGson(); /** * Constructs a new IotShadowClient * @param connection The connection to use */ public IotShadowClient(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) { ShadowStateFactory shadowStateFactory = new ShadowStateFactory(); gson.registerTypeAdapterFactory(shadowStateFactory); } /** * Subscribes to the rejected topic for the UpdateShadow 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/device-shadow-mqtt.html#update-rejected-pub-sub-topic * * @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> SubscribeToUpdateShadowRejected( UpdateShadowSubscriptionRequest request, QualityOfService qos, Consumer<ErrorResponse> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/shadow/update/rejected"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("UpdateShadowSubscriptionRequest 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); ErrorResponse response = gson.fromJson(payload, ErrorResponse.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 UpdateShadow 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/device-shadow-mqtt.html#update-rejected-pub-sub-topic * * @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> SubscribeToUpdateShadowRejected( UpdateShadowSubscriptionRequest request, QualityOfService qos, Consumer<ErrorResponse> handler) { return SubscribeToUpdateShadowRejected(request, qos, handler, null); } /** * Subscribe to ShadowDelta events for the (classic) shadow of an AWS 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/device-shadow-mqtt.html#update-delta-pub-sub-topic * * @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> SubscribeToShadowDeltaUpdatedEvents( ShadowDeltaUpdatedSubscriptionRequest request, QualityOfService qos, Consumer<ShadowDeltaUpdatedEvent> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/shadow/update/delta"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("ShadowDeltaUpdatedSubscriptionRequest 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); ShadowDeltaUpdatedEvent response = gson.fromJson(payload, ShadowDeltaUpdatedEvent.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * Subscribe to ShadowDelta events for the (classic) shadow of an AWS 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/device-shadow-mqtt.html#update-delta-pub-sub-topic * * @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> SubscribeToShadowDeltaUpdatedEvents( ShadowDeltaUpdatedSubscriptionRequest request, QualityOfService qos, Consumer<ShadowDeltaUpdatedEvent> handler) { return SubscribeToShadowDeltaUpdatedEvents(request, qos, handler, null); } /** * Subscribes to the rejected topic for the GetNamedShadow 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/device-shadow-mqtt.html#get-rejected-pub-sub-topic * * @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> SubscribeToGetNamedShadowRejected( GetNamedShadowSubscriptionRequest request, QualityOfService qos, Consumer<ErrorResponse> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/shadow/name/{shadowName}/get/rejected"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("GetNamedShadowSubscriptionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); if (request.shadowName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("GetNamedShadowSubscriptionRequest must have a non-null shadowName")); return result; } topic = topic.replace("{shadowName}", request.shadowName); Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); ErrorResponse response = gson.fromJson(payload, ErrorResponse.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 GetNamedShadow 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/device-shadow-mqtt.html#get-rejected-pub-sub-topic * * @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> SubscribeToGetNamedShadowRejected( GetNamedShadowSubscriptionRequest request, QualityOfService qos, Consumer<ErrorResponse> handler) { return SubscribeToGetNamedShadowRejected(request, qos, handler, null); } /** * Subscribes to the rejected topic for the DeleteNamedShadow 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/device-shadow-mqtt.html#delete-rejected-pub-sub-topic * * @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> SubscribeToDeleteNamedShadowRejected( DeleteNamedShadowSubscriptionRequest request, QualityOfService qos, Consumer<ErrorResponse> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/shadow/name/{shadowName}/delete/rejected"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("DeleteNamedShadowSubscriptionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); if (request.shadowName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("DeleteNamedShadowSubscriptionRequest must have a non-null shadowName")); return result; } topic = topic.replace("{shadowName}", request.shadowName); Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); ErrorResponse response = gson.fromJson(payload, ErrorResponse.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 DeleteNamedShadow 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/device-shadow-mqtt.html#delete-rejected-pub-sub-topic * * @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> SubscribeToDeleteNamedShadowRejected( DeleteNamedShadowSubscriptionRequest request, QualityOfService qos, Consumer<ErrorResponse> handler) { return SubscribeToDeleteNamedShadowRejected(request, qos, handler, null); } /** * Deletes the (classic) shadow for an AWS IoT thing. * * 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/device-shadow-mqtt.html#delete-pub-sub-topic * * @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> PublishDeleteShadow( DeleteShadowRequest request, QualityOfService qos) { String topic = "$aws/things/{thingName}/shadow/delete"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("DeleteShadowRequest 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 a named shadow for an AWS IoT thing. * * 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/device-shadow-mqtt.html#get-pub-sub-topic * * @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> PublishGetNamedShadow( GetNamedShadowRequest request, QualityOfService qos) { String topic = "$aws/things/{thingName}/shadow/name/{shadowName}/get"; if (request.shadowName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("GetNamedShadowRequest must have a non-null shadowName")); return result; } topic = topic.replace("{shadowName}", request.shadowName); if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("GetNamedShadowRequest 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 DeleteShadow 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/device-shadow-mqtt.html#delete-accepted-pub-sub-topic * * @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> SubscribeToDeleteShadowAccepted( DeleteShadowSubscriptionRequest request, QualityOfService qos, Consumer<DeleteShadowResponse> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/shadow/delete/accepted"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("DeleteShadowSubscriptionRequest 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); DeleteShadowResponse response = gson.fromJson(payload, DeleteShadowResponse.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 DeleteShadow 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/device-shadow-mqtt.html#delete-accepted-pub-sub-topic * * @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> SubscribeToDeleteShadowAccepted( DeleteShadowSubscriptionRequest request, QualityOfService qos, Consumer<DeleteShadowResponse> handler) { return SubscribeToDeleteShadowAccepted(request, qos, handler, null); } /** * Subscribes to the accepted topic for the GetShadow 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/device-shadow-mqtt.html#get-accepted-pub-sub-topic * * @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> SubscribeToGetShadowAccepted( GetShadowSubscriptionRequest request, QualityOfService qos, Consumer<GetShadowResponse> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/shadow/get/accepted"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("GetShadowSubscriptionRequest 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); GetShadowResponse response = gson.fromJson(payload, GetShadowResponse.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 GetShadow 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/device-shadow-mqtt.html#get-accepted-pub-sub-topic * * @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> SubscribeToGetShadowAccepted( GetShadowSubscriptionRequest request, QualityOfService qos, Consumer<GetShadowResponse> handler) { return SubscribeToGetShadowAccepted(request, qos, handler, null); } /** * Subscribes to the accepted topic for the GetNamedShadow 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/device-shadow-mqtt.html#get-accepted-pub-sub-topic * * @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> SubscribeToGetNamedShadowAccepted( GetNamedShadowSubscriptionRequest request, QualityOfService qos, Consumer<GetShadowResponse> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/shadow/name/{shadowName}/get/accepted"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("GetNamedShadowSubscriptionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); if (request.shadowName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("GetNamedShadowSubscriptionRequest must have a non-null shadowName")); return result; } topic = topic.replace("{shadowName}", request.shadowName); Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); GetShadowResponse response = gson.fromJson(payload, GetShadowResponse.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 GetNamedShadow 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/device-shadow-mqtt.html#get-accepted-pub-sub-topic * * @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> SubscribeToGetNamedShadowAccepted( GetNamedShadowSubscriptionRequest request, QualityOfService qos, Consumer<GetShadowResponse> handler) { return SubscribeToGetNamedShadowAccepted(request, qos, handler, null); } /** * Subscribe to ShadowUpdated events for a named shadow of an AWS 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/device-shadow-mqtt.html#update-documents-pub-sub-topic * * @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> SubscribeToNamedShadowUpdatedEvents( NamedShadowUpdatedSubscriptionRequest request, QualityOfService qos, Consumer<ShadowUpdatedEvent> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/shadow/name/{shadowName}/update/documents"; if (request.shadowName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("NamedShadowUpdatedSubscriptionRequest must have a non-null shadowName")); return result; } topic = topic.replace("{shadowName}", request.shadowName); if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("NamedShadowUpdatedSubscriptionRequest 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); ShadowUpdatedEvent response = gson.fromJson(payload, ShadowUpdatedEvent.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * Subscribe to ShadowUpdated events for a named shadow of an AWS 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/device-shadow-mqtt.html#update-documents-pub-sub-topic * * @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> SubscribeToNamedShadowUpdatedEvents( NamedShadowUpdatedSubscriptionRequest request, QualityOfService qos, Consumer<ShadowUpdatedEvent> handler) { return SubscribeToNamedShadowUpdatedEvents(request, qos, handler, null); } /** * Subscribe to ShadowUpdated events for the (classic) shadow of an AWS 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/device-shadow-mqtt.html#update-documents-pub-sub-topic * * @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> SubscribeToShadowUpdatedEvents( ShadowUpdatedSubscriptionRequest request, QualityOfService qos, Consumer<ShadowUpdatedEvent> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/shadow/update/documents"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("ShadowUpdatedSubscriptionRequest 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); ShadowUpdatedEvent response = gson.fromJson(payload, ShadowUpdatedEvent.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * Subscribe to ShadowUpdated events for the (classic) shadow of an AWS 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/device-shadow-mqtt.html#update-documents-pub-sub-topic * * @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> SubscribeToShadowUpdatedEvents( ShadowUpdatedSubscriptionRequest request, QualityOfService qos, Consumer<ShadowUpdatedEvent> handler) { return SubscribeToShadowUpdatedEvents(request, qos, handler, null); } /** * Deletes a named shadow for an AWS IoT thing. * * 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/device-shadow-mqtt.html#delete-pub-sub-topic * * @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> PublishDeleteNamedShadow( DeleteNamedShadowRequest request, QualityOfService qos) { String topic = "$aws/things/{thingName}/shadow/name/{shadowName}/delete"; if (request.shadowName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("DeleteNamedShadowRequest must have a non-null shadowName")); return result; } topic = topic.replace("{shadowName}", request.shadowName); if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("DeleteNamedShadowRequest 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 DeleteNamedShadow 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/device-shadow-mqtt.html#delete-accepted-pub-sub-topic * * @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> SubscribeToDeleteNamedShadowAccepted( DeleteNamedShadowSubscriptionRequest request, QualityOfService qos, Consumer<DeleteShadowResponse> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/shadow/name/{shadowName}/delete/accepted"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("DeleteNamedShadowSubscriptionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); if (request.shadowName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("DeleteNamedShadowSubscriptionRequest must have a non-null shadowName")); return result; } topic = topic.replace("{shadowName}", request.shadowName); Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); DeleteShadowResponse response = gson.fromJson(payload, DeleteShadowResponse.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 DeleteNamedShadow 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/device-shadow-mqtt.html#delete-accepted-pub-sub-topic * * @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> SubscribeToDeleteNamedShadowAccepted( DeleteNamedShadowSubscriptionRequest request, QualityOfService qos, Consumer<DeleteShadowResponse> handler) { return SubscribeToDeleteNamedShadowAccepted(request, qos, handler, null); } /** * Subscribes to the rejected topic for the DeleteShadow 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/device-shadow-mqtt.html#delete-rejected-pub-sub-topic * * @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> SubscribeToDeleteShadowRejected( DeleteShadowSubscriptionRequest request, QualityOfService qos, Consumer<ErrorResponse> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/shadow/delete/rejected"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("DeleteShadowSubscriptionRequest 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); ErrorResponse response = gson.fromJson(payload, ErrorResponse.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 DeleteShadow 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/device-shadow-mqtt.html#delete-rejected-pub-sub-topic * * @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> SubscribeToDeleteShadowRejected( DeleteShadowSubscriptionRequest request, QualityOfService qos, Consumer<ErrorResponse> handler) { return SubscribeToDeleteShadowRejected(request, qos, handler, null); } /** * Subscribes to the rejected topic for the GetShadow 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/device-shadow-mqtt.html#get-rejected-pub-sub-topic * * @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> SubscribeToGetShadowRejected( GetShadowSubscriptionRequest request, QualityOfService qos, Consumer<ErrorResponse> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/shadow/get/rejected"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("GetShadowSubscriptionRequest 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); ErrorResponse response = gson.fromJson(payload, ErrorResponse.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 GetShadow 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/device-shadow-mqtt.html#get-rejected-pub-sub-topic * * @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> SubscribeToGetShadowRejected( GetShadowSubscriptionRequest request, QualityOfService qos, Consumer<ErrorResponse> handler) { return SubscribeToGetShadowRejected(request, qos, handler, null); } /** * Update a device's (classic) shadow. * * 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/device-shadow-mqtt.html#update-pub-sub-topic * * @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> PublishUpdateShadow( UpdateShadowRequest request, QualityOfService qos) { String topic = "$aws/things/{thingName}/shadow/update"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("UpdateShadowRequest 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 the (classic) shadow for an AWS IoT thing. * * 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/device-shadow-mqtt.html#get-pub-sub-topic * * @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> PublishGetShadow( GetShadowRequest request, QualityOfService qos) { String topic = "$aws/things/{thingName}/shadow/get"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("GetShadowRequest 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 UpdateShadow 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/device-shadow-mqtt.html#update-accepted-pub-sub-topic * * @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> SubscribeToUpdateShadowAccepted( UpdateShadowSubscriptionRequest request, QualityOfService qos, Consumer<UpdateShadowResponse> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/shadow/update/accepted"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("UpdateShadowSubscriptionRequest 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); UpdateShadowResponse response = gson.fromJson(payload, UpdateShadowResponse.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 UpdateShadow 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/device-shadow-mqtt.html#update-accepted-pub-sub-topic * * @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> SubscribeToUpdateShadowAccepted( UpdateShadowSubscriptionRequest request, QualityOfService qos, Consumer<UpdateShadowResponse> handler) { return SubscribeToUpdateShadowAccepted(request, qos, handler, null); } /** * Subscribes to the rejected topic for the UpdateNamedShadow 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/device-shadow-mqtt.html#update-rejected-pub-sub-topic * * @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> SubscribeToUpdateNamedShadowRejected( UpdateNamedShadowSubscriptionRequest request, QualityOfService qos, Consumer<ErrorResponse> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/shadow/name/{shadowName}/update/rejected"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("UpdateNamedShadowSubscriptionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); if (request.shadowName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("UpdateNamedShadowSubscriptionRequest must have a non-null shadowName")); return result; } topic = topic.replace("{shadowName}", request.shadowName); Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); ErrorResponse response = gson.fromJson(payload, ErrorResponse.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 UpdateNamedShadow 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/device-shadow-mqtt.html#update-rejected-pub-sub-topic * * @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> SubscribeToUpdateNamedShadowRejected( UpdateNamedShadowSubscriptionRequest request, QualityOfService qos, Consumer<ErrorResponse> handler) { return SubscribeToUpdateNamedShadowRejected(request, qos, handler, null); } /** * Update a named shadow for a device. * * 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/device-shadow-mqtt.html#update-pub-sub-topic * * @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> PublishUpdateNamedShadow( UpdateNamedShadowRequest request, QualityOfService qos) { String topic = "$aws/things/{thingName}/shadow/name/{shadowName}/update"; if (request.shadowName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("UpdateNamedShadowRequest must have a non-null shadowName")); return result; } topic = topic.replace("{shadowName}", request.shadowName); if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("UpdateNamedShadowRequest 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); } /** * Subscribe to NamedShadowDelta events for a named shadow of an AWS 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/device-shadow-mqtt.html#update-delta-pub-sub-topic * * @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> SubscribeToNamedShadowDeltaUpdatedEvents( NamedShadowDeltaUpdatedSubscriptionRequest request, QualityOfService qos, Consumer<ShadowDeltaUpdatedEvent> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/shadow/name/{shadowName}/update/delta"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("NamedShadowDeltaUpdatedSubscriptionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); if (request.shadowName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("NamedShadowDeltaUpdatedSubscriptionRequest must have a non-null shadowName")); return result; } topic = topic.replace("{shadowName}", request.shadowName); Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); ShadowDeltaUpdatedEvent response = gson.fromJson(payload, ShadowDeltaUpdatedEvent.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * Subscribe to NamedShadowDelta events for a named shadow of an AWS 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/device-shadow-mqtt.html#update-delta-pub-sub-topic * * @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> SubscribeToNamedShadowDeltaUpdatedEvents( NamedShadowDeltaUpdatedSubscriptionRequest request, QualityOfService qos, Consumer<ShadowDeltaUpdatedEvent> handler) { return SubscribeToNamedShadowDeltaUpdatedEvents(request, qos, handler, null); } /** * Subscribes to the accepted topic for the UpdateNamedShadow 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/device-shadow-mqtt.html#update-accepted-pub-sub-topic * * @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> SubscribeToUpdateNamedShadowAccepted( UpdateNamedShadowSubscriptionRequest request, QualityOfService qos, Consumer<UpdateShadowResponse> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/shadow/name/{shadowName}/update/accepted"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("UpdateNamedShadowSubscriptionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); if (request.shadowName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("UpdateNamedShadowSubscriptionRequest must have a non-null shadowName")); return result; } topic = topic.replace("{shadowName}", request.shadowName); Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); UpdateShadowResponse response = gson.fromJson(payload, UpdateShadowResponse.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 UpdateNamedShadow 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/device-shadow-mqtt.html#update-accepted-pub-sub-topic * * @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> SubscribeToUpdateNamedShadowAccepted( UpdateNamedShadowSubscriptionRequest request, QualityOfService qos, Consumer<UpdateShadowResponse> handler) { return SubscribeToUpdateNamedShadowAccepted(request, qos, handler, null); } }
5,514
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow/model/NamedShadowUpdatedSubscriptionRequest.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.iotshadow.model; /** * Data needed to subscribe to a device's NamedShadowUpdated events. * */ public class NamedShadowUpdatedSubscriptionRequest { /** * Name of the shadow to get NamedShadowUpdated events for. * */ public String shadowName; /** * Name of the AWS IoT thing to get NamedShadowUpdated events for. * */ public String thingName; }
5,515
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow/model/ShadowUpdatedSnapshot.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.iotshadow.model; import software.amazon.awssdk.iot.iotshadow.model.ShadowMetadata; import software.amazon.awssdk.iot.iotshadow.model.ShadowState; /** * Complete state of the (classic) shadow of an AWS IoT Thing. * */ public class ShadowUpdatedSnapshot { /** * Current shadow state. * */ public ShadowState state; /** * Contains the timestamps for each attribute in the desired and reported sections of the state. * */ public ShadowMetadata metadata; /** * The current version of the document for the device's shadow. * */ public Integer version; }
5,516
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow/model/DeleteShadowResponse.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.iotshadow.model; import software.amazon.awssdk.iot.Timestamp; /** * Response payload to a DeleteShadow request. * */ public class DeleteShadowResponse { /** * The current version of the document for the device's shadow. * */ public Integer version; /** * A client token used to correlate requests and responses. * */ public String clientToken; /** * The time the response was generated by AWS IoT. * */ public Timestamp timestamp; }
5,517
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow/model/DeleteNamedShadowSubscriptionRequest.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.iotshadow.model; /** * Data needed to subscribe to DeleteNamedShadow responses for an AWS IoT thing. * */ public class DeleteNamedShadowSubscriptionRequest { /** * AWS IoT thing to subscribe to DeleteNamedShadow operations for. * */ public String thingName; /** * Name of the shadow to subscribe to DeleteNamedShadow operations for. * */ public String shadowName; }
5,518
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow/model/GetShadowRequest.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.iotshadow.model; /** * Data needed to make a GetShadow request. * */ public class GetShadowRequest { /** * AWS IoT thing to get the (classic) shadow for. * */ public String thingName; /** * Optional. A client token used to correlate requests and responses. Enter an arbitrary value here and it is reflected in the response. * */ public String clientToken; }
5,519
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow/model/GetNamedShadowSubscriptionRequest.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.iotshadow.model; /** * Data needed to subscribe to GetNamedShadow responses. * */ public class GetNamedShadowSubscriptionRequest { /** * AWS IoT thing subscribe to GetNamedShadow responses for. * */ public String thingName; /** * Name of the shadow to subscribe to GetNamedShadow responses for. * */ public String shadowName; }
5,520
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow/model/DeleteShadowSubscriptionRequest.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.iotshadow.model; /** * Data needed to subscribe to DeleteShadow responses for an AWS IoT thing. * */ public class DeleteShadowSubscriptionRequest { /** * AWS IoT thing to subscribe to DeleteShadow operations for. * */ public String thingName; }
5,521
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow/model/ShadowDeltaUpdatedSubscriptionRequest.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.iotshadow.model; /** * Data needed to subscribe to a device's ShadowDelta events. * */ public class ShadowDeltaUpdatedSubscriptionRequest { /** * Name of the AWS IoT thing to get ShadowDelta events for. * */ public String thingName; }
5,522
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow/model/DeleteShadowRequest.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.iotshadow.model; /** * Data needed to make a DeleteShadow request. * */ public class DeleteShadowRequest { /** * AWS IoT thing to delete the (classic) shadow of. * */ public String thingName; /** * Optional. A client token used to correlate requests and responses. Enter an arbitrary value here and it is reflected in the response. * */ public String clientToken; }
5,523
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow/model/DeleteNamedShadowRequest.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.iotshadow.model; /** * Data needed to make a DeleteNamedShadow request. * */ public class DeleteNamedShadowRequest { /** * Optional. A client token used to correlate requests and responses. Enter an arbitrary value here and it is reflected in the response. * */ public String clientToken; /** * Name of the shadow to delete. * */ public String shadowName; /** * AWS IoT thing to delete a named shadow from. * */ public String thingName; }
5,524
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow/model/UpdateShadowSubscriptionRequest.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.iotshadow.model; /** * Data needed to subscribe to UpdateShadow responses. * */ public class UpdateShadowSubscriptionRequest { /** * Name of the AWS IoT thing to listen to UpdateShadow responses for. * */ public String thingName; }
5,525
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow/model/GetShadowSubscriptionRequest.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.iotshadow.model; /** * Data needed to subscribe to GetShadow responses. * */ public class GetShadowSubscriptionRequest { /** * AWS IoT thing subscribe to GetShadow responses for. * */ public String thingName; }
5,526
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow/model/ShadowState.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.iotshadow.model; import java.util.HashMap; /** * (Potentially partial) state of an AWS IoT thing's shadow. * */ public class ShadowState { /** * The desired shadow state (from external services and devices). * */ public HashMap<String, Object> desired; /** * If set to true, then desired can be set to null. */ public transient boolean desiredIsNullable; /** * The (last) reported shadow state from the device. * */ public HashMap<String, Object> reported; /** * If set to true, then reported can be set to null. */ public transient boolean reportedIsNullable; }
5,527
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow/model/UpdateNamedShadowRequest.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.iotshadow.model; import software.amazon.awssdk.iot.iotshadow.model.ShadowState; /** * Data needed to make an UpdateNamedShadow request. * */ public class UpdateNamedShadowRequest { /** * Name of the shadow to update. * */ public String shadowName; /** * Optional. A client token used to correlate requests and responses. Enter an arbitrary value here and it is reflected in the response. * */ public String clientToken; /** * Aws IoT thing to update a named shadow of. * */ public String thingName; /** * Requested changes to shadow state. Updates affect only the fields specified. * */ public ShadowState state; /** * (Optional) The Device Shadow service applies the update only if the specified version matches the latest version. * */ public Integer version; }
5,528
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow/model/UpdateShadowRequest.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.iotshadow.model; import software.amazon.awssdk.iot.iotshadow.model.ShadowState; /** * Data needed to make an UpdateShadow request. * */ public class UpdateShadowRequest { /** * Requested changes to the shadow state. Updates affect only the fields specified. * */ public ShadowState state; /** * Aws IoT thing to update the (classic) shadow of. * */ public String thingName; /** * (Optional) The Device Shadow service processes the update only if the specified version matches the latest version. * */ public Integer version; /** * Optional. A client token used to correlate requests and responses. Enter an arbitrary value here and it is reflected in the response. * */ public String clientToken; }
5,529
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow/model/NamedShadowDeltaUpdatedSubscriptionRequest.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.iotshadow.model; /** * Data needed to subscribe to a device's NamedShadowDelta events. * */ public class NamedShadowDeltaUpdatedSubscriptionRequest { /** * Name of the AWS IoT thing to get NamedShadowDelta events for. * */ public String thingName; /** * Name of the shadow to get ShadowDelta events for. * */ public String shadowName; }
5,530
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow/model/ShadowUpdatedSubscriptionRequest.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.iotshadow.model; /** * Data needed to subscribe to a device's ShadowUpdated events. * */ public class ShadowUpdatedSubscriptionRequest { /** * Name of the AWS IoT thing to get ShadowUpdated events for. * */ public String thingName; }
5,531
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow/model/UpdateShadowResponse.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.iotshadow.model; import software.amazon.awssdk.iot.Timestamp; import software.amazon.awssdk.iot.iotshadow.model.ShadowMetadata; import software.amazon.awssdk.iot.iotshadow.model.ShadowState; /** * Response payload to an UpdateShadow request. * */ public class UpdateShadowResponse { /** * Updated device shadow state. * */ public ShadowState state; /** * An opaque token used to correlate requests and responses. Present only if a client token was used in the request. * */ public String clientToken; /** * The current version of the document for the device's shadow shared in AWS IoT. It is increased by one over the previous version of the document. * */ public Integer version; /** * Contains the timestamps for each attribute in the desired and reported sections so that you can determine when the state was updated. * */ public ShadowMetadata metadata; /** * The time the response was generated by AWS IoT. * */ public Timestamp timestamp; }
5,532
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow/model/UpdateNamedShadowSubscriptionRequest.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.iotshadow.model; /** * Data needed to subscribe to UpdateNamedShadow responses. * */ public class UpdateNamedShadowSubscriptionRequest { /** * Name of the AWS IoT thing to listen to UpdateNamedShadow responses for. * */ public String thingName; /** * Name of the shadow to listen to UpdateNamedShadow responses for. * */ public String shadowName; }
5,533
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow/model/ShadowUpdatedEvent.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.iotshadow.model; import software.amazon.awssdk.iot.Timestamp; import software.amazon.awssdk.iot.iotshadow.model.ShadowUpdatedSnapshot; /** * A description of the before and after states of a device shadow. * */ public class ShadowUpdatedEvent { /** * Contains the state of the object before the update. * */ public ShadowUpdatedSnapshot previous; /** * Contains the state of the object after the update. * */ public ShadowUpdatedSnapshot current; /** * The time the event was generated by AWS IoT. * */ public Timestamp timestamp; }
5,534
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow/model/ShadowStateWithDelta.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.iotshadow.model; import java.util.HashMap; /** * (Potentially partial) state of an AWS IoT thing's shadow. Includes the delta between the reported and desired states. * */ public class ShadowStateWithDelta { /** * The delta between the reported and desired states. * */ public HashMap<String, Object> delta; /** * The (last) reported shadow state from the device. * */ public HashMap<String, Object> reported; /** * The desired shadow state (from external services and devices). * */ public HashMap<String, Object> desired; }
5,535
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow/model/ErrorResponse.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.iotshadow.model; import software.amazon.awssdk.iot.Timestamp; /** * Response document containing details about a failed request. * */ public class ErrorResponse { /** * The date and time the response was generated by AWS IoT. This property is not present in all error response documents. * */ public Timestamp timestamp; /** * A text message that provides additional information. * */ public String message; /** * Opaque request-response correlation data. Present only if a client token was used in the request. * */ public String clientToken; /** * An HTTP response code that indicates the type of error. * */ public Integer code; }
5,536
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow/model/GetNamedShadowRequest.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.iotshadow.model; /** * Data needed to make a GetNamedShadow request. * */ public class GetNamedShadowRequest { /** * Optional. A client token used to correlate requests and responses. Enter an arbitrary value here and it is reflected in the response. * */ public String clientToken; /** * Name of the shadow to get. * */ public String shadowName; /** * AWS IoT thing to get the named shadow for. * */ public String thingName; }
5,537
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow/model/ShadowDeltaUpdatedEvent.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.iotshadow.model; import java.util.HashMap; import software.amazon.awssdk.iot.Timestamp; /** * An event generated when a shadow document was updated by a request to AWS IoT. The event payload contains only the changes requested. * */ public class ShadowDeltaUpdatedEvent { /** * An opaque token used to correlate requests and responses. Present only if a client token was used in the request. * */ public String clientToken; /** * The current version of the document for the device's shadow. * */ public Integer version; /** * The time the event was generated by AWS IoT. * */ public Timestamp timestamp; /** * Timestamps for the shadow properties that were updated. * */ public HashMap<String, Object> metadata; /** * Shadow properties that were updated. * */ public HashMap<String, Object> state; }
5,538
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow/model/GetShadowResponse.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.iotshadow.model; import software.amazon.awssdk.iot.Timestamp; import software.amazon.awssdk.iot.iotshadow.model.ShadowMetadata; import software.amazon.awssdk.iot.iotshadow.model.ShadowStateWithDelta; /** * Response payload to a GetShadow request. * */ public class GetShadowResponse { /** * The current version of the document for the device's shadow shared in AWS IoT. It is increased by one over the previous version of the document. * */ public Integer version; /** * An opaque token used to correlate requests and responses. * */ public String clientToken; /** * The (classic) shadow state of the AWS IoT thing. * */ public ShadowStateWithDelta state; /** * Contains the timestamps for each attribute in the desired and reported sections of the state. * */ public ShadowMetadata metadata; /** * The time the response was generated by AWS IoT. * */ public Timestamp timestamp; }
5,539
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotshadow/model/ShadowMetadata.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.iotshadow.model; import java.util.HashMap; /** * Contains the last-updated timestamps for each attribute in the desired and reported sections of the shadow state. * */ public class ShadowMetadata { /** * Contains the timestamps for each attribute in the desired section of a shadow's state. * */ public HashMap<String, Object> desired; /** * Contains the timestamps for each attribute in the reported section of a shadow's state. * */ public HashMap<String, Object> reported; }
5,540
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/discovery/DiscoveryClientConfig.java
package software.amazon.awssdk.iot.discovery; import java.util.concurrent.ExecutorService; 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.TlsContextOptions; /** * Configuration object for the Greengrass discovery client */ public class DiscoveryClientConfig implements AutoCloseable { final private ClientBootstrap bootstrap; final private TlsContext tlsContext; final private SocketOptions socketOptions; final private String region; final private int maxConnections; final private HttpProxyOptions proxyOptions; final private String ggServerName; private ExecutorService discoveryExecutor; /** * Constructor for DiscoveryClientConfig creates the correct endpoint if not in a special region * * @param bootstrap client bootstrap to use to establish network connections * @param tlsContextOptions tls configuration for client network connections. For greengrass discovery, the * tls context must be initialized with the certificate and private key of the * device/thing that is querying greengrass core availability. * @param socketOptions socket configuration for client network connections * @param region AWS region to query for greengrass information * @param maxConnections maximum concurrent http connections within the client * @param proxyOptions proxy configuration for client network connections */ public DiscoveryClientConfig( final ClientBootstrap bootstrap, final TlsContextOptions tlsContextOptions, final SocketOptions socketOptions, final String region, final int maxConnections, final HttpProxyOptions proxyOptions) { this.bootstrap = bootstrap; this.tlsContext = new TlsContext(tlsContextOptions); this.socketOptions = socketOptions; this.region = region; this.maxConnections = maxConnections; this.proxyOptions = proxyOptions; this.ggServerName = ""; this.discoveryExecutor = null; } /** * Constructor for DiscoveryClientConfig creates the correct endpoint if not in a special region using * the default static bootstrap. * * @param tlsContextOptions tls configuration for client network connections. For greengrass discovery, the * tls context must be initialized with the certificate and private key of the * device/thing that is querying greengrass core availability. * @param socketOptions socket configuration for client network connections * @param region AWS region to query for greengrass information * @param maxConnections maximum concurrent http connections within the client * @param proxyOptions proxy configuration for client network connections */ public DiscoveryClientConfig( final TlsContextOptions tlsContextOptions, final SocketOptions socketOptions, final String region, final int maxConnections, final HttpProxyOptions proxyOptions) { this(ClientBootstrap.getOrCreateStaticDefault(), tlsContextOptions, socketOptions, region, maxConnections, proxyOptions); } /** * Default Constructor for DiscoveryClientConfig that allows the specification of a specific ggServerName to use in special regions * * @param bootstrap client bootstrap to use to establish network connections * @param tlsContextOptions tls configuration for client network connections. For greengrass discovery, the * tls context must be initialized with the certificate and private key of the * device/thing that is querying greengrass core availability. * @param socketOptions socket configuration for client network connections * @param maxConnections maximum concurrent http connections within the client * @param proxyOptions proxy configuration for client network connections * @param ggServerName full endpoint to use when connecting in special regions */ public DiscoveryClientConfig( final ClientBootstrap bootstrap, final TlsContextOptions tlsContextOptions, final SocketOptions socketOptions, final int maxConnections, final HttpProxyOptions proxyOptions, final String ggServerName) { this.bootstrap = bootstrap; this.tlsContext = new TlsContext(tlsContextOptions); this.socketOptions = socketOptions; this.region = ""; this.maxConnections = maxConnections; this.proxyOptions = proxyOptions; this.ggServerName = ggServerName; this.discoveryExecutor = null; } /** * Default Constructor for DiscoveryClientConfig that allows the specification of a specific ggServerName to use in special regions * using the static default client bootstrap. * * @param tlsContextOptions tls configuration for client network connections. For greengrass discovery, the * tls context must be initialized with the certificate and private key of the * device/thing that is querying greengrass core availability. * @param socketOptions socket configuration for client network connections * @param maxConnections maximum concurrent http connections within the client * @param proxyOptions proxy configuration for client network connections * @param ggServerName full endpoint to use when connecting in special regions */ public DiscoveryClientConfig( final TlsContextOptions tlsContextOptions, final SocketOptions socketOptions, final int maxConnections, final HttpProxyOptions proxyOptions, final String ggServerName) { this(ClientBootstrap.getOrCreateStaticDefault(), tlsContextOptions, socketOptions, maxConnections, proxyOptions, ggServerName); } /** * @return client bootstrap to use to establish network connections */ public ClientBootstrap getBootstrap() { return bootstrap; } /** * @return tls configuration for client network connections */ public TlsContext getTlsContext() { return tlsContext; } /** * @return socket configuration for client network connections */ public SocketOptions getSocketOptions() { return socketOptions; } /** * @return AWS region to query for greengrass information */ public String getRegion() { return region; } /** * @return maximum concurrent http connections within the client */ public int getMaxConnections() { return maxConnections; } /** * @return proxy configuration for client network connections */ public HttpProxyOptions getProxyOptions() { return proxyOptions; } public String getGGServerName() { return ggServerName; } /** * @return the ExecutorService set for this discover client config. Returns null if one hasn't been set. */ public ExecutorService getDiscoveryExecutor() { return this.discoveryExecutor; } /** * Sets the executor that is used when calling discover(). * If set using this function, you are expected to close/shutdown the executor when finished with it. * * If it is not set, the discovery client will internally manage its own executor. * * @param override The executor to use * @return The client config */ public DiscoveryClientConfig setDiscoveryExecutor(ExecutorService override) { this.discoveryExecutor = override; return this; } @Override public void close() { if(tlsContext != null) { tlsContext.close(); } } }
5,541
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/discovery/DiscoveryClient.java
package software.amazon.awssdk.iot.discovery; import com.google.gson.Gson; import software.amazon.awssdk.crt.http.*; import software.amazon.awssdk.crt.io.*; import software.amazon.awssdk.iot.discovery.model.DiscoverResponse; import java.io.StringReader; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * Class for performing network-based discovery of the connectivity properties of registered greengrass cores * associated with an AWS account and region. */ public class DiscoveryClient implements AutoCloseable { public static final String TLS_EXT_ALPN = "x-amzn-http-ca"; private static final String HTTP_HEADER_REQUEST_ID = "x-amzn-RequestId"; private static final String HTTP_HEADER_ERROR_TYPE = "x-amzn-ErrorType"; private static final String AWS_DOMAIN_DEFAULT = "amazonaws.com"; private static final Map<String, String> AWS_DOMAIN_SUFFIX_MAP = new HashMap<>(); static { AWS_DOMAIN_SUFFIX_MAP.put("cn-north-1", "amazonaws.com.cn"); AWS_DOMAIN_SUFFIX_MAP.put("cn-northwest-1", "amazonaws.com.cn"); AWS_DOMAIN_SUFFIX_MAP.put("us-isob-east-1", "sc2s.sgov.gov"); AWS_DOMAIN_SUFFIX_MAP.put("us-iso-east-1", "c2s.ic.gov"); } private static final Gson GSON = new Gson(); private final HttpClientConnectionManager httpClientConnectionManager; /** * We need to use a code defined executor to avoid leaving threads alive when the discovery client is closed * It also fixes issues with the SecurityManager as well - as created ExecutorServices created via code * inherit the permissions of the application, unlike the default common thread pool that is used by default * with supplyAsync otherwise. */ private ExecutorService executorService = null; private boolean cleanExecutor = false; /** * * @param config Greengrass discovery client configuration */ public DiscoveryClient(final DiscoveryClientConfig config) { executorService = config.getDiscoveryExecutor(); if (executorService == null) { // If an executor is not set, then create one and make sure to clean it when finished. executorService = Executors.newFixedThreadPool(1); cleanExecutor = true; } httpClientConnectionManager = HttpClientConnectionManager.create( new HttpClientConnectionManagerOptions() .withClientBootstrap(config.getBootstrap()) .withProxyOptions(config.getProxyOptions()) .withSocketOptions(config.getSocketOptions()) .withMaxConnections(config.getMaxConnections()) .withTlsContext(config.getTlsContext()) .withUri(URI.create("https://" + getHostname(config))) .withPort(TlsContextOptions.isAlpnSupported() ? 443 : 8443)); } /** * Based on configuration, make an http request to query connectivity information about available Greengrass cores * @param thingName name of the thing/device making the greengrass core query * @return future holding connectivity information about greengrass cores available to the device/thing */ public CompletableFuture<DiscoverResponse> discover(final String thingName) { if(thingName == null) { throw new IllegalArgumentException("ThingName cannot be null!"); } return CompletableFuture.supplyAsync(() -> { try(final HttpClientConnection connection = httpClientConnectionManager.acquireConnection().get()) { final String requestHttpPath = "/greengrass/discover/thing/" + thingName; final HttpHeader[] headers = new HttpHeader[] { new HttpHeader("host", httpClientConnectionManager.getUri().getHost()) }; final HttpRequest request = new HttpRequest("GET", requestHttpPath, headers, null); //we are storing everything until we get the entire response final CompletableFuture<Integer> responseComplete = new CompletableFuture<>(); final StringBuilder jsonBodyResponseBuilder = new StringBuilder(); final Map<String, String> responseInfo = new HashMap<>(); try(final HttpStream stream = connection.makeRequest(request, new HttpStreamResponseHandler() { @Override public void onResponseHeaders(HttpStream stream, int responseStatusCode, int blockType, HttpHeader[] httpHeaders) { Arrays.stream(httpHeaders).forEach(header -> { responseInfo.put(header.getName(), header.getValue()); }); } @Override public int onResponseBody(HttpStream stream, byte bodyBytes[]) { jsonBodyResponseBuilder.append(new String(bodyBytes, StandardCharsets.UTF_8)); return bodyBytes.length; } @Override public void onResponseComplete(HttpStream httpStream, int errorCode) { responseComplete.complete(errorCode); }})) { stream.activate(); responseComplete.get(); if (stream.getResponseStatusCode() != 200) { throw new RuntimeException(String.format("Error %s(%d); RequestId: %s", HTTP_HEADER_ERROR_TYPE, stream.getResponseStatusCode(), HTTP_HEADER_REQUEST_ID)); } final String responseString = jsonBodyResponseBuilder.toString(); return GSON.fromJson(new StringReader(responseString), DiscoverResponse.class); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } catch(InterruptedException | ExecutionException e) { throw new RuntimeException(e.getMessage(), e); } }, executorService); } private static String getHostname(final DiscoveryClientConfig config) { //allow greengrass server endpoint to be manually set for unique endpoints if (config.getGGServerName().equals("")) { return String.format("greengrass-ats.iot.%s.%s", config.getRegion(), AWS_DOMAIN_SUFFIX_MAP.getOrDefault(config.getRegion(), AWS_DOMAIN_DEFAULT)); } else { return String.format(config.getGGServerName()); } } @Override public void close() { if(httpClientConnectionManager != null) { httpClientConnectionManager.close(); } if (cleanExecutor == true) { executorService.shutdown(); try{ // Give the executorService 30 seconds to finish existing tasks. If it takes longer, force it to shutdown if(!executorService.awaitTermination(30,TimeUnit.SECONDS)){ executorService.shutdownNow(); } } catch (InterruptedException ie){ // If current thread is interrupted, force executorService shutdown executorService.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } } executorService = null; } }
5,542
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/discovery
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/discovery/model/ConnectivityInfo.java
package software.amazon.awssdk.iot.discovery.model; import java.util.Objects; /** * Describes a Greengrass core endpoint that a device can connect to * * API Documentation: https://docs.aws.amazon.com/greengrass/latest/developerguide/gg-discover-api.html */ public class ConnectivityInfo { private String Id; private String HostAddress; private String Metadata; private Integer PortNumber; /** * @return identifier associated with this endpoint entry */ public String getId() { return Id; } /** * Sets the identifier associated with this endpoint entry * @param id identifier associated with this endpoint entry */ public void setId(String id) { this.Id = id; } /** * @return address of the endpoint */ public String getHostAddress() { return HostAddress; } /** * Sets the address of the endpoint * @param hostAddress address of the endpoint */ public void setHostAddress(String hostAddress) { this.HostAddress = hostAddress; } /** * @return additional user-configurable metadata about the connectivity entry */ public String getMetadata() { return Metadata; } /** * Sets the additional user-configurable metadata about the connectivity entry * @param metadata Additional user-configurable metadata about the connectivity entry */ public void setMetadata(String metadata) { this.Metadata = metadata; } /** * @return port of the endpoint */ public Integer getPortNumber() { return PortNumber; } /** * Sets the port of the endpoint * @param portNumber port of the endpoint */ public void setPortNumber(Integer portNumber) { this.PortNumber = portNumber; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ConnectivityInfo that = (ConnectivityInfo) o; return Objects.equals(Id, that.Id) && Objects.equals(HostAddress, that.HostAddress) && Objects.equals(Metadata, that.Metadata) && Objects.equals(PortNumber, that.PortNumber); } @Override public int hashCode() { return Objects.hash(Id, HostAddress, Metadata, PortNumber); } }
5,543
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/discovery
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/discovery/model/GGCore.java
package software.amazon.awssdk.iot.discovery.model; import java.util.List; import java.util.Objects; /** * Information about a particular Greengrass core within a Greengrass group * * API Documentation: https://docs.aws.amazon.com/greengrass/latest/developerguide/gg-discover-api.html */ public class GGCore { private String thingArn; private List<ConnectivityInfo> Connectivity; /** * @return resource name of the IoT thing associated with a Greengrass core */ public String getThingArn() { return thingArn; } /** * Sets the resource name of the IoT thing associated with a Greengrass core * @param thingArn resource name of the IoT thing associated with a Greengrass core */ public void setThingArn(String thingArn) { this.thingArn = thingArn; } /** * @return list of distinct ways to connect to the associated Greengrass core */ public List<ConnectivityInfo> getConnectivity() { return Connectivity; } /** * Sets the list of distinct ways to connect to the associated Greengrass core * @param connectivity list of distinct ways to connect to the associated Greengrass core */ public void setConnectivity(List<ConnectivityInfo> connectivity) { Connectivity = connectivity; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GGCore ggCore = (GGCore) o; return Objects.equals(thingArn, ggCore.thingArn) && Objects.equals(Connectivity, ggCore.Connectivity); } @Override public int hashCode() { return Objects.hash(thingArn, Connectivity); } }
5,544
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/discovery
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/discovery/model/GGGroup.java
package software.amazon.awssdk.iot.discovery.model; import java.util.List; import java.util.Objects; /** * Information about a Greengrass group: a structured collection of one or more Grengrass cores * * API Documentation: https://docs.aws.amazon.com/greengrass/latest/developerguide/gg-discover-api.html */ public class GGGroup { private String GGGroupId; private List<GGCore> Cores; private List<String> CAs; /** * @return list of Greengrass cores belonging to this group */ public List<GGCore> getCores() { return Cores; } /** * Sets the list of Greengrass cores belonging to this group * @param cores list of Greengrass cores belonging to this group */ public void setCores(List<GGCore> cores) { this.Cores = cores; } /** * @return list of certificate authorities (in PEM format) associated with the Greengrass group */ public List<String> getCAs() { return CAs; } /** * Sets the list of certificate authorities (in PEM format) associated with the Greengrass group * @param CAs list of certificate authorities (in PEM format) associated with the Greengrass group */ public void setCAs(List<String> CAs) { this.CAs = CAs; } /** * @return identifier for the Greengrass group */ public String getGGGroupId() { return GGGroupId; } /** * Sets the identifier for the Greengrass group * @param GGGroupId identifier for the Greengrass group */ public void setGGGroupId(String GGGroupId) { this.GGGroupId = GGGroupId; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GGGroup ggGroup = (GGGroup) o; return Objects.equals(GGGroupId, ggGroup.GGGroupId) && Objects.equals(Cores, ggGroup.Cores) && Objects.equals(CAs, ggGroup.CAs); } @Override public int hashCode() { return Objects.hash(GGGroupId, Cores, CAs); } }
5,545
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/discovery
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/discovery/model/DiscoverResponse.java
package software.amazon.awssdk.iot.discovery.model; import java.util.List; import java.util.Objects; /** * Top-level response data for a greengrass discovery request. Contains a list of available greengrass groups. * * API Documentation: https://docs.aws.amazon.com/greengrass/latest/developerguide/gg-discover-api.html */ public class DiscoverResponse { private List<GGGroup> GGGroups; /** * @return list of discovered Greengrass groups */ public List<GGGroup> getGGGroups() { return GGGroups; } /** * Sets the list of discovered Greengrass groups * @param GGGroups list of discovered Greengrass groups */ public void setGGGroups(List<GGGroup> GGGroups) { this.GGGroups = GGGroups; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DiscoverResponse that = (DiscoverResponse) o; return Objects.equals(GGGroups, that.GGGroups); } @Override public int hashCode() { return Objects.hash(GGGroups); } }
5,546
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/iotidentity/IotIdentityClient.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.iotidentity; import software.amazon.awssdk.iot.iotidentity.model.CreateCertificateFromCsrRequest; import software.amazon.awssdk.iot.iotidentity.model.CreateCertificateFromCsrResponse; import software.amazon.awssdk.iot.iotidentity.model.CreateCertificateFromCsrSubscriptionRequest; import software.amazon.awssdk.iot.iotidentity.model.CreateKeysAndCertificateRequest; import software.amazon.awssdk.iot.iotidentity.model.CreateKeysAndCertificateResponse; import software.amazon.awssdk.iot.iotidentity.model.CreateKeysAndCertificateSubscriptionRequest; import software.amazon.awssdk.iot.iotidentity.model.ErrorResponse; import software.amazon.awssdk.iot.iotidentity.model.RegisterThingRequest; import software.amazon.awssdk.iot.iotidentity.model.RegisterThingResponse; import software.amazon.awssdk.iot.iotidentity.model.RegisterThingSubscriptionRequest; 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; /** * An AWS IoT service that assists with provisioning a device and installing unique client certificates on it * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/provision-wo-cert.html * */ public class IotIdentityClient { private MqttClientConnection connection = null; private final Gson gson = getGson(); /** * Constructs a new IotIdentityClient * @param connection The connection to use */ public IotIdentityClient(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) { } /** * Creates new keys and a certificate. AWS IoT provides client certificates that are signed by the Amazon Root certificate authority (CA). The new certificate has a PENDING_ACTIVATION status. When you call RegisterThing to provision a thing with this certificate, the certificate status changes to ACTIVE or INACTIVE as described in the template. * * 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/provision-wo-cert.html#fleet-provision-api * * @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> PublishCreateKeysAndCertificate( CreateKeysAndCertificateRequest request, QualityOfService qos) { String topic = "$aws/certificates/create/json"; 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 of the CreateKeysAndCertificate 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/provision-wo-cert.html#fleet-provision-api * * @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> SubscribeToCreateKeysAndCertificateAccepted( CreateKeysAndCertificateSubscriptionRequest request, QualityOfService qos, Consumer<CreateKeysAndCertificateResponse> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/certificates/create/json/accepted"; Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); CreateKeysAndCertificateResponse response = gson.fromJson(payload, CreateKeysAndCertificateResponse.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * Subscribes to the accepted topic of the CreateKeysAndCertificate 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/provision-wo-cert.html#fleet-provision-api * * @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> SubscribeToCreateKeysAndCertificateAccepted( CreateKeysAndCertificateSubscriptionRequest request, QualityOfService qos, Consumer<CreateKeysAndCertificateResponse> handler) { return SubscribeToCreateKeysAndCertificateAccepted(request, qos, handler, null); } /** * Subscribes to the rejected topic of the CreateKeysAndCertificate 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/provision-wo-cert.html#fleet-provision-api * * @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> SubscribeToCreateKeysAndCertificateRejected( CreateKeysAndCertificateSubscriptionRequest request, QualityOfService qos, Consumer<ErrorResponse> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/certificates/create/json/rejected"; Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); ErrorResponse response = gson.fromJson(payload, ErrorResponse.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * Subscribes to the rejected topic of the CreateKeysAndCertificate 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/provision-wo-cert.html#fleet-provision-api * * @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> SubscribeToCreateKeysAndCertificateRejected( CreateKeysAndCertificateSubscriptionRequest request, QualityOfService qos, Consumer<ErrorResponse> handler) { return SubscribeToCreateKeysAndCertificateRejected(request, qos, handler, null); } /** * Subscribes to the rejected topic of the RegisterThing 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/provision-wo-cert.html#fleet-provision-api * * @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> SubscribeToRegisterThingRejected( RegisterThingSubscriptionRequest request, QualityOfService qos, Consumer<ErrorResponse> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/provisioning-templates/{templateName}/provision/json/rejected"; if (request.templateName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("RegisterThingSubscriptionRequest must have a non-null templateName")); return result; } topic = topic.replace("{templateName}", request.templateName); Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); ErrorResponse response = gson.fromJson(payload, ErrorResponse.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * Subscribes to the rejected topic of the RegisterThing 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/provision-wo-cert.html#fleet-provision-api * * @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> SubscribeToRegisterThingRejected( RegisterThingSubscriptionRequest request, QualityOfService qos, Consumer<ErrorResponse> handler) { return SubscribeToRegisterThingRejected(request, qos, handler, null); } /** * Subscribes to the accepted topic of the CreateCertificateFromCsr 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/provision-wo-cert.html#fleet-provision-api * * @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> SubscribeToCreateCertificateFromCsrAccepted( CreateCertificateFromCsrSubscriptionRequest request, QualityOfService qos, Consumer<CreateCertificateFromCsrResponse> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/certificates/create-from-csr/json/accepted"; Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); CreateCertificateFromCsrResponse response = gson.fromJson(payload, CreateCertificateFromCsrResponse.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * Subscribes to the accepted topic of the CreateCertificateFromCsr 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/provision-wo-cert.html#fleet-provision-api * * @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> SubscribeToCreateCertificateFromCsrAccepted( CreateCertificateFromCsrSubscriptionRequest request, QualityOfService qos, Consumer<CreateCertificateFromCsrResponse> handler) { return SubscribeToCreateCertificateFromCsrAccepted(request, qos, handler, null); } /** * Provisions an AWS IoT thing using a pre-defined template. * * 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/provision-wo-cert.html#fleet-provision-api * * @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> PublishRegisterThing( RegisterThingRequest request, QualityOfService qos) { String topic = "$aws/provisioning-templates/{templateName}/provision/json"; if (request.templateName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("RegisterThingRequest must have a non-null templateName")); return result; } topic = topic.replace("{templateName}", request.templateName); 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 of the RegisterThing 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/provision-wo-cert.html#fleet-provision-api * * @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> SubscribeToRegisterThingAccepted( RegisterThingSubscriptionRequest request, QualityOfService qos, Consumer<RegisterThingResponse> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/provisioning-templates/{templateName}/provision/json/accepted"; if (request.templateName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("RegisterThingSubscriptionRequest must have a non-null templateName")); return result; } topic = topic.replace("{templateName}", request.templateName); Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); RegisterThingResponse response = gson.fromJson(payload, RegisterThingResponse.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * Subscribes to the accepted topic of the RegisterThing 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/provision-wo-cert.html#fleet-provision-api * * @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> SubscribeToRegisterThingAccepted( RegisterThingSubscriptionRequest request, QualityOfService qos, Consumer<RegisterThingResponse> handler) { return SubscribeToRegisterThingAccepted(request, qos, handler, null); } /** * Subscribes to the rejected topic of the CreateCertificateFromCsr 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/provision-wo-cert.html#fleet-provision-api * * @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> SubscribeToCreateCertificateFromCsrRejected( CreateCertificateFromCsrSubscriptionRequest request, QualityOfService qos, Consumer<ErrorResponse> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/certificates/create-from-csr/json/rejected"; Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); ErrorResponse response = gson.fromJson(payload, ErrorResponse.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * Subscribes to the rejected topic of the CreateCertificateFromCsr 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/provision-wo-cert.html#fleet-provision-api * * @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> SubscribeToCreateCertificateFromCsrRejected( CreateCertificateFromCsrSubscriptionRequest request, QualityOfService qos, Consumer<ErrorResponse> handler) { return SubscribeToCreateCertificateFromCsrRejected(request, qos, handler, null); } /** * Creates a certificate from a certificate signing request (CSR). AWS IoT provides client certificates that are signed by the Amazon Root certificate authority (CA). The new certificate has a PENDING_ACTIVATION status. When you call RegisterThing to provision a thing with this certificate, the certificate status changes to ACTIVE or INACTIVE as described in the template. * * 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/provision-wo-cert.html#fleet-provision-api * * @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> PublishCreateCertificateFromCsr( CreateCertificateFromCsrRequest request, QualityOfService qos) { String topic = "$aws/certificates/create-from-csr/json"; String payloadJson = gson.toJson(request); MqttMessage message = new MqttMessage(topic, payloadJson.getBytes(StandardCharsets.UTF_8)); return connection.publish(message, qos, false); } }
5,547
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotidentity
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotidentity/model/RegisterThingResponse.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.iotidentity.model; import java.util.HashMap; /** * Response payload to a RegisterThing request. * */ public class RegisterThingResponse { /** * The name of the IoT thing created during provisioning. * */ public String thingName; /** * The device configuration defined in the template. * */ public HashMap<String, String> deviceConfiguration; }
5,548
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotidentity
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotidentity/model/CreateKeysAndCertificateRequest.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.iotidentity.model; /** * Data needed to perform a CreateKeysAndCertificate operation. * */ public class CreateKeysAndCertificateRequest { }
5,549
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotidentity
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotidentity/model/CreateCertificateFromCsrSubscriptionRequest.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.iotidentity.model; /** * Data needed to subscribe to the responses of the CreateCertificateFromCsr operation. * */ public class CreateCertificateFromCsrSubscriptionRequest { }
5,550
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotidentity
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotidentity/model/RegisterThingSubscriptionRequest.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.iotidentity.model; /** * Data needed to subscribe to the responses of the RegisterThing operation. * */ public class RegisterThingSubscriptionRequest { /** * Name of the provisioning template to listen for RegisterThing responses for. * */ public String templateName; }
5,551
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotidentity
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotidentity/model/RegisterThingRequest.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.iotidentity.model; import java.util.HashMap; /** * Data needed to perform a RegisterThing operation. * */ public class RegisterThingRequest { /** * The provisioning template name. * */ public String templateName; /** * Optional. Key-value pairs from the device that are used by the pre-provisioning hooks to evaluate the registration request. * */ public HashMap<String, String> parameters; /** * The token to prove ownership of the certificate. The token is generated by AWS IoT when you create a certificate over MQTT. * */ public String certificateOwnershipToken; }
5,552
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotidentity
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotidentity/model/CreateCertificateFromCsrRequest.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.iotidentity.model; /** * Data needed to perform a CreateCertificateFromCsr operation. * */ public class CreateCertificateFromCsrRequest { /** * The CSR, in PEM format. * */ public String certificateSigningRequest; }
5,553
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotidentity
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotidentity/model/CreateCertificateFromCsrResponse.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.iotidentity.model; /** * Response payload to a CreateCertificateFromCsr request. * */ public class CreateCertificateFromCsrResponse { /** * The ID of the certificate. * */ public String certificateId; /** * The token to prove ownership of the certificate during provisioning. * */ public String certificateOwnershipToken; /** * The certificate data, in PEM format. * */ public String certificatePem; }
5,554
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotidentity
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotidentity/model/CreateKeysAndCertificateResponse.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.iotidentity.model; /** * Response payload to a CreateKeysAndCertificate request. * */ public class CreateKeysAndCertificateResponse { /** * The certificate id. * */ public String certificateId; /** * The token to prove ownership of the certificate during provisioning. * */ public String certificateOwnershipToken; /** * The certificate data, in PEM format. * */ public String certificatePem; /** * The private key. * */ public String privateKey; }
5,555
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotidentity
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotidentity/model/ErrorResponse.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.iotidentity.model; /** * Response document containing details about a failed request. * */ public class ErrorResponse { /** * Response status code * */ public Integer statusCode; /** * Response error message * */ public String errorMessage; /** * Response error code * */ public String errorCode; }
5,556
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotidentity
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotidentity/model/CreateKeysAndCertificateSubscriptionRequest.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.iotidentity.model; /** * Data needed to subscribe to the responses of the CreateKeysAndCertificate operation. * */ public class CreateKeysAndCertificateSubscriptionRequest { }
5,557
0
Create_ds/aws-iot-device-sdk-java-v2/android/iotdevicesdk/src/androidTest/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/android/iotdevicesdk/src/androidTest/java/software/amazon/awssdk/iotdevicesdk/ExampleInstrumentedTest.java
package software.amazon.awssdk.iotdevicesdk; import android.content.Context; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); assertEquals("software.amazon.awssdk.iotdevicesdk.test", appContext.getPackageName()); } }
5,558
0
Create_ds/aws-iot-device-sdk-java-v2/android/iotdevicesdk/src/test/java/software/amazon/awssdk
Create_ds/aws-iot-device-sdk-java-v2/android/iotdevicesdk/src/test/java/software/amazon/awssdk/iotdevicesdk/ExampleUnitTest.java
package software.amazon.awssdk.iotdevicesdk; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
5,559
0
Create_ds/aws-iot-device-sdk-java-v2/deviceadvisor/tests/JobExecution/src/main/java
Create_ds/aws-iot-device-sdk-java-v2/deviceadvisor/tests/JobExecution/src/main/java/jobExecution/JobExecution.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package JobExecution; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.CrtRuntimeException; import software.amazon.awssdk.crt.mqtt.MqttClientConnection; import software.amazon.awssdk.crt.mqtt.QualityOfService; import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder; import software.amazon.awssdk.iot.iotjobs.IotJobsClient; 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.JobExecutionSummary; import software.amazon.awssdk.iot.iotjobs.model.JobStatus; import software.amazon.awssdk.iot.iotjobs.model.RejectedError; 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.UpdateJobExecutionSubscriptionRequest; import software.amazon.awssdk.iot.iotjobs.model.NextJobExecutionChangedSubscriptionRequest; import software.amazon.awssdk.iot.iotjobs.model.NextJobExecutionChangedEvent; import software.amazon.awssdk.iot.iotjobs.model.JobExecutionsChangedSubscriptionRequest; import software.amazon.awssdk.iot.iotjobs.model.JobExecutionsChangedEvent; import java.util.LinkedList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.UUID; import DATestUtils.DATestUtils; public class JobExecution { static String clientId = "test-" + UUID.randomUUID().toString(); static short port = 8883; static MqttClientConnection connection; static IotJobsClient jobs; static CompletableFuture<Void> gotResponse; static List<String> availableJobs = new LinkedList<>(); static String currentJobId; static long currentExecutionNumber = 0; static int currentVersionNumber = 0; static void onRejectedError(RejectedError error) { System.out.println("Request rejected: " + error.code.toString() + ": " + error.message); System.exit(1); } static void onGetPendingJobExecutionsAccepted(GetPendingJobExecutionsResponse response) { System.out.println( "Pending Jobs: " + (response.queuedJobs.size() + response.inProgressJobs.size() == 0 ? "none" : "")); for (JobExecutionSummary job : response.inProgressJobs) { availableJobs.add(job.jobId); System.out.println(" In Progress: " + job.jobId + " @ " + job.lastUpdatedAt.toString()); } for (JobExecutionSummary job : response.queuedJobs) { availableJobs.add(job.jobId); System.out.println(" " + job.jobId + " @ " + job.lastUpdatedAt.toString()); } gotResponse.complete(null); } static void onDescribeJobExecutionAccepted(DescribeJobExecutionResponse response) { System.out .println("Describe Job: " + response.execution.jobId + " version: " + response.execution.versionNumber); if (response.execution.jobDocument != null) { response.execution.jobDocument.forEach((key, value) -> { System.out.println(" " + key + ": " + value); }); } gotResponse.complete(null); } static void onStartNextPendingJobExecutionAccepted(StartNextJobExecutionResponse response) { System.out.println("Start Job: " + response.execution.jobId); currentJobId = response.execution.jobId; currentExecutionNumber = response.execution.executionNumber; currentVersionNumber = response.execution.versionNumber; gotResponse.complete(null); } static MqttClientConnection createConnection() { try (AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder .newMtlsBuilderFromPath(DATestUtils.certificatePath, DATestUtils.keyPath)) { builder.withClientId(clientId) .withEndpoint(DATestUtils.endpoint) .withPort(port) .withCleanSession(true) .withProtocolOperationTimeoutMs(60000); MqttClientConnection connection = builder.build(); return connection; } catch (Exception ex) { throw new RuntimeException("Failed to create connection", ex); } } static void getPendingJobs() throws RuntimeException { gotResponse = new CompletableFuture<>(); GetPendingJobExecutionsSubscriptionRequest subscriptionRequest = new GetPendingJobExecutionsSubscriptionRequest(); subscriptionRequest.thingName = DATestUtils.thing_name; System.out.println("Subscribing to GetPendingJobExecutionsAccepted for thing '" + DATestUtils.thing_name + "'"); CompletableFuture<Integer> subscribed = jobs.SubscribeToGetPendingJobExecutionsAccepted( subscriptionRequest, QualityOfService.AT_LEAST_ONCE, JobExecution::onGetPendingJobExecutionsAccepted); try { subscribed.get(); System.out.println("Subscribed to GetPendingJobExecutionsAccepted"); } catch (Exception ex) { throw new RuntimeException("Failed to subscribe to GetPendingJobExecutionsAccepted", ex); } subscribed = jobs.SubscribeToGetPendingJobExecutionsRejected( subscriptionRequest, QualityOfService.AT_LEAST_ONCE, JobExecution::onRejectedError); try { subscribed.get(); System.out.println("Subscribed to GetPendingJobExecutionsRejected"); } catch (Exception ex) { throw new RuntimeException("Failed to subscribe to GetPendingJobExecutionsRejected", ex); } GetPendingJobExecutionsRequest publishRequest = new GetPendingJobExecutionsRequest(); publishRequest.thingName = DATestUtils.thing_name; CompletableFuture<Integer> published = jobs.PublishGetPendingJobExecutions( publishRequest, QualityOfService.AT_LEAST_ONCE); try { published.get(); System.out.println("Published to GetPendingJobExecutions"); } catch (Exception ex) { throw new RuntimeException("Failed to publish to GetPendingJobExecutions", ex); } // Waiting for either onGetPendingJobExecutionsAccepted or onRejectedError to be // called. try { gotResponse.get(); } catch (Exception ex) { throw new RuntimeException("Exception occurred while waiting for pending Jobs", ex); } } static void getJobDescriptions() throws RuntimeException { for (String jobId : availableJobs) { gotResponse = new CompletableFuture<>(); DescribeJobExecutionSubscriptionRequest subscriptionRequest = new DescribeJobExecutionSubscriptionRequest(); subscriptionRequest.thingName = DATestUtils.thing_name; subscriptionRequest.jobId = jobId; jobs.SubscribeToDescribeJobExecutionAccepted( subscriptionRequest, QualityOfService.AT_LEAST_ONCE, JobExecution::onDescribeJobExecutionAccepted); jobs.SubscribeToDescribeJobExecutionRejected( subscriptionRequest, QualityOfService.AT_LEAST_ONCE, JobExecution::onRejectedError); DescribeJobExecutionRequest publishRequest = new DescribeJobExecutionRequest(); publishRequest.thingName = DATestUtils.thing_name; publishRequest.jobId = jobId; publishRequest.includeJobDocument = true; publishRequest.executionNumber = 1L; jobs.PublishDescribeJobExecution(publishRequest, QualityOfService.AT_LEAST_ONCE); // Waiting for either onDescribeJobExecutionAccepted or onRejectedError to be // called. try { gotResponse.get(); } catch (Exception ex) { throw new RuntimeException("Exception occurred while waiting for Job descriptions", ex); } } } static void startNextPendingJob() throws RuntimeException { gotResponse = new CompletableFuture<>(); StartNextPendingJobExecutionSubscriptionRequest subscriptionRequest = new StartNextPendingJobExecutionSubscriptionRequest(); subscriptionRequest.thingName = DATestUtils.thing_name; jobs.SubscribeToStartNextPendingJobExecutionAccepted( subscriptionRequest, QualityOfService.AT_LEAST_ONCE, JobExecution::onStartNextPendingJobExecutionAccepted); jobs.SubscribeToStartNextPendingJobExecutionRejected( subscriptionRequest, QualityOfService.AT_LEAST_ONCE, JobExecution::onRejectedError); StartNextPendingJobExecutionRequest publishRequest = new StartNextPendingJobExecutionRequest(); publishRequest.thingName = DATestUtils.thing_name; publishRequest.stepTimeoutInMinutes = 15L; jobs.PublishStartNextPendingJobExecution(publishRequest, QualityOfService.AT_LEAST_ONCE); // Waiting for either onStartNextPendingJobExecutionAccepted or onRejectedError // to be called. try { gotResponse.get(); } catch (Exception ex) { throw new RuntimeException("Exception occurred while waiting for starting next pending Job", ex); } } static void updateCurrentJobStatus(JobStatus jobStatus) throws RuntimeException { gotResponse = new CompletableFuture<>(); UpdateJobExecutionSubscriptionRequest subscriptionRequest = new UpdateJobExecutionSubscriptionRequest(); subscriptionRequest.thingName = DATestUtils.thing_name; subscriptionRequest.jobId = currentJobId; jobs.SubscribeToUpdateJobExecutionAccepted( subscriptionRequest, QualityOfService.AT_LEAST_ONCE, (response) -> { System.out.println("Marked job " + currentJobId + " " + jobStatus.toString()); gotResponse.complete(null); }); jobs.SubscribeToUpdateJobExecutionRejected( subscriptionRequest, QualityOfService.AT_LEAST_ONCE, JobExecution::onRejectedError); UpdateJobExecutionRequest publishRequest = new UpdateJobExecutionRequest(); publishRequest.thingName = DATestUtils.thing_name; publishRequest.jobId = currentJobId; publishRequest.executionNumber = currentExecutionNumber; publishRequest.status = jobStatus; publishRequest.expectedVersion = currentVersionNumber++; jobs.PublishUpdateJobExecution(publishRequest, QualityOfService.AT_LEAST_ONCE); // Waiting for a response to our update. try { gotResponse.get(); } catch (Exception ex) { throw new RuntimeException("Exception occurred while waiting for updating Job", ex); } } public static void main(String[] args) { // Set vars if (!DATestUtils.init(DATestUtils.TestType.JOBS)) { throw new RuntimeException("Failed to initialize environment variables."); } try (MqttClientConnection connection = createConnection()) { jobs = new IotJobsClient(connection); CompletableFuture<Boolean> connected = connection.connect(); try { boolean sessionPresent = connected.get(); } catch (Exception ex) { throw new RuntimeException("Exception occurred during connect", ex); } getPendingJobs(); // This step is optional for the DA Job test, but perform it anyway to follow a // supposed flow. getJobDescriptions(); for (int jobIdx = 0; jobIdx < availableJobs.size(); ++jobIdx) { startNextPendingJob(); updateCurrentJobStatus(JobStatus.IN_PROGRESS); // Fake doing something Thread.sleep(1000); updateCurrentJobStatus(JobStatus.SUCCEEDED); } CompletableFuture<Void> disconnected = connection.disconnect(); try { disconnected.get(); } catch (Exception ex) { throw new RuntimeException("Exception occurred during disconnect", ex); } } catch (Exception ex) { throw new RuntimeException("Job execution failed", ex); } System.exit(0); } }
5,560
0
Create_ds/aws-iot-device-sdk-java-v2/deviceadvisor/tests/MQTTSubscribe/src/main/java
Create_ds/aws-iot-device-sdk-java-v2/deviceadvisor/tests/MQTTSubscribe/src/main/java/MQTTSubscribe/MQTTSubscribe.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package MQTTSubscribe; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.CrtRuntimeException; import software.amazon.awssdk.crt.mqtt.MqttClientConnection; import software.amazon.awssdk.crt.mqtt.QualityOfService; import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import DATestUtils.DATestUtils; public class MQTTSubscribe { // When run normally, we want to exit nicely even if something goes wrong // When run from CI, we want to let an exception escape which in turn causes the // exec:java task to return a non-zero exit code static String ciPropValue = System.getProperty("aws.crt.ci"); static boolean isCI = ciPropValue != null && Boolean.valueOf(ciPropValue); static String clientId = "test-" + UUID.randomUUID().toString(); static int port = 8883; /* * When called during a CI run, throw an exception that will escape and fail the exec:java task * When called otherwise, print what went wrong (if anything) and just continue (return from main) */ static void onApplicationFailure(Throwable cause) { if (isCI) { throw new RuntimeException("BasicPubSub execution failure", cause); } } public static void main(String[] args) { if(!DATestUtils.init(DATestUtils.TestType.SUB_PUB)) { throw new RuntimeException("Failed to initialize environment variables."); } try(AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newMtlsBuilderFromPath(DATestUtils.certificatePath, DATestUtils.keyPath)) { builder.withClientId(clientId) .withEndpoint(DATestUtils.endpoint) .withPort((short)port) .withCleanSession(true) .withPingTimeoutMs(60000) .withProtocolOperationTimeoutMs(60000); try(MqttClientConnection connection = builder.build()) { CompletableFuture<Boolean> connected = connection.connect(); try { boolean sessionPresent = connected.get(); } catch (Exception ex) { throw new RuntimeException("Exception occurred during connect", ex); } CompletableFuture<Integer> subscribed = connection.subscribe(DATestUtils.topic, QualityOfService.AT_MOST_ONCE, (message) -> { }); subscribed.get(); CompletableFuture<Void> disconnected = connection.disconnect(); disconnected.get(); } } catch (CrtRuntimeException | InterruptedException | ExecutionException ex) { onApplicationFailure(ex); } System.exit(0); } }
5,561
0
Create_ds/aws-iot-device-sdk-java-v2/deviceadvisor/tests
Create_ds/aws-iot-device-sdk-java-v2/deviceadvisor/tests/DATestUtils/DATestUtils.java
package DATestUtils; import java.util.UUID; public class DATestUtils { public enum TestType { CONNECT, SUB_PUB, SHADOW, JOBS } private final static String ENV_ENDPONT = "DA_ENDPOINT"; private final static String ENV_CERTI = "DA_CERTI"; private final static String ENV_KEY = "DA_KEY"; private final static String ENV_TOPIC = "DA_TOPIC"; private final static String ENV_THING_NAME = "DA_THING_NAME"; private final static String ENV_SHADOW_PROPERTY = "DA_SHADOW_PROPERTY"; private final static String ENV_SHADOW_VALUE_SET = "DA_SHADOW_VALUE_SET"; private final static String ENV_SHADOW_VALUE_DEFAULT = "DA_SHADOW_VALUE_DEFAULT"; private final static String ENV_SHADOW_NAME = "DA_SHADOW_NAME"; public static String endpoint; public static String certificatePath; public static String keyPath; public static String topic; public static String thing_name; public static String shadowProperty; public static String shadowValue; public static String shadowName; public static Boolean init(TestType type) { endpoint = System.getenv(ENV_ENDPONT); certificatePath = System.getenv(ENV_CERTI); keyPath = System.getenv(ENV_KEY); topic = System.getenv(ENV_TOPIC); thing_name = System.getenv(ENV_THING_NAME); shadowProperty = System.getenv(ENV_SHADOW_PROPERTY); shadowValue = System.getenv(ENV_SHADOW_VALUE_SET); shadowName = System.getenv(ENV_SHADOW_NAME); if (endpoint.isEmpty() || certificatePath.isEmpty() || keyPath.isEmpty()) { return false; } if (type == TestType.SUB_PUB && topic.isEmpty()) { return false; } if (type == TestType.SHADOW && (thing_name.isEmpty() || shadowProperty.isEmpty() || shadowValue.isEmpty())) { return false; } if (type == TestType.JOBS && thing_name.isEmpty()) { return false; } return true; } }
5,562
0
Create_ds/aws-iot-device-sdk-java-v2/deviceadvisor/tests/MQTTConnect/src/main/java
Create_ds/aws-iot-device-sdk-java-v2/deviceadvisor/tests/MQTTConnect/src/main/java/MQTTConnect/MQTTConnect.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package MQTTConnect; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.CrtRuntimeException; import software.amazon.awssdk.crt.mqtt.MqttClientConnection; import software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents; import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import DATestUtils.DATestUtils; public class MQTTConnect { // When run normally, we want to exit nicely even if something goes wrong // When run from CI, we want to let an exception escape which in turn causes the // exec:java task to return a non-zero exit code static String ciPropValue = System.getProperty("aws.crt.ci"); static boolean isCI = ciPropValue != null && Boolean.valueOf(ciPropValue); static String clientId = "test-" + UUID.randomUUID().toString(); static int port = 8883; /* * When called during a CI run, throw an exception that will escape and fail the exec:java task * When called otherwise, print what went wrong (if anything) and just continue (return from main) */ static void onApplicationFailure(Throwable cause) { if (isCI) { throw new RuntimeException("BasicPubSub execution failure", cause); } } public static void main(String[] args) { if(!DATestUtils.init(DATestUtils.TestType.CONNECT)) { throw new RuntimeException("Failed to initialize environment variables."); } try(AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newMtlsBuilderFromPath(DATestUtils.certificatePath, DATestUtils.keyPath)) { builder.withClientId(clientId) .withEndpoint(DATestUtils.endpoint) .withPort((short)port) .withCleanSession(true) .withPingTimeoutMs(60000) .withProtocolOperationTimeoutMs(60000); try(MqttClientConnection connection = builder.build()) { CompletableFuture<Boolean> connected = connection.connect(); try { boolean sessionPresent = connected.get(); } catch (Exception ex) { throw new RuntimeException("Exception occurred during connect", ex); } CompletableFuture<Void> disconnected = connection.disconnect(); disconnected.get(); } } catch (CrtRuntimeException | InterruptedException | ExecutionException ex) { System.out.print("failed: " + ex.getMessage()); } System.exit(0); } }
5,563
0
Create_ds/aws-iot-device-sdk-java-v2/deviceadvisor/tests/ShadowUpdate/src/main/java
Create_ds/aws-iot-device-sdk-java-v2/deviceadvisor/tests/ShadowUpdate/src/main/java/shadowUpdate/ShadowUpdate.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package ShadowUpdate; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.CrtRuntimeException; import software.amazon.awssdk.crt.mqtt.MqttClientConnection; import software.amazon.awssdk.crt.mqtt.QualityOfService; import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder; import software.amazon.awssdk.iot.iotshadow.IotShadowClient; import software.amazon.awssdk.iot.iotshadow.model.ShadowState; import software.amazon.awssdk.iot.iotshadow.model.UpdateShadowRequest; import software.amazon.awssdk.iot.iotshadow.model.UpdateNamedShadowRequest; import java.util.HashMap; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.UUID; import DATestUtils.DATestUtils; public class ShadowUpdate { static String clientId = "test-" + UUID.randomUUID().toString(); static int port = 8883; static MqttClientConnection connection; static IotShadowClient shadow; static CompletableFuture<Integer> changeShadowValue() { // build a request to let the service know our current value and desired value, and that we only want // to update if the version matches the version we know about UpdateShadowRequest request = new UpdateShadowRequest(); request.thingName = DATestUtils.thing_name; request.state = new ShadowState(); request.state.reported = new HashMap<String, Object>() {{ put(DATestUtils.shadowProperty, DATestUtils.shadowValue); }}; request.state.desired = new HashMap<String, Object>() {{ put(DATestUtils.shadowProperty, DATestUtils.shadowValue); }}; // Publish the request return shadow.PublishUpdateShadow(request, QualityOfService.AT_MOST_ONCE); } static CompletableFuture<Integer> changeNamedShadowValue() { // build a request to let the service know our current value and desired value, and that we only want // to update if the version matches the version we know about UpdateNamedShadowRequest request = new UpdateNamedShadowRequest(); request.thingName = DATestUtils.thing_name; request.state = new ShadowState(); request.state.reported = new HashMap<String, Object>() {{ put(DATestUtils.shadowProperty, DATestUtils.shadowValue); }}; request.state.desired = new HashMap<String, Object>() {{ put(DATestUtils.shadowProperty, DATestUtils.shadowValue); }}; request.shadowName = DATestUtils.shadowName; // Publish the request return shadow.PublishUpdateNamedShadow(request, QualityOfService.AT_MOST_ONCE); } public static void main(String[] args) { Boolean isNamedShadow = false; if (args.length > 0 && args[0].equals("--named-shadow")) { isNamedShadow = true; } // Set vars if(!DATestUtils.init(DATestUtils.TestType.SHADOW)) { throw new RuntimeException("Failed to initialize environment variables."); } try(AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newMtlsBuilderFromPath(DATestUtils.certificatePath, DATestUtils.keyPath)) { builder.withClientId(clientId) .withEndpoint(DATestUtils.endpoint) .withPort((short)port) .withCleanSession(true) .withProtocolOperationTimeoutMs(60000); try(MqttClientConnection connection = builder.build()) { shadow = new IotShadowClient(connection); CompletableFuture<Boolean> connected = connection.connect(); try { connected.get(); } catch (Exception ex) { throw new RuntimeException("Exception occurred during connect", ex); } if (isNamedShadow) { changeNamedShadowValue().get(); } else { changeShadowValue().get(); } CompletableFuture<Void> disconnected = connection.disconnect(); disconnected.get(); } } catch (CrtRuntimeException | InterruptedException | ExecutionException ex) { throw new RuntimeException("Builder Connection Failed.", ex); } System.exit(0); } }
5,564
0
Create_ds/aws-iot-device-sdk-java-v2/deviceadvisor/tests/MQTTPublish/src/main/java
Create_ds/aws-iot-device-sdk-java-v2/deviceadvisor/tests/MQTTPublish/src/main/java/MQTTPublish/MQTTPublish.java
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package MQTTPublish; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.CrtResource; import software.amazon.awssdk.crt.CrtRuntimeException; import software.amazon.awssdk.crt.mqtt.MqttClientConnection; import software.amazon.awssdk.crt.mqtt.QualityOfService; import software.amazon.awssdk.crt.mqtt.MqttMessage; import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import DATestUtils.DATestUtils; public class MQTTPublish { // When run normally, we want to exit nicely even if something goes wrong // When run from CI, we want to let an exception escape which in turn causes the // exec:java task to return a non-zero exit code static String ciPropValue = System.getProperty("aws.crt.ci"); static boolean isCI = ciPropValue != null && Boolean.valueOf(ciPropValue); static String clientId = "test-" + UUID.randomUUID().toString(); static String message = "Hello World!"; static int port = 8883; /* * When called during a CI run, throw an exception that will escape and fail the exec:java task * When called otherwise, print what went wrong (if anything) and just continue (return from main) */ static void onApplicationFailure(Throwable cause) { if (isCI) { throw new RuntimeException("BasicPubSub execution failure", cause); } } public static void main(String[] args) { if(!DATestUtils.init(DATestUtils.TestType.SUB_PUB)) { throw new RuntimeException("Failed to initialize environment variables."); } try(AwsIotMqttConnectionBuilder builder = AwsIotMqttConnectionBuilder.newMtlsBuilderFromPath(DATestUtils.certificatePath, DATestUtils.keyPath)) { builder.withClientId(clientId) .withEndpoint(DATestUtils.endpoint) .withPort((short)port) .withCleanSession(true) .withPingTimeoutMs(60000) .withProtocolOperationTimeoutMs(60000); try(MqttClientConnection connection = builder.build()) { CompletableFuture<Boolean> connected = connection.connect(); try { boolean sessionPresent = connected.get(); } catch (Exception ex) { throw new RuntimeException("Exception occurred during connect", ex); } CompletableFuture<Integer> published = connection.publish(new MqttMessage(DATestUtils.topic, message.getBytes(), QualityOfService.AT_MOST_ONCE, false)); published.get(); Thread.sleep(1000); CompletableFuture<Void> disconnected = connection.disconnect(); disconnected.get(); } } catch (CrtRuntimeException | InterruptedException | ExecutionException ex) { onApplicationFailure(ex); } System.exit(0); } }
5,565
0
Create_ds/aws-sdk-java-archetype/src/main/resources/archetype-resources/src/main
Create_ds/aws-sdk-java-archetype/src/main/resources/archetype-resources/src/main/java/AwsSdkSample.java
#set( $symbol_pound = '#' ) #set( $symbol_dollar = '$' ) #set( $symbol_escape = '\' ) /* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ import java.io.File; import java.util.HashSet; import java.util.List; import java.util.Set; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.auth.profile.ProfilesConfigFile; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.model.AvailabilityZone; import com.amazonaws.services.ec2.model.DescribeAvailabilityZonesResult; import com.amazonaws.services.ec2.model.DescribeInstancesResult; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.Reservation; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.iterable.S3Objects; import com.amazonaws.services.s3.model.Bucket; import com.amazonaws.services.s3.model.S3ObjectSummary; /** * This class is a starting point for working with the AWS SDK for Java, and * shows how to make a few simple requests to Amazon EC2 and Amazon S3. * * Before you run this code, be sure to fill in your AWS security credentials * in the .aws/credentials file under your home directory. * * If you don't have an Amazon Web Services account, you can get started for free: * http://aws.amazon.com/free * * For lots more information on using the AWS SDK for Java, including information on * high-level APIs and advanced features, check out the AWS SDK for Java Developer Guide: * http://docs.aws.amazon.com/AWSSdkDocsJava/latest/DeveloperGuide/welcome.html * * Stay up to date with new features in the AWS SDK for Java by following the * AWS Java Developer Blog: * https://java.awsblog.com */ public class AwsSdkSample { /* * Important: Be sure to fill in your AWS access credentials in the * .aws/credentials file under your home directory * before you run this sample. * http://aws.amazon.com/security-credentials */ static AmazonEC2 ec2; static AmazonS3 s3; /** * The only information needed to create a client are security credentials - * your AWS Access Key ID and Secret Access Key. All other * configuration, such as the service endpoints have defaults provided. * * Additional client parameters, such as proxy configuration, can be specified * in an optional ClientConfiguration object when constructing a client. * * @see com.amazonaws.auth.BasicAWSCredentials * @see com.amazonaws.auth.PropertiesCredentials * @see com.amazonaws.ClientConfiguration */ private static void init() throws Exception { /* * ProfileCredentialsProvider loads AWS security credentials from a * .aws/config file in your home directory. * * These same credentials are used when working with other AWS SDKs and the AWS CLI. * * You can find more information on the AWS profiles config file here: * http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html */ File configFile = new File(System.getProperty("user.home"), ".aws/credentials"); AWSCredentialsProvider credentialsProvider = new ProfileCredentialsProvider( new ProfilesConfigFile(configFile), "default"); if (credentialsProvider.getCredentials() == null) { throw new RuntimeException("No AWS security credentials found:\n" + "Make sure you've configured your credentials in: " + configFile.getAbsolutePath() + "\n" + "For more information on configuring your credentials, see " + "http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html"); } ec2 = new AmazonEC2Client(credentialsProvider); s3 = new AmazonS3Client(credentialsProvider); } public static void main(String[] args) throws Exception { System.out.println("==========================================="); System.out.println("Welcome to the AWS Java SDK!"); System.out.println("==========================================="); init(); try { /* * The Amazon EC2 client allows you to easily launch and configure * computing capacity in AWS datacenters. * * In this sample, we use the EC2 client to list the availability zones * in a region, and then list the instances running in those zones. */ DescribeAvailabilityZonesResult availabilityZonesResult = ec2.describeAvailabilityZones(); List<AvailabilityZone> availabilityZones = availabilityZonesResult.getAvailabilityZones(); System.out.println("You have access to " + availabilityZones.size() + " availability zones:"); for (AvailabilityZone zone : availabilityZones) { System.out.println(" - " + zone.getZoneName() + " (" + zone.getRegionName() + ")"); } DescribeInstancesResult describeInstancesResult = ec2.describeInstances(); Set<Instance> instances = new HashSet<Instance>(); for (Reservation reservation : describeInstancesResult.getReservations()) { instances.addAll(reservation.getInstances()); } System.out.println("You have " + instances.size() + " Amazon EC2 instance(s) running."); /* * The Amazon S3 client allows you to manage and configure buckets * and to upload and download data. * * In this sample, we use the S3 client to list all the buckets in * your account, and then iterate over the object metadata for all * objects in one bucket to calculate the total object count and * space usage for that one bucket. Note that this sample only * retrieves the object's metadata and doesn't actually download the * object's content. * * In addition to the low-level Amazon S3 client in the SDK, there * is also a high-level TransferManager API that provides * asynchronous management of uploads and downloads with an easy to * use API: * http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/s3/transfer/TransferManager.html */ List<Bucket> buckets = s3.listBuckets(); System.out.println("You have " + buckets.size() + " Amazon S3 bucket(s)."); if (buckets.size() > 0) { Bucket bucket = buckets.get(0); long totalSize = 0; long totalItems = 0; /* * The S3Objects and S3Versions classes provide convenient APIs * for iterating over the contents of your buckets, without * having to manually deal with response pagination. */ for (S3ObjectSummary objectSummary : S3Objects.inBucket(s3, bucket.getName())) { totalSize += objectSummary.getSize(); totalItems++; } System.out.println("The bucket '" + bucket.getName() + "' contains "+ totalItems + " objects " + "with a total size of " + totalSize + " bytes."); } } catch (AmazonServiceException ase) { /* * AmazonServiceExceptions represent an error response from an AWS * services, i.e. your request made it to AWS, but the AWS service * either found it invalid or encountered an error trying to execute * it. */ System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { /* * AmazonClientExceptions represent an error that occurred inside * the client on the local host, either while trying to send the * request to AWS or interpret the response. For example, if no * network connection is available, the client won't be able to * connect to AWS to execute a request and will throw an * AmazonClientException. */ System.out.println("Error Message: " + ace.getMessage()); } } }
5,566
0
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam/IAMClientCallbackHandlerTest.java
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package software.amazon.msk.auth.iam; import software.amazon.msk.auth.iam.internals.AWSCredentialsCallback; import software.amazon.msk.auth.iam.internals.SystemPropertyCredentialsUtils; import org.junit.jupiter.api.Test; import javax.security.auth.callback.Callback; import javax.security.auth.callback.UnsupportedCallbackException; import java.io.IOException; import java.util.Collections; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; public class IAMClientCallbackHandlerTest { private static final String ACCESS_KEY_VALUE = "ACCESS_KEY_VALUE"; private static final String SECRET_KEY_VALUE = "SECRET_KEY_VALUE"; @Test public void testDefaultCredentials() throws IOException, UnsupportedCallbackException { IAMClientCallbackHandler clientCallbackHandler = new IAMClientCallbackHandler(); clientCallbackHandler.configure(Collections.emptyMap(), "AWS_MSK_IAM", Collections.emptyList()); SystemPropertyCredentialsUtils.runTestWithSystemPropertyCredentials(() -> { AWSCredentialsCallback callback = new AWSCredentialsCallback(); try { clientCallbackHandler.handle(new Callback[]{callback}); } catch (Exception e) { throw new RuntimeException("Test failed", e); } assertTrue(callback.isSuccessful()); assertEquals(ACCESS_KEY_VALUE, callback.getAwsCredentials().getAWSAccessKeyId()); assertEquals(SECRET_KEY_VALUE, callback.getAwsCredentials().getAWSSecretKey()); }, ACCESS_KEY_VALUE, SECRET_KEY_VALUE); } @Test public void testDifferentMechanism() { IAMClientCallbackHandler clientCallbackHandler = new IAMClientCallbackHandler(); assertThrows(IllegalArgumentException.class, () -> clientCallbackHandler .configure(Collections.emptyMap(), "SOME_OTHER_MECHANISM", Collections.emptyList())); } @Test public void testDifferentCallback() { IAMClientCallbackHandler clientCallbackHandler = new IAMClientCallbackHandler(); UnsupportedCallbackException callbackException = assertThrows(UnsupportedCallbackException.class, () -> clientCallbackHandler.handle(new Callback[]{new Callback() { }})); assertTrue(callbackException.getMessage().startsWith("Unsupported")); } @Test public void testDebugClassString() { String debug1 = IAMClientCallbackHandler.debugClassString(this.getClass()); assertTrue(debug1.contains("software.amazon.msk.auth.iam.IAMClientCallbackHandlerTest")); IAMClientCallbackHandler clientCallbackHandler = new IAMClientCallbackHandler(); String debug2 = IAMClientCallbackHandler.debugClassString(clientCallbackHandler.getClass()); assertTrue(debug2.contains("software.amazon.msk.auth.iam.IAMClientCallbackHandler")); } }
5,567
0
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam/IAMOAuthBearerLoginCallbackHandlerTest.java
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package software.amazon.msk.auth.iam; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.text.ParseException; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Base64; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import javax.security.auth.callback.Callback; import javax.security.auth.callback.UnsupportedCallbackException; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule; import org.apache.kafka.common.security.oauthbearer.OAuthBearerToken; import org.apache.kafka.common.security.oauthbearer.OAuthBearerTokenCallback; import org.apache.kafka.common.security.scram.ScramCredentialCallback; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.amazonaws.auth.internal.SignerConstants; import static org.junit.jupiter.api.Assertions.assertTrue; public class IAMOAuthBearerLoginCallbackHandlerTest { private static final String ACCESS_KEY_VALUE = "ACCESS_KEY_VALUE"; private static final String SECRET_KEY_VALUE = "SECRET_KEY_VALUE"; private static final String SESSION_TOKEN = "SESSION_TOKEN"; private static final String TEST_REGION = "us-west-1"; @Test public void configureWithInvalidMechanismShouldFail() { // Given IAMOAuthBearerLoginCallbackHandler iamOAuthBearerLoginCallbackHandler = new IAMOAuthBearerLoginCallbackHandler(); // When & Then Assertions.assertThrows(IllegalArgumentException.class, () -> iamOAuthBearerLoginCallbackHandler.configure( Collections.emptyMap(), "SCRAM-SHA-512", Collections.emptyList())); } @Test public void handleWithoutConfigureShouldThrow() { // Given IAMOAuthBearerLoginCallbackHandler iamoAuthBearerLoginCallbackHandler = new IAMOAuthBearerLoginCallbackHandler(); // When & Then Assertions.assertThrows(IllegalStateException.class, () -> iamoAuthBearerLoginCallbackHandler.handle(new Callback[]{new OAuthBearerTokenCallback()})); } @Test public void handleWithDifferentCallbackShouldThrow() { // Given IAMOAuthBearerLoginCallbackHandler iamoAuthBearerLoginCallbackHandler = new IAMOAuthBearerLoginCallbackHandler(); iamoAuthBearerLoginCallbackHandler.configure( Collections.emptyMap(), OAuthBearerLoginModule.OAUTHBEARER_MECHANISM, Collections.emptyList()); // When & Then Assertions.assertThrows(UnsupportedCallbackException.class, () -> iamoAuthBearerLoginCallbackHandler.handle(new Callback[]{new ScramCredentialCallback()})); } @Test public void handleWithTokenValuePresentShouldThrow() { // Given IAMOAuthBearerLoginCallbackHandler iamoAuthBearerLoginCallbackHandler = new IAMOAuthBearerLoginCallbackHandler(); iamoAuthBearerLoginCallbackHandler.configure( Collections.emptyMap(), OAuthBearerLoginModule.OAUTHBEARER_MECHANISM, Collections.emptyList()); OAuthBearerTokenCallback callback = new OAuthBearerTokenCallback(); callback.token(getTestToken("token")); // When & Then Assertions.assertThrows(IllegalArgumentException.class, () -> iamoAuthBearerLoginCallbackHandler.handle(new Callback[]{callback})); } @Test public void handleWithDefaultCredentials() throws IOException, UnsupportedCallbackException, URISyntaxException, ParseException { // Given IAMOAuthBearerLoginCallbackHandler iamoAuthBearerLoginCallbackHandler = new IAMOAuthBearerLoginCallbackHandler(); iamoAuthBearerLoginCallbackHandler.configure( Collections.emptyMap(), OAuthBearerLoginModule.OAUTHBEARER_MECHANISM, Collections.emptyList()); System.setProperty("aws.accessKeyId", ACCESS_KEY_VALUE); System.setProperty("aws.secretKey", SECRET_KEY_VALUE); System.setProperty("aws.sessionToken", SESSION_TOKEN); System.setProperty("aws.region", TEST_REGION); OAuthBearerTokenCallback callback = new OAuthBearerTokenCallback(); // When iamoAuthBearerLoginCallbackHandler.handle(new Callback[]{callback}); // Then assertTokenValidity(callback.token(), TEST_REGION, ACCESS_KEY_VALUE, SESSION_TOKEN); cleanUp(); } @Test public void testGovCloudRegionHandler() throws IOException, UnsupportedCallbackException, URISyntaxException, ParseException { // Given IAMOAuthBearerLoginCallbackHandler iamoAuthBearerLoginCallbackHandler = new IAMOAuthBearerLoginCallbackHandler(); iamoAuthBearerLoginCallbackHandler.configure( Collections.emptyMap(), OAuthBearerLoginModule.OAUTHBEARER_MECHANISM, Collections.emptyList()); System.setProperty("aws.accessKeyId", ACCESS_KEY_VALUE); System.setProperty("aws.secretKey", SECRET_KEY_VALUE); System.setProperty("aws.sessionToken", SESSION_TOKEN); System.setProperty("aws.region", "us-gov-west-2"); OAuthBearerTokenCallback callback = new OAuthBearerTokenCallback(); // When iamoAuthBearerLoginCallbackHandler.handle(new Callback[]{callback}); // Then assertTokenValidity(callback.token(), "us-gov-west-2", ACCESS_KEY_VALUE, SESSION_TOKEN); cleanUp(); } @Test public void handleWithProfileCredentials() throws IOException, UnsupportedCallbackException, URISyntaxException, ParseException { // Given final String accessKey = "PROFILE_ACCESS_KEY"; final String secretKey = "PROFILE_SECRET_KEY"; final String sessionToken = "PROFILE_SESSION_TOKEN"; final String profileName = "dev"; IAMOAuthBearerLoginCallbackHandler iamoAuthBearerLoginCallbackHandler = new IAMOAuthBearerLoginCallbackHandler(); iamoAuthBearerLoginCallbackHandler.configure( Collections.singletonMap("awsProfileName", profileName), OAuthBearerLoginModule.OAUTHBEARER_MECHANISM, Collections.emptyList()); System.setProperty("aws.accessKeyId", accessKey); System.setProperty("aws.secretKey", secretKey); System.setProperty("aws.sessionToken", sessionToken); System.setProperty("aws.profile", profileName); System.setProperty("aws.region", TEST_REGION); OAuthBearerTokenCallback callback = new OAuthBearerTokenCallback(); // When iamoAuthBearerLoginCallbackHandler.handle(new Callback[]{callback}); // Then assertTokenValidity(callback.token(), TEST_REGION, accessKey, sessionToken); cleanUp(); } @Test public void testDebugClassString() { String debug1 = IAMOAuthBearerLoginCallbackHandler.debugClassString(this.getClass()); assertTrue(debug1.contains("software.amazon.msk.auth.iam.IAMOAuthBearerLoginCallbackHandlerTest")); IAMOAuthBearerLoginCallbackHandler loginCallbackHandler = new IAMOAuthBearerLoginCallbackHandler(); String debug2 = IAMOAuthBearerLoginCallbackHandler.debugClassString(loginCallbackHandler.getClass()); assertTrue(debug2.contains("software.amazon.msk.auth.iam.IAMOAuthBearerLoginCallbackHandler")); } private OAuthBearerToken getTestToken(final String tokenValue) { return new IAMOAuthBearerToken(tokenValue, TimeUnit.MINUTES.toSeconds(15)); } private void assertTokenValidity(OAuthBearerToken token, String region, String accessKey, String sessionToken) throws URISyntaxException, ParseException { Assertions.assertNotNull(token); String tokenValue = token.value(); Assertions.assertNotNull(tokenValue); Assertions.assertEquals("kafka-cluster", token.principalName()); Assertions.assertEquals(Collections.emptySet(), token.scope()); Assertions.assertTrue(token.startTimeMs() <= System.currentTimeMillis()); byte[] tokenBytes = tokenValue.getBytes(StandardCharsets.UTF_8); String decodedPresignedUrl = new String(Base64.getUrlDecoder() .decode(tokenBytes), StandardCharsets.UTF_8); final URI uri = new URI(decodedPresignedUrl); Assertions.assertEquals(String.format("kafka.%s.amazonaws.com", region), uri.getHost()); Assertions.assertEquals("https", uri.getScheme()); List<NameValuePair> params = URLEncodedUtils.parse(uri, StandardCharsets.UTF_8); Map<String, String> paramMap = params.stream() .collect(Collectors.toMap(NameValuePair::getName, NameValuePair::getValue)); Assertions.assertEquals("kafka-cluster:Connect", paramMap.get("Action")); Assertions.assertEquals(SignerConstants.AWS4_SIGNING_ALGORITHM, paramMap.get(SignerConstants.X_AMZ_ALGORITHM)); final Integer expirySeconds = Integer.parseInt(paramMap.get(SignerConstants.X_AMZ_EXPIRES)); Assertions.assertTrue(expirySeconds <= 900); Assertions.assertTrue(token.lifetimeMs() <= System.currentTimeMillis() + Integer.parseInt(paramMap.get(SignerConstants.X_AMZ_EXPIRES)) * 1000); Assertions.assertEquals(sessionToken, paramMap.get(SignerConstants.X_AMZ_SECURITY_TOKEN)); Assertions.assertEquals("host", paramMap.get(SignerConstants.X_AMZ_SIGNED_HEADER)); String credential = paramMap.get(SignerConstants.X_AMZ_CREDENTIAL); Assertions.assertNotNull(credential); String[] credentialArray = credential.split("/"); Assertions.assertEquals(5, credentialArray.length); Assertions.assertEquals(accessKey, credentialArray[0]); Assertions.assertEquals("kafka-cluster", credentialArray[3]); Assertions.assertEquals(SignerConstants.AWS4_TERMINATOR, credentialArray[4]); DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'"); final LocalDateTime signedDate = LocalDateTime.parse(paramMap.get(SignerConstants.X_AMZ_DATE), dateFormat); long signedDateEpochMillis = signedDate.toInstant(ZoneOffset.UTC) .toEpochMilli(); Assertions.assertTrue(signedDateEpochMillis <= Instant.now() .toEpochMilli()); Assertions.assertEquals(signedDateEpochMillis, token.startTimeMs()); Assertions.assertEquals(signedDateEpochMillis + expirySeconds * 1000, token.lifetimeMs()); String userAgent = paramMap.get("User-Agent"); Assertions.assertNotNull(userAgent); Assertions.assertTrue(userAgent.startsWith("aws-msk-iam-auth")); } private void cleanUp() { System.clearProperty("aws.accessKeyId"); System.clearProperty("aws.secretKey"); System.clearProperty("aws.sessionToken"); System.clearProperty("aws.profile"); System.clearProperty("aws.region"); } }
5,568
0
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam/ProducerClientTest.java
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package software.amazon.msk.auth.iam; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerRecord; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import java.util.Properties; public class ProducerClientTest { private static final String SASL_IAM_JAAS_CONFIG_VALUE = "software.amazon.msk.auth.iam.IAMLoginModule required awsProfileName=\"dadada bbbb\";"; @Test @Tag("ignored") public void testProducer() { Properties producerProperties = new Properties(); producerProperties.put("bootstrap.servers", "localhost:9092"); producerProperties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); producerProperties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); producerProperties.put("sasl.jaas.config", SASL_IAM_JAAS_CONFIG_VALUE); producerProperties.put("security.protocol", "SASL_SSL"); producerProperties.put("sasl.mechanism", "AWS_MSK_IAM"); producerProperties .put("sasl.client.callback.handler.class", "software.amazon.msk.auth.iam.IAMClientCallbackHandler"); KafkaProducer<String, String> producer = new KafkaProducer<String, String>(producerProperties); producer.send(new ProducerRecord<>("test", "keys", "values")); } }
5,569
0
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam/internals/IAMSaslClientTest.java
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package software.amazon.msk.auth.iam.internals; import com.amazonaws.auth.BasicAWSCredentials; import org.junit.jupiter.api.BeforeEach; import software.amazon.msk.auth.iam.IAMClientCallbackHandler; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.lang3.RandomStringUtils; import org.apache.kafka.common.errors.IllegalSaslStateException; import org.junit.jupiter.api.Test; import software.amazon.msk.auth.iam.internals.IAMSaslClient.ClassLoaderAwareIAMSaslClientFactory; import static java.util.Collections.emptyMap; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import javax.security.sasl.SaslClient; import javax.security.sasl.SaslException; import java.io.IOException; import java.text.ParseException; import java.util.Collections; import java.util.function.Supplier; public class IAMSaslClientTest { private static final String VALID_HOSTNAME = "b-3.unit-test.abcdef.kafka.us-west-2.amazonaws.com"; private static final String AWS_MSK_IAM = "AWS_MSK_IAM"; private static final String ACCESS_KEY_VALUE = "ACCESS_KEY_VALUE"; private static final String SECRET_KEY_VALUE = "SECRET_KEY_VALUE"; private static final String ACCESS_KEY_VALUE_TWO = "ACCESS_KEY_VALUE_TWO"; private static final String SECRET_KEY_VALUE_TWO = "SECRET_KEY_VALUE_TWO"; private static final String RESPONSE_VERSION = "2020_10_22"; private static final BasicAWSCredentials BASIC_AWS_CREDENTIALS = new BasicAWSCredentials(ACCESS_KEY_VALUE, SECRET_KEY_VALUE); @BeforeEach public void setUp() { IAMSaslClientProvider.initialize(); } @Test public void testCompleteValidExchange() throws IOException { IAMSaslClient saslClient = getSuccessfulIAMClient(getIamClientCallbackHandler()); runValidExchangeForSaslClient(saslClient, ACCESS_KEY_VALUE, SECRET_KEY_VALUE); } private void runValidExchangeForSaslClient(IAMSaslClient saslClient, String accessKey, String secretKey) { assertEquals(getMechanismName(), saslClient.getMechanismName()); assertTrue(saslClient.hasInitialResponse()); SystemPropertyCredentialsUtils.runTestWithSystemPropertyCredentials(() -> { try { byte[] response = saslClient.evaluateChallenge(new byte[] {}); SignedPayloadValidatorUtils .validatePayload(response, AuthenticationRequestParams .create(VALID_HOSTNAME, new BasicAWSCredentials(accessKey, secretKey), UserAgentUtils.getUserAgentValue())); assertFalse(saslClient.isComplete()); String requestId = RandomStringUtils.randomAlphabetic(10); saslClient.evaluateChallenge(getServerResponse(RESPONSE_VERSION, requestId)); assertTrue(saslClient.isComplete()); assertEquals(requestId, saslClient.getResponseRequestId()); } catch (Exception e) { throw new RuntimeException("Test failed", e); } }, accessKey, secretKey); } private byte [] getServerResponse(String version, String requestId) throws JsonProcessingException { AuthenticationResponse response = new AuthenticationResponse(version, requestId); return new ObjectMapper().writeValueAsBytes(response); } @Test public void testMultipleSaslClients() throws IOException, ParseException { IAMClientCallbackHandler cbh = getIamClientCallbackHandler(); //test the first Sasl client with 1 set of credentials. IAMSaslClient saslClient1 = getSuccessfulIAMClient(cbh); runValidExchangeForSaslClient(saslClient1, ACCESS_KEY_VALUE, SECRET_KEY_VALUE); //test second sasl client with another set of credentials IAMSaslClient saslClient2 = getSuccessfulIAMClient(cbh); runValidExchangeForSaslClient(saslClient2, ACCESS_KEY_VALUE_TWO, SECRET_KEY_VALUE_TWO); } private IAMClientCallbackHandler getIamClientCallbackHandler() { IAMClientCallbackHandler cbh = new IAMClientCallbackHandler(); cbh.configure(emptyMap(), AWS_MSK_IAM, Collections.emptyList()); return cbh; } @Test public void testNonEmptyChallenge() throws SaslException { SaslClient saslClient = getSuccessfulIAMClient(getIamClientCallbackHandler()); SystemPropertyCredentialsUtils.runTestWithSystemPropertyCredentials(() -> { assertThrows(SaslException.class, () -> saslClient.evaluateChallenge(new byte[]{2, 3})); }, ACCESS_KEY_VALUE, SECRET_KEY_VALUE); assertFalse(saslClient.isComplete()); } @Test public void testFailedCallback() throws SaslException { SaslClient saslClient = getFailureIAMClient(); assertThrows(SaslException.class, () -> saslClient.evaluateChallenge(new byte[]{})); assertFalse(saslClient.isComplete()); } @Test public void testThrowingCallback() throws SaslException { SaslClient saslClient = getThrowingIAMClient(); assertThrows(SaslException.class, () -> saslClient.evaluateChallenge(new byte[]{})); assertFalse(saslClient.isComplete()); } @Test public void testInvalidServerResponse() throws SaslException { SaslClient saslClient = getSuccessfulIAMClient(getIamClientCallbackHandler()); assertEquals(getMechanismName(), saslClient.getMechanismName()); assertTrue(saslClient.hasInitialResponse()); SystemPropertyCredentialsUtils.runTestWithSystemPropertyCredentials(() -> { try { saslClient.evaluateChallenge(new byte[]{}); } catch (SaslException e) { throw new RuntimeException("Test failed", e); } assertFalse(saslClient.isComplete()); assertThrows(SaslException.class, () -> saslClient.evaluateChallenge(new byte[]{3, 4})); assertFalse(saslClient.isComplete()); assertThrows(IllegalSaslStateException.class, () -> saslClient.evaluateChallenge(new byte[]{})); }, ACCESS_KEY_VALUE, SECRET_KEY_VALUE); } @Test public void testInvalidResponseVersion() throws SaslException { SaslClient saslClient = getSuccessfulIAMClient(getIamClientCallbackHandler()); SystemPropertyCredentialsUtils.runTestWithSystemPropertyCredentials(() -> { try { saslClient.evaluateChallenge(new byte[]{}); } catch (SaslException e) { throw new RuntimeException("Test failed", e); } assertFalse(saslClient.isComplete()); assertThrows(SaslException.class, () -> saslClient.evaluateChallenge(getResponseWithInvalidVersion())); assertFalse(saslClient.isComplete()); assertThrows(IllegalSaslStateException.class, () -> saslClient.evaluateChallenge(new byte[]{})); }, ACCESS_KEY_VALUE, SECRET_KEY_VALUE); } private byte[] getResponseWithInvalidVersion() { AuthenticationResponse response = new AuthenticationResponse(RESPONSE_VERSION, "TEST_REQUEST_ID"); try { return new ObjectMapper().writeValueAsString(response).replaceAll(RESPONSE_VERSION,"INVALID_VERSION").getBytes(); } catch (JsonProcessingException e) { throw new RuntimeException("Test failed", e); } } @Test public void testEmptyServerResponse() throws SaslException { SaslClient saslClient = getSuccessfulIAMClient(getIamClientCallbackHandler()); assertEquals(getMechanismName(), saslClient.getMechanismName()); assertTrue(saslClient.hasInitialResponse()); SystemPropertyCredentialsUtils.runTestWithSystemPropertyCredentials(() -> { try { saslClient.evaluateChallenge(new byte[]{}); } catch (SaslException e) { throw new RuntimeException("Test failed", e); } assertFalse(saslClient.isComplete()); assertThrows(SaslException.class, () -> saslClient.evaluateChallenge(new byte[]{})); assertFalse(saslClient.isComplete()); }, ACCESS_KEY_VALUE, SECRET_KEY_VALUE); } @Test public void testFactoryMechanisms() { assertArrayEquals(new String[] { getMechanismName() }, new IAMSaslClient.IAMSaslClientFactory().getMechanismNames(emptyMap())); } @Test public void testInvalidMechanism() { assertThrows(SaslException.class, () -> new IAMSaslClient.IAMSaslClientFactory() .createSaslClient(new String[]{AWS_MSK_IAM + "BAD"}, "AUTH_ID", "PROTOCOL", VALID_HOSTNAME, emptyMap(), new SuccessfulIAMCallbackHandler(BASIC_AWS_CREDENTIALS))); } @Test public void testClassLoaderAwareIAMSaslClientFactoryMechanisms() { assertArrayEquals(new String[] { AWS_MSK_IAM }, new ClassLoaderAwareIAMSaslClientFactory().getMechanismNames(emptyMap())); } private static class SuccessfulIAMCallbackHandler extends IAMClientCallbackHandler { private final BasicAWSCredentials basicAWSCredentials; public SuccessfulIAMCallbackHandler(BasicAWSCredentials basicAWSCredentials) { this.basicAWSCredentials = basicAWSCredentials; } @Override protected void handleCallback(AWSCredentialsCallback callback) { callback.setAwsCredentials(basicAWSCredentials); } } private IAMSaslClient getSuccessfulIAMClient(IAMClientCallbackHandler cbh) throws SaslException { return getIAMClient(() -> cbh); } private SaslClient getFailureIAMClient() throws SaslException { return getIAMClient(() -> new IAMClientCallbackHandler() { @Override protected void handleCallback(AWSCredentialsCallback callback) { callback.setLoadingException(new IllegalArgumentException("TEST Exception")); } }); } private SaslClient getThrowingIAMClient() throws SaslException { return getIAMClient(() -> new IAMClientCallbackHandler() { @Override protected void handleCallback(AWSCredentialsCallback callback) throws IOException { throw new IOException("TEST IO Exception"); } }); } private IAMSaslClient getIAMClient(Supplier<IAMClientCallbackHandler> handlerSupplier) throws SaslException { return (IAMSaslClient) new IAMSaslClient.ClassLoaderAwareIAMSaslClientFactory() .createSaslClient(new String[] { AWS_MSK_IAM }, "AUTH_ID", "PROTOCOL", VALID_HOSTNAME, emptyMap(), handlerSupplier.get()); } private String getMechanismName() { return AWS_MSK_IAM + "." + getClass().getClassLoader().hashCode(); } }
5,570
0
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam/internals/SignedPayloadValidatorUtils.java
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package software.amazon.msk.auth.iam.internals; import com.amazonaws.auth.internal.SignerConstants; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.Instant; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; public final class SignedPayloadValidatorUtils { private static final String VERSION = "version"; private static final String HOST = "host"; private static final String[] requiredKeys = {VERSION, HOST, SignerConstants.X_AMZ_CREDENTIAL.toLowerCase(), SignerConstants.X_AMZ_DATE.toLowerCase(), SignerConstants.X_AMZ_SIGNED_HEADER.toLowerCase(), SignerConstants.X_AMZ_EXPIRES.toLowerCase(), SignerConstants.X_AMZ_SIGNATURE.toLowerCase(), SignerConstants.X_AMZ_ALGORITHM.toLowerCase()}; private static final String ACTION = "action"; private static final String[] optionalKeys = { "x-amz-security-token", ACTION, }; private static final SimpleDateFormat dateFormat = new SimpleDateFormat("YYYYMMDD\'T\'HHMMSS\'Z\'"); private SignedPayloadValidatorUtils() { } public static void validatePayload(byte[] payload, AuthenticationRequestParams params) throws IOException, ParseException { ObjectMapper mapper = new ObjectMapper(); Map<String, String> propertyMap = (Map<String, String>) mapper.readValue(payload, Map.class); assertEquals(10, propertyMap.size()); //check if all required keys are present and non-empty List<String> missingRequiredKeys = Arrays.stream(requiredKeys) .filter(k -> propertyMap.get(k) == null || propertyMap.get(k).isEmpty()) .collect(Collectors.toList()); assertTrue(missingRequiredKeys.isEmpty()); // check values for some keys assertEquals("2020_10_22", propertyMap.get(VERSION)); assertEquals(params.getHost(), propertyMap.get(HOST)); assertEquals("kafka-cluster:Connect", propertyMap.get(ACTION)); assertEquals("host", propertyMap.get(SignerConstants.X_AMZ_SIGNED_HEADER.toLowerCase())); assertEquals(SignerConstants.AWS4_SIGNING_ALGORITHM, propertyMap.get(SignerConstants.X_AMZ_ALGORITHM.toLowerCase())); assertTrue(dateFormat.parse(propertyMap.get(SignerConstants.X_AMZ_DATE.toLowerCase())).toInstant() .isBefore(Instant.now())); assertTrue(Integer.parseInt(propertyMap.get(SignerConstants.X_AMZ_EXPIRES.toLowerCase())) <= 900); String credential = propertyMap.get(SignerConstants.X_AMZ_CREDENTIAL.toLowerCase()); assertNotNull(credential); String[] credentialArray = credential.split("/"); assertEquals(5, credentialArray.length); assertEquals(params.getAwsCredentials().getAWSAccessKeyId(), credentialArray[0]); String userAgent = propertyMap.get("user-agent"); assertNotNull(userAgent); assertTrue(userAgent.startsWith("aws-msk-iam-auth")); } }
5,571
0
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam/internals/MSKCredentialProviderTest.java
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package software.amazon.msk.auth.iam.internals; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import com.amazonaws.SdkBaseException; import com.amazonaws.SdkClientException; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.AWSCredentialsProviderChain; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.auth.BasicSessionCredentials; import com.amazonaws.auth.EC2ContainerCredentialsProviderWrapper; import com.amazonaws.auth.EnvironmentVariableCredentialsProvider; import com.amazonaws.auth.STSAssumeRoleSessionCredentialsProvider; import com.amazonaws.auth.SystemPropertiesCredentialsProvider; import com.amazonaws.auth.WebIdentityTokenCredentialsProvider; import com.amazonaws.services.securitytoken.AWSSecurityTokenService; import com.amazonaws.services.securitytoken.model.GetCallerIdentityRequest; import com.amazonaws.services.securitytoken.model.GetCallerIdentityResult; import software.amazon.awssdk.profiles.ProfileFile; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static software.amazon.msk.auth.iam.internals.SystemPropertyCredentialsUtils.runTestWithSystemPropertyCredentials; import static software.amazon.msk.auth.iam.internals.SystemPropertyCredentialsUtils.runTestWithSystemPropertyProfile; public class MSKCredentialProviderTest { private static final String ACCESS_KEY_VALUE = "ACCESS_KEY_VALUE"; private static final String SECRET_KEY_VALUE = "SECRET_KEY_VALUE"; private static final String ACCESS_KEY_VALUE_TWO = "ACCESS_KEY_VALUE_TWO"; private static final String SECRET_KEY_VALUE_TWO = "SECRET_KEY_VALUE_TWO"; private static final String TEST_PROFILE_NAME = "test_profile"; private static final String PROFILE_ACCESS_KEY_VALUE = "PROFILE_ACCESS_KEY"; private static final String PROFILE_SECRET_KEY_VALUE = "PROFILE_SECRET_KEY"; private static final String TEST_ROLE_ARN = "TEST_ROLE_ARN"; private static final String TEST_ROLE_EXTERNAL_ID = "TEST_EXTERNAL_ID"; private static final String TEST_ROLE_SESSION_NAME = "TEST_ROLE_SESSION_NAME"; private static final String SESSION_TOKEN = "SESSION_TOKEN"; private static final String AWS_ROLE_ARN = "awsRoleArn"; private static final String AWS_ROLE_EXTERNAL_ID = "awsRoleExternalId"; private static final String AWS_ROLE_ACCESS_KEY_ID = "awsRoleAccessKeyId"; private static final String AWS_ROLE_SECRET_ACCESS_KEY = "awsRoleSecretAccessKey"; private static final String AWS_PROFILE_NAME = "awsProfileName"; private static final String AWS_DEBUG_CREDS_NAME = "awsDebugCreds"; /** * If no options are passed in it should use the default credentials provider * which should pick up the java system properties. */ @Test public void testNoOptions() { runDefaultTest(); } private void runDefaultTest() { runTestWithSystemPropertyCredentials(() -> { MSKCredentialProvider provider = new MSKCredentialProvider(Collections.emptyMap()); assertFalse(provider.getShouldDebugCreds()); AWSCredentials credentials = provider.getCredentials(); assertEquals(ACCESS_KEY_VALUE, credentials.getAWSAccessKeyId()); assertEquals(SECRET_KEY_VALUE, credentials.getAWSSecretKey()); }, ACCESS_KEY_VALUE, SECRET_KEY_VALUE); } /** * If a profile name is passed in but there is no profile by that name * it should still use the default credential provider. */ @Test public void testMissingProfileName() { runTestWithSystemPropertyCredentials(() -> { Map<String, String> optionsMap = new HashMap<>(); optionsMap.put(AWS_PROFILE_NAME, "MISSING_PROFILE"); MSKCredentialProvider provider = new MSKCredentialProvider(optionsMap); AWSCredentials credentials = provider.getCredentials(); assertEquals(ACCESS_KEY_VALUE, credentials.getAWSAccessKeyId()); assertEquals(SECRET_KEY_VALUE, credentials.getAWSSecretKey()); }, ACCESS_KEY_VALUE, SECRET_KEY_VALUE); } /** * If the credentials available to the default credential provider change, * the new credentials should be picked up. * * @throws IOException */ @Test public void testChangingCredentials() throws IOException { runDefaultTest(); runTestWithSystemPropertyProfile(() -> { ProfileFile profileFile = getProfileFile(); MSKCredentialProvider provider = new MSKCredentialProvider(Collections.emptyMap()) { protected AWSCredentialsProviderChain getDefaultProvider() { return new AWSCredentialsProviderChain(new EnvironmentVariableCredentialsProvider(), new SystemPropertiesCredentialsProvider(), WebIdentityTokenCredentialsProvider.create(), new EnhancedProfileCredentialsProvider(profileFile, null), new EC2ContainerCredentialsProviderWrapper()); } }; AWSCredentials credentials = provider.getCredentials(); assertEquals(PROFILE_ACCESS_KEY_VALUE, credentials.getAWSAccessKeyId()); assertEquals(PROFILE_SECRET_KEY_VALUE, credentials.getAWSSecretKey()); }, TEST_PROFILE_NAME); } @Test public void testProfileName() { ProfileFile profileFile = getProfileFile(); Map<String, String> optionsMap = new HashMap<>(); optionsMap.put(AWS_PROFILE_NAME, "test_profile"); MSKCredentialProvider.ProviderBuilder providerBuilder = new MSKCredentialProvider.ProviderBuilder(optionsMap) { EnhancedProfileCredentialsProvider createEnhancedProfileCredentialsProvider(String profileName) { assertEquals(TEST_PROFILE_NAME, profileName); return new EnhancedProfileCredentialsProvider(profileFile, TEST_PROFILE_NAME); } }; MSKCredentialProvider provider = new MSKCredentialProvider(providerBuilder); assertFalse(provider.getShouldDebugCreds()); AWSCredentials credentials = provider.getCredentials(); assertEquals(PROFILE_ACCESS_KEY_VALUE, credentials.getAWSAccessKeyId()); assertEquals(PROFILE_SECRET_KEY_VALUE, credentials.getAWSSecretKey()); } @Test public void testAwsRoleArn() { STSAssumeRoleSessionCredentialsProvider mockStsRoleProvider = Mockito .mock(STSAssumeRoleSessionCredentialsProvider.class); Mockito.when(mockStsRoleProvider.getCredentials()) .thenReturn(new BasicSessionCredentials(ACCESS_KEY_VALUE, SECRET_KEY_VALUE, SESSION_TOKEN)); Map<String, String> optionsMap = new HashMap<>(); optionsMap.put(AWS_ROLE_ARN, TEST_ROLE_ARN); MSKCredentialProvider.ProviderBuilder providerBuilder = getProviderBuilder(mockStsRoleProvider, optionsMap, "aws-msk-iam-auth"); MSKCredentialProvider provider = new MSKCredentialProvider(providerBuilder); assertFalse(provider.getShouldDebugCreds()); AWSCredentials credentials = provider.getCredentials(); validateBasicSessionCredentials(credentials); provider.close(); Mockito.verify(mockStsRoleProvider, times(1)).close(); } @Test public void testAwsRoleArnWithAccessKey() { STSAssumeRoleSessionCredentialsProvider mockStsRoleProvider = Mockito .mock(STSAssumeRoleSessionCredentialsProvider.class); Mockito.when(mockStsRoleProvider.getCredentials()) .thenAnswer(invocation -> new BasicSessionCredentials(ACCESS_KEY_VALUE_TWO, SECRET_KEY_VALUE_TWO, SESSION_TOKEN)); Map<String, String> optionsMap = new HashMap<>(); optionsMap.put(AWS_ROLE_ARN, TEST_ROLE_ARN); optionsMap.put(AWS_ROLE_ACCESS_KEY_ID, ACCESS_KEY_VALUE_TWO); optionsMap.put(AWS_ROLE_SECRET_ACCESS_KEY, SECRET_KEY_VALUE_TWO); MSKCredentialProvider.ProviderBuilder providerBuilder = getProviderBuilderWithCredentials(mockStsRoleProvider, optionsMap, "aws-msk-iam-auth"); MSKCredentialProvider provider = new MSKCredentialProvider(providerBuilder); assertFalse(provider.getShouldDebugCreds()); AWSCredentials credentials = provider.getCredentials(); validateBasicSessionCredentialsTwo(credentials); provider.close(); Mockito.verify(mockStsRoleProvider, times(1)).close(); } @Test public void testAwsRoleArnWithDebugCreds() { STSAssumeRoleSessionCredentialsProvider mockStsRoleProvider = Mockito .mock(STSAssumeRoleSessionCredentialsProvider.class); Mockito.when(mockStsRoleProvider.getCredentials()) .thenReturn(new BasicSessionCredentials(ACCESS_KEY_VALUE, SECRET_KEY_VALUE, SESSION_TOKEN)); Map<String, String> optionsMap = new HashMap<>(); optionsMap.put(AWS_ROLE_ARN, TEST_ROLE_ARN); optionsMap.put(AWS_DEBUG_CREDS_NAME, "true"); MSKCredentialProvider.ProviderBuilder providerBuilder = getProviderBuilder(mockStsRoleProvider, optionsMap, "aws-msk-iam-auth"); AWSSecurityTokenService mockSts = Mockito.mock(AWSSecurityTokenService.class); Mockito.when(mockSts.getCallerIdentity(Mockito.any(GetCallerIdentityRequest.class))).thenReturn(new GetCallerIdentityResult().withUserId("TEST_USER_ID").withAccount("TEST_ACCOUNT").withArn("TEST_ARN")); MSKCredentialProvider provider = new MSKCredentialProvider(providerBuilder) { AWSSecurityTokenService getStsClientForDebuggingCreds(AWSCredentials credentials) { return mockSts; } }; assertTrue(provider.getShouldDebugCreds()); AWSCredentials credentials = provider.getCredentials(); validateBasicSessionCredentials(credentials); provider.close(); Mockito.verify(mockStsRoleProvider, times(1)).close(); Mockito.verify(mockSts, times(1)).getCallerIdentity(any(GetCallerIdentityRequest.class)); } @Test public void testEc2CredsWithDebugCredsNoAccessToSts_Succeed() { Map<String, String> optionsMap = new HashMap<>(); optionsMap.put(AWS_DEBUG_CREDS_NAME, "true"); EC2ContainerCredentialsProviderWrapper mockEc2CredsProvider = Mockito.mock(EC2ContainerCredentialsProviderWrapper.class); Mockito.when(mockEc2CredsProvider.getCredentials()) .thenReturn(new BasicAWSCredentials(ACCESS_KEY_VALUE_TWO, SECRET_KEY_VALUE_TWO)); AWSSecurityTokenService mockSts = Mockito.mock(AWSSecurityTokenService.class); Mockito.when(mockSts.getCallerIdentity(Mockito.any(GetCallerIdentityRequest.class))) .thenThrow(new SdkClientException("TEST TEST")); MSKCredentialProvider provider = new MSKCredentialProvider(optionsMap) { protected AWSCredentialsProviderChain getDefaultProvider() { return new AWSCredentialsProviderChain(mockEc2CredsProvider); } AWSSecurityTokenService getStsClientForDebuggingCreds(AWSCredentials credentials) { return mockSts; } }; assertTrue(provider.getShouldDebugCreds()); AWSCredentials credentials = provider.getCredentials(); validateBasicCredentialsTwo(credentials); provider.close(); Mockito.verify(mockSts, times(1)).getCallerIdentity(Mockito.any()); Mockito.verify(mockEc2CredsProvider, times(1)).getCredentials(); Mockito.verifyNoMoreInteractions(mockEc2CredsProvider); } @Test public void testAwsRoleArnAndSessionName() { STSAssumeRoleSessionCredentialsProvider mockStsRoleProvider = Mockito .mock(STSAssumeRoleSessionCredentialsProvider.class); Mockito.when(mockStsRoleProvider.getCredentials()) .thenReturn(new BasicSessionCredentials(ACCESS_KEY_VALUE, SECRET_KEY_VALUE, SESSION_TOKEN)); Map<String, String> optionsMap = new HashMap<>(); optionsMap.put(AWS_ROLE_ARN, TEST_ROLE_ARN); optionsMap.put("awsRoleSessionName", TEST_ROLE_SESSION_NAME); MSKCredentialProvider.ProviderBuilder providerBuilder = getProviderBuilder(mockStsRoleProvider, optionsMap, TEST_ROLE_SESSION_NAME); MSKCredentialProvider provider = new MSKCredentialProvider(providerBuilder); assertFalse(provider.getShouldDebugCreds()); AWSCredentials credentials = provider.getCredentials(); validateBasicSessionCredentials(credentials); provider.close(); Mockito.verify(mockStsRoleProvider, times(1)).close(); } @Test public void testAwsRoleArnSessionNameAndStsRegion() { STSAssumeRoleSessionCredentialsProvider mockStsRoleProvider = Mockito .mock(STSAssumeRoleSessionCredentialsProvider.class); Mockito.when(mockStsRoleProvider.getCredentials()) .thenReturn(new BasicSessionCredentials(ACCESS_KEY_VALUE, SECRET_KEY_VALUE, SESSION_TOKEN)); Map<String, String> optionsMap = new HashMap<>(); optionsMap.put(AWS_ROLE_ARN, TEST_ROLE_ARN); optionsMap.put("awsRoleSessionName", TEST_ROLE_SESSION_NAME); optionsMap.put("awsStsRegion", "eu-west-1"); MSKCredentialProvider.ProviderBuilder providerBuilder = new MSKCredentialProvider.ProviderBuilder(optionsMap) { STSAssumeRoleSessionCredentialsProvider createSTSRoleCredentialProvider(String roleArn, String sessionName, String stsRegion) { assertEquals(TEST_ROLE_ARN, roleArn); assertEquals(TEST_ROLE_SESSION_NAME, sessionName); assertEquals("eu-west-1", stsRegion); return mockStsRoleProvider; } }; MSKCredentialProvider provider = new MSKCredentialProvider(providerBuilder); assertFalse(provider.getShouldDebugCreds()); AWSCredentials credentials = provider.getCredentials(); validateBasicSessionCredentials(credentials); provider.close(); Mockito.verify(mockStsRoleProvider, times(1)).close(); } @Test public void testAwsRoleArnSessionNameStsRegionAndExternalId() { STSAssumeRoleSessionCredentialsProvider mockStsRoleProvider = Mockito .mock(STSAssumeRoleSessionCredentialsProvider.class); Mockito.when(mockStsRoleProvider.getCredentials()) .thenReturn(new BasicSessionCredentials(ACCESS_KEY_VALUE, SECRET_KEY_VALUE, SESSION_TOKEN)); Map<String, String> optionsMap = new HashMap<>(); optionsMap.put(AWS_ROLE_ARN, TEST_ROLE_ARN); optionsMap.put(AWS_ROLE_EXTERNAL_ID, TEST_ROLE_EXTERNAL_ID); optionsMap.put("awsRoleSessionName", TEST_ROLE_SESSION_NAME); optionsMap.put("awsStsRegion", "eu-west-1"); MSKCredentialProvider.ProviderBuilder providerBuilder = new MSKCredentialProvider.ProviderBuilder(optionsMap) { STSAssumeRoleSessionCredentialsProvider createSTSRoleCredentialProvider(String roleArn, String externalId, String sessionName, String stsRegion) { assertEquals(TEST_ROLE_ARN, roleArn); assertEquals(TEST_ROLE_EXTERNAL_ID, externalId); assertEquals(TEST_ROLE_SESSION_NAME, sessionName); assertEquals("eu-west-1", stsRegion); return mockStsRoleProvider; } }; MSKCredentialProvider provider = new MSKCredentialProvider(providerBuilder); assertFalse(provider.getShouldDebugCreds()); AWSCredentials credentials = provider.getCredentials(); validateBasicSessionCredentials(credentials); provider.close(); Mockito.verify(mockStsRoleProvider, times(1)).close(); } @Test public void testProfileNameAndRoleArn() { ProfileFile profileFile = getProfileFile(); STSAssumeRoleSessionCredentialsProvider mockStsRoleProvider = Mockito .mock(STSAssumeRoleSessionCredentialsProvider.class); Mockito.when(mockStsRoleProvider.getCredentials()) .thenReturn(new BasicSessionCredentials(ACCESS_KEY_VALUE_TWO, SECRET_KEY_VALUE_TWO, SESSION_TOKEN)); Map<String, String> optionsMap = new HashMap<>(); optionsMap.put(AWS_PROFILE_NAME, "test_profile"); optionsMap.put(AWS_ROLE_ARN, TEST_ROLE_ARN); MSKCredentialProvider.ProviderBuilder providerBuilder = new MSKCredentialProvider.ProviderBuilder(optionsMap) { EnhancedProfileCredentialsProvider createEnhancedProfileCredentialsProvider(String profileName) { assertEquals(TEST_PROFILE_NAME, profileName); return new EnhancedProfileCredentialsProvider(profileFile, TEST_PROFILE_NAME); } STSAssumeRoleSessionCredentialsProvider createSTSRoleCredentialProvider(String roleArn, String sessionName, String stsRegion) { assertEquals(TEST_ROLE_ARN, roleArn); assertEquals("aws-msk-iam-auth", sessionName); return mockStsRoleProvider; } }; MSKCredentialProvider provider = new MSKCredentialProvider(providerBuilder); assertFalse(provider.getShouldDebugCreds()); AWSCredentials credentials = provider.getCredentials(); provider.close(); assertEquals(PROFILE_ACCESS_KEY_VALUE, credentials.getAWSAccessKeyId()); assertEquals(PROFILE_SECRET_KEY_VALUE, credentials.getAWSSecretKey()); Mockito.verify(mockStsRoleProvider, times(0)).getCredentials(); Mockito.verify(mockStsRoleProvider, times(1)).close(); } @Test public void testRoleCredsWithTwoRetriableErrors() { testRoleCredsWithRetriableErrors(2); } @Test public void testRoleCredsWithThreeRetriableErrors() { testRoleCredsWithRetriableErrors(3); } @Test public void testRoleCredsWithFourRetriableErrors_ThrowsException() { int numExceptions = 4; STSAssumeRoleSessionCredentialsProvider mockStsRoleProvider = setupMockStsRoleCredentialsProviderWithRetriableExceptions(numExceptions); Map<String, String> optionsMap = new HashMap<>(); optionsMap.put(AWS_ROLE_ARN, TEST_ROLE_ARN); MSKCredentialProvider.ProviderBuilder providerBuilder = getProviderBuilder(mockStsRoleProvider, optionsMap, "aws-msk-iam-auth"); MSKCredentialProvider provider = new MSKCredentialProvider(providerBuilder) { protected AWSCredentialsProviderChain getDefaultProvider() { return new AWSCredentialsProviderChain(new EnvironmentVariableCredentialsProvider()); } }; assertFalse(provider.getShouldDebugCreds()); assertThrows(SdkClientException.class, () -> provider.getCredentials()); Mockito.verify(mockStsRoleProvider, times(numExceptions)).getCredentials(); Mockito.verifyNoMoreInteractions(mockStsRoleProvider); } @Test public void testEc2CredsWithTwoRetriableErrorsCustomRetry() { testEc2CredsWithRetriableErrorsCustomRetry(2); } @Test public void testEc2CredsWithFiveRetriableErrorsCustomRetry() { testEc2CredsWithRetriableErrorsCustomRetry(5); } @Test public void testEc2CredsWithSixRetriableErrorsCustomRetry_ThrowsException() { int numExceptions = 6; Map<String, String> optionsMap = new HashMap<>(); optionsMap.put("awsMaxRetries", "5"); AWSCredentialsProvider mockEc2CredsProvider = setupMockDefaultProviderWithRetriableExceptions(numExceptions); MSKCredentialProvider provider = new MSKCredentialProvider(optionsMap) { protected AWSCredentialsProviderChain getDefaultProvider() { return new AWSCredentialsProviderChain(mockEc2CredsProvider); } }; assertFalse(provider.getShouldDebugCreds()); assertThrows(SdkClientException.class, () -> provider.getCredentials()); Mockito.verify(mockEc2CredsProvider, times(numExceptions)).getCredentials(); Mockito.verifyNoMoreInteractions(mockEc2CredsProvider); } @Test public void testEc2CredsWithOnrRetriableErrorsCustomZeroRetry_ThrowsException() { int numExceptions = 1; Map<String, String> optionsMap = new HashMap<>(); optionsMap.put("awsMaxRetries", "0"); AWSCredentialsProvider mockEc2CredsProvider = setupMockDefaultProviderWithRetriableExceptions(numExceptions); MSKCredentialProvider provider = new MSKCredentialProvider(optionsMap) { protected AWSCredentialsProviderChain getDefaultProvider() { return new AWSCredentialsProviderChain(mockEc2CredsProvider); } }; assertFalse(provider.getShouldDebugCreds()); assertThrows(SdkClientException.class, () -> provider.getCredentials()); Mockito.verify(mockEc2CredsProvider, times(numExceptions)).getCredentials(); Mockito.verifyNoMoreInteractions(mockEc2CredsProvider); } private void testEc2CredsWithRetriableErrorsCustomRetry(int numExceptions) { Map<String, String> optionsMap = new HashMap<>(); optionsMap.put("awsMaxRetries", "5"); AWSCredentialsProvider mockEc2CredsProvider = setupMockDefaultProviderWithRetriableExceptions(numExceptions); MSKCredentialProvider provider = new MSKCredentialProvider(optionsMap) { protected AWSCredentialsProviderChain getDefaultProvider() { return new AWSCredentialsProviderChain(mockEc2CredsProvider); } }; assertFalse(provider.getShouldDebugCreds()); AWSCredentials credentials = provider.getCredentials(); validateBasicCredentialsTwo(credentials); provider.close(); Mockito.verify(mockEc2CredsProvider, times(numExceptions + 1)).getCredentials(); Mockito.verifyNoMoreInteractions(mockEc2CredsProvider); } private void testRoleCredsWithRetriableErrors(int numExceptions) { STSAssumeRoleSessionCredentialsProvider mockStsRoleProvider = setupMockStsRoleCredentialsProviderWithRetriableExceptions( numExceptions); Map<String, String> optionsMap = new HashMap<>(); optionsMap.put(AWS_ROLE_ARN, TEST_ROLE_ARN); MSKCredentialProvider.ProviderBuilder providerBuilder = getProviderBuilder(mockStsRoleProvider, optionsMap, "aws-msk-iam-auth"); MSKCredentialProvider provider = new MSKCredentialProvider(providerBuilder) { protected AWSCredentialsProviderChain getDefaultProvider() { return new AWSCredentialsProviderChain(new EnvironmentVariableCredentialsProvider()); } }; assertFalse(provider.getShouldDebugCreds()); AWSCredentials credentials = provider.getCredentials(); validateBasicSessionCredentials(credentials); provider.close(); Mockito.verify(mockStsRoleProvider, times(numExceptions + 1)).getCredentials(); Mockito.verify(mockStsRoleProvider, times(1)).close(); Mockito.verifyNoMoreInteractions(mockStsRoleProvider); } private MSKCredentialProvider.ProviderBuilder getProviderBuilder(STSAssumeRoleSessionCredentialsProvider mockStsRoleProvider, Map<String, String> optionsMap, String s) { return new MSKCredentialProvider.ProviderBuilder(optionsMap) { STSAssumeRoleSessionCredentialsProvider createSTSRoleCredentialProvider(String roleArn, String sessionName, String stsRegion) { assertEquals(TEST_ROLE_ARN, roleArn); assertEquals(s, sessionName); return mockStsRoleProvider; } }; } private MSKCredentialProvider.ProviderBuilder getProviderBuilderWithCredentials(STSAssumeRoleSessionCredentialsProvider mockStsRoleProvider, Map<String, String> optionsMap, String s) { return new MSKCredentialProvider.ProviderBuilder(optionsMap) { STSAssumeRoleSessionCredentialsProvider createSTSRoleCredentialProvider(String roleArn, String sessionName, String stsRegion, AWSCredentialsProvider credentials) { assertEquals(TEST_ROLE_ARN, roleArn); assertEquals(s, sessionName); return mockStsRoleProvider; } }; } private void validateBasicSessionCredentials(AWSCredentials credentials) { assertTrue(credentials instanceof BasicSessionCredentials); BasicSessionCredentials sessionCredentials = (BasicSessionCredentials) credentials; assertEquals(ACCESS_KEY_VALUE, sessionCredentials.getAWSAccessKeyId()); assertEquals(SECRET_KEY_VALUE, sessionCredentials.getAWSSecretKey()); assertEquals(SESSION_TOKEN, sessionCredentials.getSessionToken()); } private void validateBasicSessionCredentialsTwo(AWSCredentials credentials) { assertTrue(credentials instanceof BasicSessionCredentials); BasicSessionCredentials sessionCredentials = (BasicSessionCredentials) credentials; assertEquals(ACCESS_KEY_VALUE_TWO, sessionCredentials.getAWSAccessKeyId()); assertEquals(SECRET_KEY_VALUE_TWO, sessionCredentials.getAWSSecretKey()); assertEquals(SESSION_TOKEN, sessionCredentials.getSessionToken()); } private void validateBasicCredentialsTwo(AWSCredentials credentials) { assertTrue(credentials instanceof BasicAWSCredentials); assertEquals(ACCESS_KEY_VALUE_TWO, credentials.getAWSAccessKeyId()); assertEquals(SECRET_KEY_VALUE_TWO, credentials.getAWSSecretKey()); } private STSAssumeRoleSessionCredentialsProvider setupMockStsRoleCredentialsProviderWithRetriableExceptions(int numErrors) { SdkBaseException[] exceptionsToThrow = getSdkBaseExceptions(numErrors); STSAssumeRoleSessionCredentialsProvider mockStsRoleProvider = Mockito .mock(STSAssumeRoleSessionCredentialsProvider.class); Mockito.when(mockStsRoleProvider.getCredentials()) .thenThrow(exceptionsToThrow) .thenReturn(new BasicSessionCredentials(ACCESS_KEY_VALUE, SECRET_KEY_VALUE, SESSION_TOKEN)); return mockStsRoleProvider; } private SdkBaseException[] getSdkBaseExceptions(int numErrors) { final SdkBaseException exceptionFromProvider = new SdkClientException("TEST TEST TEST"); return IntStream.range(0, numErrors).mapToObj(i -> exceptionFromProvider) .collect(Collectors.toList()).toArray(new SdkBaseException[numErrors]); } private AWSCredentialsProvider setupMockDefaultProviderWithRetriableExceptions(int numErrors) { SdkBaseException[] exceptionsToThrow = getSdkBaseExceptions(numErrors); EC2ContainerCredentialsProviderWrapper mockEc2Provider = Mockito.mock(EC2ContainerCredentialsProviderWrapper.class); Mockito.when(mockEc2Provider.getCredentials()) .thenThrow(exceptionsToThrow) .thenReturn(new BasicAWSCredentials(ACCESS_KEY_VALUE_TWO, SECRET_KEY_VALUE_TWO)); return mockEc2Provider; } private ProfileFile getProfileFile() { return ProfileFile.builder().content(new File(getProfileResourceURL().getFile()).toPath()).type( ProfileFile.Type.CREDENTIALS).build(); } private URL getProfileResourceURL() { return getClass().getClassLoader().getResource("profile_config_file"); } }
5,572
0
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam/internals/AuthenticateRequestParamsTest.java
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package software.amazon.msk.auth.iam.internals; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; public class AuthenticateRequestParamsTest { private static final String VALID_HOSTNAME = "b-3.unit-test.abcdef.kafka.us-west-2.amazonaws.com"; private static final String HOSTNAME_NO_REGION = "abcd.efgh.com"; private AWSCredentials credentials; private static final String ACCESS_KEY = "ACCESS_KEY"; private static final String SECRET_KEY = "SECRET_KEY"; private static final String USER_AGENT = "USER_AGENT"; private static final Region TEST_EC2_REGION = Region.getRegion(Regions.US_WEST_1); @BeforeEach public void setup() { credentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY); } @Test public void testAllProperties() { AuthenticationRequestParams params = AuthenticationRequestParams .create(VALID_HOSTNAME, credentials, USER_AGENT); assertEquals("us-west-2", params.getRegion().getName()); assertEquals("kafka-cluster", params.getServiceScope()); assertEquals(USER_AGENT, params.getUserAgent()); assertEquals(VALID_HOSTNAME, params.getHost()); assertEquals(ACCESS_KEY, params.getAwsCredentials().getAWSAccessKeyId()); assertEquals(SECRET_KEY, params.getAwsCredentials().getAWSSecretKey()); } @Test public void testInvalidHost() { try (MockedStatic<Regions> regionsMockedStatic = Mockito.mockStatic(Regions.class)) { regionsMockedStatic.when(Regions::getCurrentRegion).thenReturn(null); assertThrows(IllegalArgumentException.class, () -> AuthenticationRequestParams.create(HOSTNAME_NO_REGION, credentials, USER_AGENT)); } } @Test public void testInvalidHostInEC2() { try (MockedStatic<Regions> regionsMockedStatic = Mockito.mockStatic(Regions.class)) { regionsMockedStatic.when(Regions::getCurrentRegion).thenReturn(TEST_EC2_REGION); AuthenticationRequestParams params = AuthenticationRequestParams.create(HOSTNAME_NO_REGION, credentials, USER_AGENT); assertEquals(TEST_EC2_REGION, params.getRegion()); } } }
5,573
0
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam/internals/SystemPropertyCredentialsUtils.java
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package software.amazon.msk.auth.iam.internals; public final class SystemPropertyCredentialsUtils { private static final String ACCESS_KEY_PROPERTY = "aws.accessKeyId"; private static final String SECRET_KEY_PROPERTY = "aws.secretKey"; private static final String AWS_PROFILE_SYSTEM_PROPERTY = "aws.profile"; private SystemPropertyCredentialsUtils() { } public static void runTestWithSystemPropertyCredentials(Runnable test, String accessKeyValue, String secretKeyValue) { String initialAccessKey = System.getProperty(ACCESS_KEY_PROPERTY); String initialSecretKey = System.getProperty(SECRET_KEY_PROPERTY); try { //Setup test system properties System.setProperty(ACCESS_KEY_PROPERTY, accessKeyValue); System.setProperty(SECRET_KEY_PROPERTY, secretKeyValue); test.run(); } finally { if (initialAccessKey != null) { System.setProperty(ACCESS_KEY_PROPERTY, initialAccessKey); } if (initialSecretKey != null) { System.setProperty(SECRET_KEY_PROPERTY, initialSecretKey); } } } public static void runTestWithSystemPropertyProfile(Runnable test, String profileName) { String initialProfileName = System.getProperty(AWS_PROFILE_SYSTEM_PROPERTY); try { //Setup test system properties System.setProperty(AWS_PROFILE_SYSTEM_PROPERTY, profileName); runTestWithSystemPropertyCredentials( test, "", ""); } finally { if (initialProfileName != null) { System.setProperty(AWS_PROFILE_SYSTEM_PROPERTY, initialProfileName); } } } }
5,574
0
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam
Create_ds/aws-msk-iam-auth/src/test/java/software/amazon/msk/auth/iam/internals/AWS4SignedPayloadGeneratorTest.java
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package software.amazon.msk.auth.iam.internals; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.BasicAWSCredentials; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.IOException; import java.text.ParseException; public class AWS4SignedPayloadGeneratorTest { private static final String VALID_HOSTNAME = "b-3.unit-test.abcdef.kafka.us-west-2.amazonaws.com"; private static final String ACCESS_KEY = "ACCESS_KEY"; private static final String SECRET_KEY = "SECRET_KEY"; private static final String USER_AGENT = "USER_AGENT"; private AWSCredentials credentials; @BeforeEach public void setup() { credentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY); } @Test public void testSigning() throws IOException, ParseException { AuthenticationRequestParams params = AuthenticationRequestParams .create(VALID_HOSTNAME, credentials, UserAgentUtils.getUserAgentValue()); AWS4SignedPayloadGenerator generator = new AWS4SignedPayloadGenerator(); byte[] signedPayload = generator.signedPayload(params); assertNotNull(signedPayload); SignedPayloadValidatorUtils.validatePayload(signedPayload, params); } }
5,575
0
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam/IAMOAuthBearerLoginCallbackHandler.java
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package software.amazon.msk.auth.iam; import java.io.IOException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.text.ParseException; import java.util.Base64; import java.util.List; import java.util.Map; import java.util.Optional; import javax.security.auth.callback.Callback; import javax.security.auth.callback.UnsupportedCallbackException; import javax.security.auth.login.AppConfigurationEntry; import org.apache.kafka.common.security.auth.AuthenticateCallbackHandler; import org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule; import org.apache.kafka.common.security.oauthbearer.OAuthBearerToken; import org.apache.kafka.common.security.oauthbearer.OAuthBearerTokenCallback; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.amazonaws.AmazonWebServiceRequest; import com.amazonaws.DefaultRequest; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import lombok.NonNull; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.http.SdkHttpFullRequest; import software.amazon.awssdk.http.SdkHttpMethod; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.providers.AwsRegionProvider; import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain; import software.amazon.msk.auth.iam.internals.AWS4SignedPayloadGenerator; import software.amazon.msk.auth.iam.internals.AuthenticationRequestParams; import software.amazon.msk.auth.iam.internals.MSKCredentialProvider; import software.amazon.msk.auth.iam.internals.UserAgentUtils; /** * This login callback handler is used to extract base64 encoded signed url as an auth token. * The credentials are based on JaasConfig options passed to {@link OAuthBearerLoginModule}. * If config options are provided the {@link MSKCredentialProvider} is used. * If no config options are provided it uses the DefaultAWSCredentialsProviderChain. */ public class IAMOAuthBearerLoginCallbackHandler implements AuthenticateCallbackHandler { private static final Logger LOGGER = LoggerFactory.getLogger(IAMOAuthBearerLoginCallbackHandler.class); private static final String PROTOCOL = "https"; private static final String USER_AGENT_KEY = "User-Agent"; private final AWS4SignedPayloadGenerator aws4Signer = new AWS4SignedPayloadGenerator(); private AWSCredentialsProvider credentialsProvider; private AwsRegionProvider awsRegionProvider; private boolean configured = false; /** * Return true if this instance has been configured, otherwise false. */ public boolean configured() { return configured; } @Override public void configure(Map<String, ?> configs, @NonNull String saslMechanism, @NonNull List<AppConfigurationEntry> jaasConfigEntries) { if (!OAuthBearerLoginModule.OAUTHBEARER_MECHANISM.equals(saslMechanism)) { throw new IllegalArgumentException(String.format("Unexpected SASL mechanism: %s", saslMechanism)); } final Optional<AppConfigurationEntry> configEntry = jaasConfigEntries.stream() .filter(j -> OAuthBearerLoginModule.class.getCanonicalName() .equals(j.getLoginModuleName())) .findFirst(); credentialsProvider = configEntry.map(c -> (AWSCredentialsProvider) new MSKCredentialProvider(c.getOptions())) .orElse(DefaultAWSCredentialsProviderChain.getInstance()); awsRegionProvider = new DefaultAwsRegionProviderChain(); configured = true; } @Override public void close() { try { if (credentialsProvider instanceof AutoCloseable) { ((AutoCloseable) credentialsProvider).close(); } } catch (Exception e) { LOGGER.warn("Error closing provider", e); } } @Override public void handle(@NonNull Callback[] callbacks) throws IOException, UnsupportedCallbackException { if (!configured()) { throw new IllegalStateException("Callback handler not configured"); } for (Callback callback : callbacks) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Type information for callback: " + debugClassString(callback.getClass()) + " from " + debugClassString(this.getClass())); } if (callback instanceof OAuthBearerTokenCallback) { try { handleCallback((OAuthBearerTokenCallback) callback); } catch (ParseException | URISyntaxException e) { throw new MalformedURLException(e.getMessage()); } } else { String message = "Unsupported callback type: " + debugClassString(callback.getClass()) + " from " + debugClassString(this.getClass()); throw new UnsupportedCallbackException(callback, message); } } } private void handleCallback(OAuthBearerTokenCallback callback) throws IOException, URISyntaxException, ParseException { if (callback.token() != null) { throw new IllegalArgumentException("Callback had a token already"); } AWSCredentials awsCredentials = credentialsProvider.getCredentials(); // Generate token value i.e. Base64 encoded pre-signed URL string String tokenValue = generateTokenValue(awsCredentials, getCurrentRegion()); // Set OAuth token callback.token(getOAuthBearerToken(tokenValue)); } /** * Generates base64 encoded signed url based on IAM credentials provided * * @param awsCredentials aws credentials object * @param region aws region * @return a base64 encoded token string */ private String generateTokenValue(@NonNull final AWSCredentials awsCredentials, @NonNull final Region region) { final String userAgentValue = UserAgentUtils.getUserAgentValue(); final AuthenticationRequestParams authenticationRequestParams = AuthenticationRequestParams .create(getHostName(region), awsCredentials, userAgentValue); final DefaultRequest request = aws4Signer.presignRequest(authenticationRequestParams); request.addParameter(USER_AGENT_KEY, userAgentValue); final SdkHttpFullRequest fullRequest = convertToSdkHttpFullRequest(request); String signedUrl = fullRequest.getUri() .toString(); return Base64.getUrlEncoder() .withoutPadding() .encodeToString(signedUrl.getBytes(StandardCharsets.UTF_8)); } /** * Builds hostname string * * @param region aws region * @return hostname */ private String getHostName(final Region region) { return String.format("kafka.%s.amazonaws.com", region.toString()); } /** * Gets current aws region from metadata * * @return aws region object * @throws IOException */ private Region getCurrentRegion() throws IOException { try { return awsRegionProvider.getRegion(); } catch (SdkClientException exception) { throw new IOException("AWS region could not be resolved."); } } /** * Constructs OAuthBearerToken object as required by OAuthModule * * @param token base64 encoded token * @return */ private OAuthBearerToken getOAuthBearerToken(final String token) throws URISyntaxException, ParseException { return new IAMOAuthBearerToken(token); } static String debugClassString(Class<?> clazz) { return "class: " + clazz.getName() + " classloader: " + clazz.getClassLoader().toString(); } /** * Converts the DefaultRequest object to a http request object from aws sdk. * * @param defaultRequest pre-signed request object * @return */ private SdkHttpFullRequest convertToSdkHttpFullRequest(DefaultRequest<? extends AmazonWebServiceRequest> defaultRequest) { final SdkHttpMethod httpMethod = SdkHttpMethod.valueOf(defaultRequest.getHttpMethod().name()); String endpoint = defaultRequest.getEndpoint().toString(); final SdkHttpFullRequest.Builder requestBuilder = SdkHttpFullRequest.builder() .method(httpMethod) .protocol(PROTOCOL) // Replace Protocol with 'https://' since 'kafka://' fails for not being recognized as a valid scheme by builder .encodedPath(defaultRequest.getResourcePath()) .host(endpoint.substring(endpoint.indexOf("://") + 3)); // Extract hostname e.g. 'kafka://kafka.us-west-1.amazonaws.com' => 'kafka.us-west-1.amazonaws.com' defaultRequest.getHeaders() .forEach((key, value) -> requestBuilder.appendHeader(key, value)); defaultRequest.getParameters() .forEach((key, value) -> requestBuilder.appendRawQueryParameter(key, value.get(0))); return requestBuilder.build(); } }
5,576
0
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam/IAMLoginModule.java
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package software.amazon.msk.auth.iam; import software.amazon.msk.auth.iam.internals.ClassLoaderAwareIAMSaslClientProvider; import software.amazon.msk.auth.iam.internals.IAMSaslClientProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.security.auth.Subject; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.login.LoginException; import javax.security.auth.spi.LoginModule; import java.util.Map; /** * This Login Module is used to register the {@link IAMSaslClientProvider}. * The module is a no-op for other purposes. */ public class IAMLoginModule implements LoginModule { public static final String MECHANISM = "AWS_MSK_IAM"; private static final Logger log = LoggerFactory.getLogger(IAMLoginModule.class); static { ClassLoaderAwareIAMSaslClientProvider.initialize(); IAMSaslClientProvider.initialize(); } @Override public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options) { if (log.isDebugEnabled()) { log.debug("IAMLoginModule initialized"); } } @Override public boolean login() throws LoginException { return true; } @Override public boolean commit() throws LoginException { return true; } @Override public boolean abort() throws LoginException { return false; } @Override public boolean logout() throws LoginException { return true; } }
5,577
0
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam/IAMClientCallbackHandler.java
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package software.amazon.msk.auth.iam; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import software.amazon.msk.auth.iam.internals.AWSCredentialsCallback; import software.amazon.msk.auth.iam.internals.MSKCredentialProvider; import lombok.NonNull; import org.apache.kafka.common.security.auth.AuthenticateCallbackHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.security.auth.callback.Callback; import javax.security.auth.callback.UnsupportedCallbackException; import javax.security.auth.login.AppConfigurationEntry; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Optional; /** * This client callback handler is used to extract AWSCredentials. * The credentials are based on JaasConfig options passed to {@link IAMLoginModule}. * If config options are provided the {@link MSKCredentialProvider} is used. * If no config options are provided it uses the DefaultAWSCredentialsProviderChain. */ public class IAMClientCallbackHandler implements AuthenticateCallbackHandler { private static final Logger log = LoggerFactory.getLogger(IAMClientCallbackHandler.class); private AWSCredentialsProvider provider; @Override public void configure(Map<String, ?> configs, @NonNull String saslMechanism, @NonNull List<AppConfigurationEntry> jaasConfigEntries) { if (!IAMLoginModule.MECHANISM.equals(saslMechanism)) { throw new IllegalArgumentException("Unexpected SASL mechanism: " + saslMechanism); } final Optional<AppConfigurationEntry> configEntry = jaasConfigEntries.stream() .filter(j -> IAMLoginModule.class.getCanonicalName().equals(j.getLoginModuleName())).findFirst(); provider = configEntry.map(c -> (AWSCredentialsProvider) new MSKCredentialProvider(c.getOptions())) .orElse(DefaultAWSCredentialsProviderChain.getInstance()); } @Override public void close() { try { if (provider instanceof AutoCloseable) { ((AutoCloseable) provider).close(); } } catch (Exception e) { log.warn("Error closing provider", e); } } @Override public void handle(@NonNull Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (Callback callback : callbacks) { if (log.isDebugEnabled()) { log.debug("Type information for callback: " + debugClassString(callback.getClass()) + " from " + debugClassString(this.getClass())); } if (callback instanceof AWSCredentialsCallback) { handleCallback((AWSCredentialsCallback) callback); } else { String message = "Unsupported callback type: " + debugClassString(callback.getClass()) + " from " + debugClassString(this.getClass()); //We are breaking good practice and logging as well as throwing since this is where client side //integrations might have trouble. Depending on the client framework either logging or throwing might //surface the error more easily to the user. log.error(message); throw new UnsupportedCallbackException(callback, message); } } } protected static String debugClassString(Class<?> clazz) { return "class: " + clazz.getName() + " classloader: " + clazz.getClassLoader().toString(); } protected void handleCallback(AWSCredentialsCallback callback) throws IOException { if (log.isDebugEnabled()) { log.debug("Selecting provider {} to load credentials", provider.getClass().getName()); } try { provider.refresh(); callback.setAwsCredentials(provider.getCredentials()); } catch (Exception e) { callback.setLoadingException(e); } } }
5,578
0
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam/IAMOAuthBearerToken.java
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package software.amazon.msk.auth.iam; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Base64; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.kafka.common.security.oauthbearer.OAuthBearerToken; import com.amazonaws.auth.internal.SignerConstants; import software.amazon.awssdk.utils.StringUtils; /** * Implements the contract provided by OAuthBearerToken interface */ public class IAMOAuthBearerToken implements OAuthBearerToken { private static final String SIGNING_NAME = "kafka-cluster"; private final String value; private final long lifetimeMs; private final long startTimeMs; // Used for testing IAMOAuthBearerToken(String token, long lifeTimeSeconds) { this.value = token; this.startTimeMs = System.currentTimeMillis(); this.lifetimeMs = this.startTimeMs + (lifeTimeSeconds * 1000); } public IAMOAuthBearerToken(String token) throws URISyntaxException { if(StringUtils.isEmpty(token)) { throw new IllegalArgumentException("Token can not be empty"); } this.value = token; byte[] tokenBytes = token.getBytes(StandardCharsets.UTF_8); byte[] decodedBytes = Base64.getUrlDecoder().decode(tokenBytes); final String decodedPresignedUrl = new String(decodedBytes, StandardCharsets.UTF_8); final URI uri = new URI(decodedPresignedUrl); List<NameValuePair> params = URLEncodedUtils.parse(uri, StandardCharsets.UTF_8); Map<String, String> paramMap = params.stream() .collect(Collectors.toMap(NameValuePair::getName, NameValuePair::getValue)); int lifeTimeSeconds = Integer.parseInt(paramMap.get(SignerConstants.X_AMZ_EXPIRES)); final DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'"); final LocalDateTime signedDate = LocalDateTime.parse(paramMap.get(SignerConstants.X_AMZ_DATE), dateFormat); long signedDateEpochMillis = signedDate.toInstant(ZoneOffset.UTC) .toEpochMilli(); this.startTimeMs = signedDateEpochMillis; this.lifetimeMs = this.startTimeMs + (lifeTimeSeconds * 1000L); } @Override public String value() { return this.value; } @Override public Set<String> scope() { return Collections.emptySet(); } @Override public long lifetimeMs() { return this.lifetimeMs; } @Override public String principalName() { return SIGNING_NAME; } @Override public Long startTimeMs() { return this.startTimeMs; } }
5,579
0
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam/internals/MSKCredentialProvider.java
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package software.amazon.msk.auth.iam.internals; import com.amazonaws.SdkBaseException; import com.amazonaws.SdkClientException; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.AWSCredentialsProviderChain; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.auth.BasicSessionCredentials; import com.amazonaws.auth.EC2ContainerCredentialsProviderWrapper; import com.amazonaws.auth.EnvironmentVariableCredentialsProvider; import com.amazonaws.auth.STSAssumeRoleSessionCredentialsProvider; import com.amazonaws.auth.SystemPropertiesCredentialsProvider; import com.amazonaws.auth.WebIdentityTokenCredentialsProvider; import com.amazonaws.retry.PredefinedBackoffStrategies; import com.amazonaws.retry.v2.AndRetryCondition; import com.amazonaws.retry.v2.MaxNumberOfRetriesCondition; import com.amazonaws.retry.v2.RetryOnExceptionsCondition; import com.amazonaws.retry.v2.RetryPolicy; import com.amazonaws.retry.v2.RetryPolicyContext; import com.amazonaws.retry.v2.SimpleRetryPolicy; import com.amazonaws.services.securitytoken.AWSSecurityTokenService; import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClientBuilder; import com.amazonaws.services.securitytoken.model.GetCallerIdentityRequest; import com.amazonaws.services.securitytoken.model.GetCallerIdentityResult; import lombok.AccessLevel; import lombok.Getter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; /** * This AWS Credential Provider is used to load up AWS Credentials based on options provided on the Jaas config line. * As as an example * sasl.jaas.config = IAMLoginModule required awsProfileName={profile name}; * The currently supported options are: * 1. A particular AWS Credential profile: awsProfileName={profile name} * 2. A particular AWS IAM Role, with optional access key id, secret key and session token OR optional external id, * and optionally AWS IAM role session name and AWS region for the STS endpoint: * awsRoleArn={IAM Role ARN}, awsRoleAccessKeyId={access key id}, awsRoleSecretAccessKey={secret access key}, * awsRoleSessionToken={session token}, awsRoleSessionName={session name}, awsStsRegion={region name} * 3. Optional arguments to configure retries when we fail to load credentials: * awsMaxRetries={Maximum number of retries}, awsMaxBackOffTimeMs={Maximum back off time between retries in ms} * 4. Optional argument to help debug credentials used to establish connections: * awsDebugCreds={true|false} * 5. If no options is provided, the DefaultAWSCredentialsProviderChain is used. * The DefaultAWSCredentialProviderChain can be pointed to credentials in many different ways: * <a href="https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html">Working with AWS Credentials</a> */ public class MSKCredentialProvider implements AWSCredentialsProvider, AutoCloseable { private static final Logger log = LoggerFactory.getLogger(MSKCredentialProvider.class); private static final String AWS_PROFILE_NAME_KEY = "awsProfileName"; private static final String AWS_ROLE_ARN_KEY = "awsRoleArn"; private static final String AWS_ROLE_EXTERNAL_ID = "awsRoleExternalId"; private static final String AWS_ROLE_ACCESS_KEY_ID = "awsRoleAccessKeyId"; private static final String AWS_ROLE_SECRET_ACCESS_KEY = "awsRoleSecretAccessKey"; private static final String AWS_ROLE_SESSION_KEY = "awsRoleSessionName"; private static final String AWS_ROLE_SESSION_TOKEN = "awsRoleSessionToken"; private static final String AWS_STS_REGION = "awsStsRegion"; private static final String AWS_DEBUG_CREDS_KEY = "awsDebugCreds"; private static final String AWS_MAX_RETRIES = "awsMaxRetries"; private static final String AWS_MAX_BACK_OFF_TIME_MS = "awsMaxBackOffTimeMs"; private static final int DEFAULT_MAX_RETRIES = 3; private static final int DEFAULT_MAX_BACK_OFF_TIME_MS = 5000; private static final int BASE_DELAY = 500; private final List<AutoCloseable> closeableProviders; private final AWSCredentialsProvider compositeDelegate; @Getter(AccessLevel.PACKAGE) private final Boolean shouldDebugCreds; private final String stsRegion; private final RetryPolicy retryPolicy; public MSKCredentialProvider(Map<String, ?> options) { this(new ProviderBuilder(options)); } MSKCredentialProvider(ProviderBuilder builder) { this(builder.getProviders(), builder.shouldDebugCreds(), builder.getStsRegion(), builder.getMaxRetries(), builder.getMaxBackOffTimeMs()); } MSKCredentialProvider(List<AWSCredentialsProvider> providers, Boolean shouldDebugCreds, String stsRegion, int maxRetries, int maxBackOffTimeMs) { List<AWSCredentialsProvider> delegateList = new ArrayList<>(providers); delegateList.add(getDefaultProvider()); compositeDelegate = new AWSCredentialsProviderChain(delegateList); closeableProviders = providers.stream().filter(p -> p instanceof AutoCloseable).map(p -> (AutoCloseable) p) .collect(Collectors.toList()); this.shouldDebugCreds = shouldDebugCreds; this.stsRegion = stsRegion; if (maxRetries > 0) { this.retryPolicy = new SimpleRetryPolicy( new AndRetryCondition(new RetryOnExceptionsCondition(Collections.singletonList( SdkClientException.class)), new MaxNumberOfRetriesCondition(maxRetries)), new PredefinedBackoffStrategies.FullJitterBackoffStrategy(BASE_DELAY, maxBackOffTimeMs)); } else { this.retryPolicy = new SimpleRetryPolicy((c) -> false, new PredefinedBackoffStrategies.FullJitterBackoffStrategy(BASE_DELAY, maxBackOffTimeMs)); } } //We want to override the ProfileCredentialsProvider with the EnhancedProfileCredentialsProvider protected AWSCredentialsProviderChain getDefaultProvider() { return new AWSCredentialsProviderChain(new EnvironmentVariableCredentialsProvider(), new SystemPropertiesCredentialsProvider(), WebIdentityTokenCredentialsProvider.create(), new EnhancedProfileCredentialsProvider(), new EC2ContainerCredentialsProviderWrapper()); } @Override public AWSCredentials getCredentials() { AWSCredentials credentials = loadCredentialsWithRetry(); if (credentials != null && shouldDebugCreds && log.isDebugEnabled()) { logCallerIdentity(credentials); } return credentials; } private AWSCredentials loadCredentialsWithRetry() { RetryPolicyContext retryPolicyContext = RetryPolicyContext.builder().build(); boolean shouldTry = true; try { while (shouldTry) { try { AWSCredentials credentials = compositeDelegate.getCredentials(); if (credentials == null) { throw new SdkClientException("Composite delegate returned empty credentials."); } return credentials; } catch (SdkBaseException se) { log.warn("Exception loading credentials. Retry Attempts: {}", retryPolicyContext.retriesAttempted(), se); retryPolicyContext = createRetryPolicyContext(se, retryPolicyContext.retriesAttempted()); shouldTry = retryPolicy.shouldRetry(retryPolicyContext); if (shouldTry) { Thread.sleep(retryPolicy.computeDelayBeforeNextRetry(retryPolicyContext)); retryPolicyContext = createRetryPolicyContext(retryPolicyContext.exception(), retryPolicyContext.retriesAttempted() + 1); } else { throw se; } } } throw new SdkClientException( "loadCredentialsWithRetry in unexpected location " + retryPolicyContext.totalRequests(), retryPolicyContext.exception()); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new RuntimeException("Interrupted while waiting for credentials.", ie); } } private RetryPolicyContext createRetryPolicyContext(SdkBaseException sdkException, int retriesAttempted) { return RetryPolicyContext.builder().exception(sdkException) .retriesAttempted(retriesAttempted).build(); } private void logCallerIdentity(AWSCredentials credentials) { try { AWSSecurityTokenService stsClient = getStsClientForDebuggingCreds(credentials); GetCallerIdentityResult response = stsClient.getCallerIdentity(new GetCallerIdentityRequest()); log.debug("The identity of the credentials is {}", response.toString()); } catch (Exception e) { //If we run into an exception logging the caller identity, we should log the exception but //continue running. log.warn("Error identifying caller identity. If this is not transient, does this application have" + "access to AWS STS?", e); } } AWSSecurityTokenService getStsClientForDebuggingCreds(AWSCredentials credentials) { return AWSSecurityTokenServiceClientBuilder.standard() .withRegion(stsRegion) .withCredentials(new AWSCredentialsProvider() { @Override public AWSCredentials getCredentials() { return credentials; } @Override public void refresh() { } }) .build(); } @Override public void refresh() { compositeDelegate.refresh(); } @Override public void close() { closeableProviders.stream().forEach(p -> { try { p.close(); } catch (Exception e) { log.warn("Error closing credential provider", e); } }); } public static class ProviderBuilder { private final Map<String, ?> optionsMap; public ProviderBuilder(Map<String, ?> optionsMap) { this.optionsMap = optionsMap; if (log.isDebugEnabled()) { log.debug("Number of options to configure credential provider {}", optionsMap.size()); } } public List<AWSCredentialsProvider> getProviders() { List<AWSCredentialsProvider> providers = new ArrayList<>(); getProfileProvider().ifPresent(providers::add); getStsRoleProvider().ifPresent(providers::add); return providers; } public Boolean shouldDebugCreds() { return Optional.ofNullable(optionsMap.get(AWS_DEBUG_CREDS_KEY)).map(d -> d.equals("true")).orElse(false); } public String getStsRegion() { return Optional.ofNullable((String) optionsMap.get(AWS_STS_REGION)) .orElse("aws-global"); } public int getMaxRetries() { return Optional.ofNullable(optionsMap.get(AWS_MAX_RETRIES)).map(p -> (String) p).map(Integer::parseInt) .orElse(DEFAULT_MAX_RETRIES); } public int getMaxBackOffTimeMs() { return Optional.ofNullable(optionsMap.get(AWS_MAX_BACK_OFF_TIME_MS)).map(p -> (String) p) .map(Integer::parseInt) .orElse(DEFAULT_MAX_BACK_OFF_TIME_MS); } private Optional<EnhancedProfileCredentialsProvider> getProfileProvider() { return Optional.ofNullable(optionsMap.get(AWS_PROFILE_NAME_KEY)).map(p -> { if (log.isDebugEnabled()) { log.debug("Profile name {}", p); } return createEnhancedProfileCredentialsProvider((String) p); }); } EnhancedProfileCredentialsProvider createEnhancedProfileCredentialsProvider(String p) { return new EnhancedProfileCredentialsProvider(p); } private Optional<STSAssumeRoleSessionCredentialsProvider> getStsRoleProvider() { return Optional.ofNullable(optionsMap.get(AWS_ROLE_ARN_KEY)).map(p -> { if (log.isDebugEnabled()) { log.debug("Role ARN {}", p); } String sessionName = Optional.ofNullable((String) optionsMap.get(AWS_ROLE_SESSION_KEY)) .orElse("aws-msk-iam-auth"); String stsRegion = getStsRegion(); String accessKey = (String) optionsMap.getOrDefault(AWS_ROLE_ACCESS_KEY_ID, null); String secretKey = (String) optionsMap.getOrDefault(AWS_ROLE_SECRET_ACCESS_KEY, null); String sessionToken = (String) optionsMap.getOrDefault(AWS_ROLE_SESSION_TOKEN, null); String externalId = (String) optionsMap.getOrDefault(AWS_ROLE_EXTERNAL_ID, null); if (accessKey != null && secretKey != null) { AWSCredentialsProvider credentials = new AWSStaticCredentialsProvider( sessionToken != null ? new BasicSessionCredentials(accessKey, secretKey, sessionToken) : new BasicAWSCredentials(accessKey, secretKey)); return createSTSRoleCredentialProvider((String) p, sessionName, stsRegion, credentials); } else if (externalId != null) { return createSTSRoleCredentialProvider((String) p, externalId, sessionName, stsRegion); } return createSTSRoleCredentialProvider((String) p, sessionName, stsRegion); }); } STSAssumeRoleSessionCredentialsProvider createSTSRoleCredentialProvider(String roleArn, String sessionName, String stsRegion) { AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder.standard() .withRegion(stsRegion) .build(); return new STSAssumeRoleSessionCredentialsProvider.Builder(roleArn, sessionName) .withStsClient(stsClient) .build(); } STSAssumeRoleSessionCredentialsProvider createSTSRoleCredentialProvider(String roleArn, String sessionName, String stsRegion, AWSCredentialsProvider credentials) { AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder.standard() .withRegion(stsRegion) .withCredentials(credentials) .build(); return new STSAssumeRoleSessionCredentialsProvider.Builder(roleArn, sessionName) .withStsClient(stsClient) .build(); } STSAssumeRoleSessionCredentialsProvider createSTSRoleCredentialProvider(String roleArn, String externalId, String sessionName, String stsRegion) { AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder.standard() .withRegion(stsRegion) .build(); return new STSAssumeRoleSessionCredentialsProvider.Builder(roleArn, sessionName) .withStsClient(stsClient) .withExternalId(externalId) .build(); } } }
5,580
0
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam/internals/ClassLoaderAwareIAMSaslClientProvider.java
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package software.amazon.msk.auth.iam.internals; import software.amazon.msk.auth.iam.IAMLoginModule; import software.amazon.msk.auth.iam.internals.IAMSaslClient.ClassLoaderAwareIAMSaslClientFactory; import java.security.Provider; import java.security.Security; public class ClassLoaderAwareIAMSaslClientProvider extends Provider { /** * Constructs an IAM Sasl Client provider that installs a {@link ClassLoaderAwareIAMSaslClientFactory}. */ protected ClassLoaderAwareIAMSaslClientProvider() { super("ClassLoader Aware SASL/IAM Client Provider", 1.0, "SASL/IAM Client Provider for Kafka"); put("SaslClientFactory." + IAMLoginModule.MECHANISM, ClassLoaderAwareIAMSaslClientFactory.class.getName()); } public static void initialize() { Security.addProvider(new ClassLoaderAwareIAMSaslClientProvider()); } }
5,581
0
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam/internals/IAMSaslClientProvider.java
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package software.amazon.msk.auth.iam.internals; import software.amazon.msk.auth.iam.internals.IAMSaslClient.IAMSaslClientFactory; import java.security.Provider; import java.security.Security; import static software.amazon.msk.auth.iam.internals.IAMSaslClient.getMechanismNameForClassLoader; public class IAMSaslClientProvider extends Provider { /** * Constructs a IAM Sasl Client provider with a fixed name, version number, * and information. */ protected IAMSaslClientProvider() { super("SASL/IAM Client Provider (" + IAMSaslClientProvider.class.getClassLoader().hashCode(), 1.0, ") SASL/IAM Client Provider for Kafka"); put("SaslClientFactory." + getMechanismNameForClassLoader(getClass().getClassLoader()), IAMSaslClientFactory.class.getName()); } public static void initialize() { Security.addProvider(new IAMSaslClientProvider()); } }
5,582
0
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam/internals/IAMSaslClient.java
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package software.amazon.msk.auth.iam.internals; import software.amazon.msk.auth.iam.IAMClientCallbackHandler; import software.amazon.msk.auth.iam.IAMLoginModule; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.NonNull; import org.apache.kafka.common.errors.IllegalSaslStateException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.UnsupportedCallbackException; import javax.security.sasl.Sasl; import javax.security.sasl.SaslClient; import javax.security.sasl.SaslClientFactory; import javax.security.sasl.SaslException; import java.io.IOException; import java.util.Arrays; import java.util.Map; /** * The IAMSaslClient is used to provide SASL integration with AWS IAM. * It has an initial response, so it starts out in the state SEND_CLIENT_FIRST_MESSAGE. * The initial response sent to the server contains an authentication payload. * The authentication payload consists of a json object that includes a signature signed by the client's credentials. * The exact details of the authentication payload can be seen in {@link AWS4SignedPayloadGenerator}. * The credentials used to sign the payload are fetched by invoking the * {@link IAMClientCallbackHandler}. * After sending the authentication payload, the client transitions to state RECEIVE_SENDER_RESPONSE. * Once it receives a successful response from the server, the client transitions to the state completed. * A failure at any intermediate step transitions the client to a FAILED state. */ public class IAMSaslClient implements SaslClient { private static final Logger log = LoggerFactory.getLogger(IAMSaslClient.class); enum State { SEND_CLIENT_FIRST_MESSAGE, RECEIVE_SERVER_RESPONSE, COMPLETE, FAILED } private final String mechanism; private final CallbackHandler cbh; private final String serverName; private final SignedPayloadGenerator payloadGenerator; private State state; private String responseRequestId; public IAMSaslClient(@NonNull String mechanism, @NonNull CallbackHandler cbh, @NonNull String serverName, @NonNull SignedPayloadGenerator payloadGenerator) { this.mechanism = mechanism; this.cbh = cbh; this.serverName = serverName; this.payloadGenerator = payloadGenerator; setState(State.SEND_CLIENT_FIRST_MESSAGE); } @Override public String getMechanismName() { return mechanism; } @Override public boolean hasInitialResponse() { return true; } @Override public byte[] evaluateChallenge(byte[] challenge) throws SaslException { if (log.isDebugEnabled()) { log.debug("State {} at start of evaluating challenge", state); } try { switch (state) { case SEND_CLIENT_FIRST_MESSAGE: //For the initial response, the challenge should be empty. if (!isChallengeEmpty(challenge)) { throw new SaslException("Expects an empty challenge in state " + state); } return generateClientMessage(); case RECEIVE_SERVER_RESPONSE: //we expect the successful server response to contain a non-empty challenge. if (isChallengeEmpty(challenge)) { throw new SaslException("Expects a non-empty authentication response in state " + state); } handleServerResponse(challenge); //At this point, the authentication is complete. setState(State.COMPLETE); return null; default: throw new IllegalSaslStateException("Challenge received in unexpected state " + state); } } catch (SaslException se) { setState(State.FAILED); throw se; } catch (IOException | IllegalArgumentException | UnsupportedCallbackException e) { setState(State.FAILED); throw new SaslException("Exception while evaluating challenge", e); } finally { if (log.isDebugEnabled()) { log.debug("State {} at end of evaluating challenge", state); } } } private void handleServerResponse(byte[] challenge) throws IOException { //If we got a non-empty server challenge, then the authentication succeeded on the server. //Deserialize and log the server response as necessary. ObjectMapper mapper = new ObjectMapper(); AuthenticationResponse response = mapper.readValue(challenge, AuthenticationResponse.class); if (response == null) { throw new SaslException("Invalid response from server "); } responseRequestId = response.getRequestId(); if (log.isDebugEnabled()) { log.debug("Response from server: " + response.toString()); } } private byte[] generateClientMessage() throws IOException, UnsupportedCallbackException { //Invoke the callback handler to fetch the credentials. final AWSCredentialsCallback callback = new AWSCredentialsCallback(); cbh.handle(new Callback[] { callback }); if (callback.isSuccessful()) { //Generate the signed payload final byte[] response = payloadGenerator.signedPayload( AuthenticationRequestParams .create(serverName, callback.getAwsCredentials(), UserAgentUtils.getUserAgentValue())); //transition to the state waiting to receive server response. setState(State.RECEIVE_SERVER_RESPONSE); return response; } else { throw new SaslException("Failed to find AWS IAM Credentials", callback.getLoadingException()); } } @Override public boolean isComplete() { return State.COMPLETE.equals(state); } @Override public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException { if (!isComplete()) { throw new IllegalStateException("Authentication exchange has not completed"); } return Arrays.copyOfRange(incoming, offset, offset + len); } @Override public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException { if (!isComplete()) { throw new IllegalStateException("Authentication exchange has not completed"); } return Arrays.copyOfRange(outgoing, offset, offset + len); } @Override public Object getNegotiatedProperty(String propName) { if (!isComplete()) { throw new IllegalStateException("Authentication exchange has not completed"); } return null; } @Override public void dispose() throws SaslException { } public String getResponseRequestId() { if (!isComplete()) { throw new IllegalStateException("Authentication exchange has not completed"); } return responseRequestId; } private void setState(State state) { if (log.isDebugEnabled()) { log.debug("Setting SASL/{} client state to {}", mechanism, state); } this.state = state; } private static boolean isChallengeEmpty(byte[] challenge) { if (challenge != null && challenge.length > 0) { return false; } return true; } public static class ClassLoaderAwareIAMSaslClientFactory implements SaslClientFactory { @Override public SaslClient createSaslClient(String[] mechanisms, String authorizationId, String protocol, String serverName, Map<String, ?> props, CallbackHandler cbh) throws SaslException { String mechanismName = getMechanismNameForClassLoader(cbh.getClass().getClassLoader()); // Create a client by delegating to the SaslClientFactory for the classloader of the CallbackHandler return Sasl.createSaslClient( new String[] { mechanismName }, authorizationId, protocol, serverName, props, cbh); } @Override public String[] getMechanismNames(Map<String, ?> props) { return new String[] { IAMLoginModule.MECHANISM }; } } public static class IAMSaslClientFactory implements SaslClientFactory { @Override public SaslClient createSaslClient(String[] mechanisms, String authorizationId, String protocol, String serverName, Map<String, ?> props, CallbackHandler cbh) throws SaslException { String mechanismName = getMechanismNameForClassLoader(getClass().getClassLoader()); for (String mechanism : mechanisms) { if (mechanismName.equals(mechanism)) { return new IAMSaslClient(mechanism, cbh, serverName, new AWS4SignedPayloadGenerator()); } } throw new SaslException( "Requested mechanisms " + Arrays.asList(mechanisms) + " not supported. " + "The supported mechanism is " + mechanismName); } @Override public String[] getMechanismNames(Map<String, ?> props) { return new String[] { getMechanismNameForClassLoader(getClass().getClassLoader()) }; } } public static String getMechanismNameForClassLoader(ClassLoader classLoader) { return IAMLoginModule.MECHANISM + "." + classLoader.hashCode(); } }
5,583
0
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam/internals/EnhancedProfileCredentialsProvider.java
package software.amazon.msk.auth.iam.internals; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.auth.BasicSessionCredentials; import software.amazon.awssdk.auth.credentials.AwsSessionCredentials; import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.profiles.ProfileFile; /** * This credential provider delegates to the v2 ProfileCredentialProvider so that users * are able to use Single Sign On credentials and also get more standard credential loading * behavior. * See https://github.com/aws/aws-sdk-java/issues/803#issuecomment-593530484 */ public class EnhancedProfileCredentialsProvider implements AWSCredentialsProvider { private final ProfileCredentialsProvider delegate; public EnhancedProfileCredentialsProvider() { delegate = ProfileCredentialsProvider.create(); } public EnhancedProfileCredentialsProvider(String profileName) { delegate = ProfileCredentialsProvider.create(profileName); } public EnhancedProfileCredentialsProvider(ProfileFile profileFile, String profileName) { delegate = ProfileCredentialsProvider.builder().profileFile(profileFile).profileName(profileName).build(); } @Override public AWSCredentials getCredentials() { software.amazon.awssdk.auth.credentials.AwsCredentials credentialsV2 = delegate.resolveCredentials(); if (credentialsV2 instanceof AwsSessionCredentials) { AwsSessionCredentials sessionCredentialsV2 = (AwsSessionCredentials) credentialsV2; return new BasicSessionCredentials(sessionCredentialsV2.accessKeyId(), sessionCredentialsV2.secretAccessKey(), sessionCredentialsV2.sessionToken()); } return new BasicAWSCredentials(credentialsV2.accessKeyId(), credentialsV2.secretAccessKey()); } @Override public void refresh() { } }
5,584
0
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam/internals/AuthenticationResponse.java
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package software.amazon.msk.auth.iam.internals; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Getter; import lombok.NonNull; import lombok.ToString; /** * This class is used to model the authentication response sent by the broker. */ @Getter(onMethod = @__(@JsonIgnore)) @ToString public class AuthenticationResponse { private static final String VERSION_1 = "2020_10_22"; private static final String VERSION_FIELD_NAME = "version"; private static final String REQUEST_ID_FIELD_NAME = "request-id"; @NonNull @JsonProperty(VERSION_FIELD_NAME) private final String version; @JsonProperty(REQUEST_ID_FIELD_NAME) @NonNull private final String requestId; @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) public AuthenticationResponse(@JsonProperty(VERSION_FIELD_NAME) String version, @JsonProperty(REQUEST_ID_FIELD_NAME) String requestId) { if (!VERSION_1.equals(version)) { throw new IllegalArgumentException("Invalid version " + version); } this.version = version; this.requestId = requestId; } }
5,585
0
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam/internals/AWS4SignedPayloadGenerator.java
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package software.amazon.msk.auth.iam.internals; import com.amazonaws.DefaultRequest; import com.amazonaws.auth.AWS4Signer; import com.amazonaws.auth.internal.SignerConstants; import com.amazonaws.http.HttpMethodName; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.NonNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.sql.Date; import java.time.Instant; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringJoiner; import java.util.concurrent.TimeUnit; /** * This class is used to generate the AWS Sigv4 signed authentication payload sent by the IAMSaslClient to the broker. * It configures a AWSSigner based on the authentication request parameters. It generates a request with the endpoint * set to the kafka broker (kafka:// as prefix), action set to kafka-cluster:Connect and the Http method as GET. * It then pre-signs the request using the credentials in the authentication request parameters and a expiration period * of 15 minutes. Afterwards, the signed request is converted into a key value map with headers and query parameters * acting as keys. Then the key value map is serialized as a JSON object and returned as bytes. */ public class AWS4SignedPayloadGenerator implements SignedPayloadGenerator { private static final Logger log = LoggerFactory.getLogger(AWS4SignedPayloadGenerator.class); private static final String ACTION_KEY = "Action"; private static final String ACTION_VALUE = "kafka-cluster:Connect"; private static final String VERSION_KEY = "version"; private static final String USER_AGENT_KEY = "user-agent"; private static final int EXPIRY_DURATION_MINUTES = 15; @Override public byte[] signedPayload(@NonNull AuthenticationRequestParams params) throws PayloadGenerationException { final DefaultRequest request = presignRequest(params); try { return toPayloadBytes(request, params); } catch (IOException e) { throw new PayloadGenerationException("Failure to create authentication payload ", e); } } /** * Presigns the request with AWS sigv4 * * @param params authentication request parameters * @return DefaultRequest object */ public DefaultRequest presignRequest(@NonNull AuthenticationRequestParams params) { final AWS4Signer signer = getConfiguredSigner(params); final DefaultRequest request = createRequestForSigning(params); signer.presignRequest(request, params.getAwsCredentials(), getExpiryDate()); return request; } private DefaultRequest createRequestForSigning(AuthenticationRequestParams params) { final DefaultRequest request = new DefaultRequest(params.getServiceScope()); request.setHttpMethod(HttpMethodName.GET); try { request.setEndpoint(new URI("kafka://" + params.getHost())); } catch (URISyntaxException e) { throw new IllegalArgumentException("Failed to parse host URI", e); } request.addParameter(ACTION_KEY, ACTION_VALUE); return request; } private java.util.Date getExpiryDate() { return Date.from(Instant.ofEpochMilli(Instant.now().toEpochMilli() + TimeUnit.MINUTES.toMillis( EXPIRY_DURATION_MINUTES))); } private AWS4Signer getConfiguredSigner(AuthenticationRequestParams params) { final AWS4Signer aws4Signer = new AWS4Signer(); aws4Signer.setServiceName(params.getServiceScope()); aws4Signer.setRegionName(params.getRegion().getName()); if (log.isDebugEnabled()) { log.debug("Signer configured for {} service and {} region", aws4Signer.getServiceName(), aws4Signer.getRegionName()); } return aws4Signer; } private byte[] toPayloadBytes(DefaultRequest request, AuthenticationRequestParams params) throws IOException { final Map<String, String> keyValueMap = toKeyValueMap(request, params); final ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsBytes(keyValueMap); } /** * Convert the signed request into the map of key value strings that will be used to create the signed payload. * It adds all the query parameters and headers in the request object as entries in the map of key value strings. * It also adds the version of the AuthenticationRequestParams into the map of key value strings. * * @param request The signed request that contains the information to be converted into a key value map. * @param params The authentication request parameters used to generate the signed request. * @return A key value map containing the query parameters and headers from the signed request. */ private Map<String, String> toKeyValueMap(DefaultRequest request, AuthenticationRequestParams params) { final Map<String, String> keyValueMap = new HashMap<>(); final Set<Map.Entry<String, List<String>>> parameterEntries = request.getParameters().entrySet(); parameterEntries.stream().forEach( e -> keyValueMap.put(e.getKey().toLowerCase(), generateParameterValue(e.getKey(), e.getValue()))); keyValueMap.put(VERSION_KEY, params.getVersion()); keyValueMap.put(USER_AGENT_KEY, params.getUserAgent()); //Add the headers. final Set<Map.Entry<String, String>> headerEntries = request.getHeaders().entrySet(); headerEntries.stream().forEach(e -> keyValueMap.put(e.getKey().toLowerCase(), e.getValue())); return keyValueMap; } /** * Convert a query parameter value which is a list of strings into a single string. * The values of all query parameters other than signed headers are expected to be a list of length 1 or 0. * If the parameter value is of length 0, return an empty string. * If the parameter value is of length 1, return the sole element. * if the parameter value is longer than 1, join the list of string into a single string, separate by ";". * * @param key The name of the query parameter. * @param value The list of strings that is the value of the query parameter. * @return A single joined string. */ private String generateParameterValue(String key, List<String> value) { if (value.isEmpty()) { return ""; } if (value.size() > 1) { if (!SignerConstants.X_AMZ_SIGNED_HEADER.equals(key)) { throw new IllegalArgumentException( "Unexpected number of arguments " + value.size() + " for query parameter " + key); } final StringJoiner joiner = new StringJoiner(";"); value.stream().forEach(joiner::add); return joiner.toString(); } return value.get(0); } }
5,586
0
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam/internals/AWSCredentialsCallback.java
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package software.amazon.msk.auth.iam.internals; import com.amazonaws.auth.AWSCredentials; import lombok.Getter; import lombok.NonNull; import software.amazon.msk.auth.iam.IAMClientCallbackHandler; import javax.security.auth.callback.Callback; /** * This class is used to pass AWSCredentials to the {@link IAMSaslClient}. * It is processed by the {@link IAMClientCallbackHandler}. * If the callback handler succeeds, it sets the AWSCredentials. If the callback handler fails to load the credentials, * it sets the loading exception. */ public class AWSCredentialsCallback implements Callback { @Getter private AWSCredentials awsCredentials = null; @Getter private Exception loadingException = null; public void setAwsCredentials(@NonNull AWSCredentials awsCredentials) { this.awsCredentials = awsCredentials; this.loadingException = null; } public void setLoadingException(@NonNull Exception loadingException) { this.loadingException = loadingException; this.awsCredentials = null; } public boolean isSuccessful() { return awsCredentials != null; } }
5,587
0
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam/internals/AuthenticationRequestParams.java
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package software.amazon.msk.auth.iam.internals; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.regions.Region; import com.amazonaws.regions.RegionMetadata; import com.amazonaws.partitions.PartitionsLoader; import com.amazonaws.regions.Regions; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NonNull; import java.util.Optional; /** * This class represents the parameters that will be used to generate the Sigv4 signature * as well as the final Authentication Payload sent to the kafka broker. * The class is versioned so that it can be extended if necessary in the future. **/ @Getter @AllArgsConstructor(access = AccessLevel.PRIVATE) public class AuthenticationRequestParams { private static final String VERSION_1 = "2020_10_22"; private static final String SERVICE_SCOPE = "kafka-cluster"; private static RegionMetadata regionMetadata = new RegionMetadata(new PartitionsLoader().build()); /* we are not using the RegionMetadataFactory.create() method here as one of its path relies on the LegacyRegionXmlMetadataBuilder which does not implement tryGetRegionByEndpointDnsSuffix */ @NonNull private final String version; @NonNull private final String host; @NonNull private final AWSCredentials awsCredentials; @NonNull private final Region region; @NonNull private final String userAgent; public String getServiceScope() { return SERVICE_SCOPE; } public static AuthenticationRequestParams create(@NonNull String host, AWSCredentials credentials, @NonNull String userAgent) throws IllegalArgumentException { Region region = Optional.ofNullable(regionMetadata.tryGetRegionByEndpointDnsSuffix(host)) .orElseGet(() -> Regions.getCurrentRegion()); if (region == null) { throw new IllegalArgumentException("Host " + host + " does not belong to a valid region."); } return new AuthenticationRequestParams(VERSION_1, host, credentials, region, userAgent); } }
5,588
0
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam/internals/PayloadGenerationException.java
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package software.amazon.msk.auth.iam.internals; import java.io.IOException; public class PayloadGenerationException extends IOException { public PayloadGenerationException(String message, Throwable cause) { super(message, cause); } }
5,589
0
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam/internals/SignedPayloadGenerator.java
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package software.amazon.msk.auth.iam.internals; interface SignedPayloadGenerator { byte[] signedPayload(AuthenticationRequestParams authenticationRequestParams) throws PayloadGenerationException; }
5,590
0
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam
Create_ds/aws-msk-iam-auth/src/main/java/software/amazon/msk/auth/iam/internals/UserAgentUtils.java
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package software.amazon.msk.auth.iam.internals; import com.amazonaws.util.ClassLoaderHelper; import com.amazonaws.util.VersionInfoUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.InputStream; import java.util.Properties; import java.util.StringJoiner; import static com.amazonaws.util.IOUtils.closeQuietly; /** * This class is used to generate the user agent for the authentication request. */ public final class UserAgentUtils { private static final Logger log = LoggerFactory.getLogger(UserAgentUtils.class); private static final String USER_AGENT_SEP = "/"; private static final String USER_AGENT_NAME = "aws-msk-iam-auth"; private static final String VERSION_INFO_FILE = "version.properties"; //TODO: UPDATE WHEN NEW VERSIONS ARE PUBLISHED. //TODO: Find a way to read the library version from a resource generated by the build system. private static final String[] AGENT_COMPONENTS = new String[] { USER_AGENT_NAME, getLibraryVersion(), VersionInfoUtils.getUserAgent() }; private static final String USER_AGENT_STRING = generateUserAgentString(AGENT_COMPONENTS); private static final String generateUserAgentString(String[] components) { StringJoiner joiner = new StringJoiner(USER_AGENT_SEP); for (String component : components) { joiner.add(component); } return joiner.toString(); } private static String getLibraryVersion() { String version = "unknown-version"; InputStream inputStream = ClassLoaderHelper.getResourceAsStream( VERSION_INFO_FILE, true, UserAgentUtils.class); Properties versionProperties = new Properties(); try { if (inputStream == null) { log.info("Unable to load version information for msk iam auth plugin"); } else { versionProperties.load(inputStream); version = versionProperties.getProperty("version"); } } catch (Exception e) { log.info("Unable to load version information for the running SDK: " + e.getMessage()); } finally { closeQuietly(inputStream, null); } return version; } public static String getUserAgentValue() { return USER_AGENT_STRING; } }
5,591
0
Create_ds/atlas/atlas-core/src/test/java/com/netflix/atlas/core
Create_ds/atlas/atlas-core/src/test/java/com/netflix/atlas/core/validation/JavaTestRule.java
/* * Copyright 2014-2023 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.atlas.core.validation; import com.typesafe.config.Config; public class JavaTestRule extends TagRuleWrapper { public JavaTestRule(Config conf) { } @Override public String validate(String k, String v) { return null; } }
5,592
0
Create_ds/atlas/atlas-core/src/main/scala/com/netflix/atlas/core
Create_ds/atlas/atlas-core/src/main/scala/com/netflix/atlas/core/util/PrimeFinder.java
/* * Copyright 2014-2023 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.atlas.core.util; import java.util.Arrays; /** * Copied from the apache-mahout project. * * <p>Not of interest for users; only for implementors of hashtables. * Used to keep hash table capacities prime numbers. * * <p>Choosing prime numbers as hash table capacities is a good idea to keep them working fast, * particularly under hash table expansions. * * <p>However, JDK 1.2, JGL 3.1 and many other toolkits do nothing to keep capacities prime. * This class provides efficient means to choose prime capacities. * * <p>Choosing a prime is <tt>O(log 300)</tt> (binary search in a list of 300 int's). * Memory requirements: 1 KB static memory. * */ class PrimeFinder { /** The largest prime this class can generate; currently equal to <tt>Integer.MAX_VALUE</tt>. */ public static final int largestPrime = Integer.MAX_VALUE; //yes, it is prime. /** * The prime number list consists of 11 chunks. Each chunk contains prime numbers. A chunk starts with a prime P1. The * next element is a prime P2. P2 is the smallest prime for which holds: P2 >= 2*P1. The next element is P3, for which * the same holds with respect to P2, and so on. * * <p>Chunks are chosen such that for any desired capacity >= 1000 the list includes a prime number <= desired capacity * * 1.11 (11%). For any desired capacity >= 200 the list includes a prime number <= desired capacity * 1.16 (16%). For * any desired capacity >= 16 the list includes a prime number <= desired capacity * 1.21 (21%). * * <p>Therefore, primes can be retrieved which are quite close to any desired capacity, which in turn avoids wasting * memory. For example, the list includes 1039,1117,1201,1277,1361,1439,1523,1597,1759,1907,2081. So if you need a * prime >= 1040, you will find a prime <= 1040*1.11=1154. * * <p>Chunks are chosen such that they are optimized for a hashtable growthfactor of 2.0; If your hashtable has such a * growthfactor then, after initially "rounding to a prime" upon hashtable construction, it will later expand to prime * capacities such that there exist no better primes. * * <p>In total these are about 32*10=320 numbers -> 1 KB of static memory needed. If you are stingy, then delete every * second or fourth chunk. */ private static final int[] primeCapacities = { //chunk #0 largestPrime, //chunk #1 5, 11, 23, 47, 97, 197, 397, 797, 1597, 3203, 6421, 12853, 25717, 51437, 102877, 205759, 411527, 823117, 1646237, 3292489, 6584983, 13169977, 26339969, 52679969, 105359939, 210719881, 421439783, 842879579, 1685759167, //chunk #2 433, 877, 1759, 3527, 7057, 14143, 28289, 56591, 113189, 226379, 452759, 905551, 1811107, 3622219, 7244441, 14488931, 28977863, 57955739, 115911563, 231823147, 463646329, 927292699, 1854585413, //chunk #3 953, 1907, 3821, 7643, 15287, 30577, 61169, 122347, 244703, 489407, 978821, 1957651, 3915341, 7830701, 15661423, 31322867, 62645741, 125291483, 250582987, 501165979, 1002331963, 2004663929, //chunk #4 1039, 2081, 4177, 8363, 16729, 33461, 66923, 133853, 267713, 535481, 1070981, 2141977, 4283963, 8567929, 17135863, 34271747, 68543509, 137087021, 274174111, 548348231, 1096696463, //chunk #5 31, 67, 137, 277, 557, 1117, 2237, 4481, 8963, 17929, 35863, 71741, 143483, 286973, 573953, 1147921, 2295859, 4591721, 9183457, 18366923, 36733847, 73467739, 146935499, 293871013, 587742049, 1175484103, //chunk #6 599, 1201, 2411, 4831, 9677, 19373, 38747, 77509, 155027, 310081, 620171, 1240361, 2480729, 4961459, 9922933, 19845871, 39691759, 79383533, 158767069, 317534141, 635068283, 1270136683, //chunk #7 311, 631, 1277, 2557, 5119, 10243, 20507, 41017, 82037, 164089, 328213, 656429, 1312867, 2625761, 5251529, 10503061, 21006137, 42012281, 84024581, 168049163, 336098327, 672196673, 1344393353, //chunk #8 3, 7, 17, 37, 79, 163, 331, 673, 1361, 2729, 5471, 10949, 21911, 43853, 87719, 175447, 350899, 701819, 1403641, 2807303, 5614657, 11229331, 22458671, 44917381, 89834777, 179669557, 359339171, 718678369, 1437356741, //chunk #9 43, 89, 179, 359, 719, 1439, 2879, 5779, 11579, 23159, 46327, 92657, 185323, 370661, 741337, 1482707, 2965421, 5930887, 11861791, 23723597, 47447201, 94894427, 189788857, 379577741, 759155483, 1518310967, //chunk #10 379, 761, 1523, 3049, 6101, 12203, 24407, 48817, 97649, 195311, 390647, 781301, 1562611, 3125257, 6250537, 12501169, 25002389, 50004791, 100009607, 200019221, 400038451, 800076929, 1600153859 }; static { //initializer // The above prime numbers are formatted for human readability. // To find numbers fast, we sort them once and for all. Arrays.sort(primeCapacities); } /** Makes this class non instantiable, but still let's others inherit from it. */ private PrimeFinder() { } /** * Returns a prime number which is <code>&gt;= desiredCapacity</code> and very close to <code>desiredCapacity</code> * (within 11% if <code>desiredCapacity &gt;= 1000</code>). * * @param desiredCapacity the capacity desired by the user. * @return the capacity which should be used for a hashtable. */ public static int nextPrime(int desiredCapacity) { int i = java.util.Arrays.binarySearch(primeCapacities, desiredCapacity); if (i < 0) { // desired capacity not found, choose next prime greater than desired capacity i = -i - 1; // remember the semantics of binarySearch... } return primeCapacities[i]; } }
5,593
0
Create_ds/atlas/atlas-core/src/main/scala/com/netflix/atlas/core
Create_ds/atlas/atlas-core/src/main/scala/com/netflix/atlas/core/util/Features.java
/* * Copyright 2014-2023 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.atlas.core.util; /** * Set of features that are enabled for the API. */ public enum Features { /** Default feature set that is stable and the user can rely on. */ STABLE, /** * Indicates that unstable features should be enabled for testing by early adopters. * Features in this set can change at anytime without notice. A feature should not stay * in this state for a long time. A few months should be considered an upper bound. */ UNSTABLE }
5,594
0
Create_ds/atlas/atlas-eval/src/main/scala/com/netflix/atlas/eval
Create_ds/atlas/atlas-eval/src/main/scala/com/netflix/atlas/eval/stream/Evaluator.java
/* * Copyright 2014-2023 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.atlas.eval.stream; import org.apache.pekko.actor.ActorSystem; import org.apache.pekko.http.javadsl.model.Uri; import org.apache.pekko.stream.Materializer; import org.apache.pekko.stream.ThrottleMode; import org.apache.pekko.stream.javadsl.Flow; import org.apache.pekko.stream.javadsl.Framing; import org.apache.pekko.stream.javadsl.Source; import org.apache.pekko.stream.javadsl.StreamConverters; import org.apache.pekko.util.ByteString; import com.fasterxml.jackson.annotation.JsonIgnore; import com.netflix.atlas.core.util.Strings$; import com.netflix.atlas.json.JsonSupport; import com.netflix.spectator.api.NoopRegistry; import com.netflix.spectator.api.Registry; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import org.reactivestreams.Processor; import org.reactivestreams.Publisher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.time.Duration; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * Public API for streaming evaluation of expressions. */ public final class Evaluator extends EvaluatorImpl { /** * Create a new instance. It is assumed this is created via the injector and the * signature may change over time. */ public Evaluator(Config config, Registry registry, ActorSystem system) { super(config, registry, system, Materializer.createMaterializer(system)); } /** * Collects the data from LWC for the specified duration and store it to a file. The * file can then be used as an input to replay evaluation. * * @param uri * Source URI for collecting the data. * @param file * Output file to store the results. * @param duration * Specified how long the collection will run. Note this method will block until * the collection is complete. */ public void writeInputToFile(String uri, Path file, Duration duration) { writeInputToFileImpl(uri, file, duration); } /** * Creates a publisher stream for a given URI. * * @param uri * Source URI for collecting the data. * @return * Publisher that produces events representing the evaluation results for the * expression in the URI. */ public Publisher<JsonSupport> createPublisher(String uri) { return createPublisherImpl(uri); } /** * Creates a processor that can multiplex many streams at once. This can be used to * help reduce the overhead in terms of number of connections and duplicate work on * the backend producing the data. * * <p>It takes a stream of data sources as an input and returns the output of evaluating * those streams. Each {@code DataSources} object should be the complete set of * sources that should be evaluated at a given time. The output messages can be * correlated with a particular data source using the id on the {@code MessageEnvelope}. */ public Processor<DataSources, MessageEnvelope> createStreamsProcessor() { return createStreamsProcessorImpl(); } /** * Creates a processor that evaluates a fixed set of expressions against the stream of * time grouped datapoints. The caller must ensure: * * <ul> * <li>All data sources have the same step size. This is required because there is a * single input datapoint stream with a fixed step.</li> * <li>There should be a single group for each step interval with timestamps aligned to * the step boundary.</li> * <li>Operations are feasible for the input. Time based operators may or may not work * correctly depending on how the timestamps for the input groups are determined. * For use-cases where the the timestamps are generated arbitrarily, such as incrementing * for each group once a certain number of datapoints is available, then operators * based on a clock such as {@code :time} will have bogus values based on the arbitrary * times for the group. If the data is a snapshot of an actual stream, then time based * operators should work correctly.</li> * </ul> */ public Processor<DatapointGroup, MessageEnvelope> createDatapointProcessor(DataSources sources) { return createDatapointProcessorImpl(sources); } /** * Perform static analysis checks to ensure that the provided data source is supported * by this evaluator instance. * * @param ds * Data source to validate. */ public void validate(DataSource ds) { validateImpl(ds); } /** * Immutable set of data sources that should be consumed. */ public record DataSources(Set<DataSource> sources) { /** Create a new instance that is empty. */ public static DataSources empty() { return new DataSources(Collections.emptySet()); } /** Create a new instance. */ public static DataSources of(DataSource... sources) { Set<DataSource> set = new HashSet<>(Arrays.asList(sources)); return new DataSources(set); } /** Create a new instance. */ public DataSources { sources = Set.copyOf(sources); } /** Compares with another set and returns the new data sources that have been added. */ public Set<DataSource> addedSources(DataSources other) { Set<DataSource> copy = new HashSet<>(sources); copy.removeAll(other.sources()); return copy; } /** Compares with another set and returns the data sources that have been removed. */ public Set<DataSource> removedSources(DataSources other) { return other.addedSources(this); } DataSources remoteOnly() { Set<DataSource> remote = new HashSet<>(sources); remote.removeAll(localSources()); return new DataSources(remote); } DataSources localOnly() { return new DataSources(localSources()); } private Set<DataSource> localSources() { return sources.stream() .filter(DataSource::isLocal) .collect(Collectors.toSet()); } /** * Return the step size for the sources in this set. If there are mixed step sizes an * IllegalStateException will be thrown. If the set is empty, then -1 will be returned. */ long stepSize() { long step = -1L; for (DataSource source : sources) { long sourceStep = source.step().toMillis(); if (step != -1L && step != sourceStep) { throw new IllegalStateException("inconsistent step sizes, expected " + step + ", found " + sourceStep + " on " + source); } step = sourceStep; } return step; } } /** * Triple mapping an id to a step size and a URI that should be consumed. The * id can be used to find the messages in the output that correspond to this * data source. * * @param id * An identifier for this {@code DataSource}. It will be added to * corresponding MessageEnvelope objects in the output, facilitating * matching output messages with the data source. * @param step * The requested step size for this {@code DataSource}. <em>NOTE:</em> * This may result in rejection of this {@code DataSource} if the * backing metrics producers do not support the requested step size. * @param uri * The URI for this {@code DataSource} (in atlas backend form). */ public record DataSource(String id, Duration step, String uri) { /** * Create a new instance. */ public DataSource { step = step == null ? extractStepFromUri(uri) : step; } /** * Create a new instance with the step size being derived from the URI or falling * back to {@link #DEFAULT_STEP}. * * @param id * An identifier for this {@code DataSource}. It will be added to * corresponding MessageEnvelope objects in the output, facilitating * matching output messages with the data source. * @param uri * The URI for this {@code DataSource} (in atlas backend form). */ public DataSource(String id, String uri) { this(id, null, uri); } /** Returns true if the URI is for a local file or classpath resource. */ @JsonIgnore public boolean isLocal() { return uri.startsWith("/") || uri.startsWith("file:") || uri.startsWith("resource:") || uri.startsWith("synthetic:"); } } /** * Wraps the output messages from the evaluation with the id of the data source. This * can be used to route the message back to the appropriate consumer. */ public record MessageEnvelope(String id, JsonSupport message) { } /** * Group of datapoints for the same time. */ public record DatapointGroup(long timestamp, List<Datapoint> datapoints) { } /** * Represents a datapoint for a dataset that is generated independently of the LWC clusters. * This can be used for synthetic data or if there is an alternative data source such as a * stream of events that are being mapped into streaming time series. */ public record Datapoint(Map<String, String> tags, double value) { } /** The default step size. */ private static final Duration DEFAULT_STEP = Duration.ofSeconds(60L); /** * Try to extract the step size based on the URI query parameter. If this fails for any * reason or the parameter is not present, then use the default of 1 minute. */ private static Duration extractStepFromUri(String uriString) { try { Uri uri = Uri.create(uriString, Uri.RELAXED); return uri.query() .get("step") .map(Strings$.MODULE$::parseDuration) .orElse(DEFAULT_STEP); } catch (Exception e) { return DEFAULT_STEP; } } /** * Helper used for simple tests. A set of URIs will be read from {@code stdin}, one per line, * and sent through a processor created via {@link #createStreamsProcessor()}. The output will * be sent to {@code stdout}. * * @param args * Paths to additional configuration files that should be loaded. The configs will be * loaded in order with later entries overriding earlier ones if there are conflicts. */ public static void main(String[] args) throws Exception { final Logger logger = LoggerFactory.getLogger(Evaluator.class); // Load any additional configurations if present Config config = ConfigFactory.load(); for (String file : args) { logger.info("loading configuration file {}", file); config = ConfigFactory.parseFile(new File(file)) .withFallback(config) .resolve(); } // Setup evaluator ActorSystem system = ActorSystem.create(); Materializer mat = Materializer.createMaterializer(system); Evaluator evaluator = new Evaluator(config, new NoopRegistry(), system); // Process URIs StreamConverters // Read in URIs from stdin .fromInputStream(() -> System.in) .via(Framing.delimiter(ByteString.fromString("\n"), 16384)) .map(b -> b.decodeString(StandardCharsets.UTF_8)) .zipWithIndex() // Use line number as id for output .map(p -> new DataSource(p.second().toString(), p.first())) .fold(new HashSet<DataSource>(), (vs, v) -> { vs.add(v); return vs; }) .map(DataSources::new) .flatMapConcat(Source::repeat) // Repeat so stream doesn't shutdown .throttle( // Throttle to avoid wasting CPU 1, Duration.ofMinutes(1), 1, ThrottleMode.shaping() ) .via(Flow.fromProcessor(evaluator::createStreamsProcessor)) .runForeach( msg -> System.out.printf("%10s: %s%n", msg.id(), msg.message().toJson()), mat ) .toCompletableFuture() .get(); } }
5,595
0
Create_ds/atlas/atlas-eval/src/main/scala/com/netflix/atlas/eval
Create_ds/atlas/atlas-eval/src/main/scala/com/netflix/atlas/eval/model/ExprType.java
/* * Copyright 2014-2023 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.atlas.eval.model; /** Indicates the type of expression for a subscription. */ public enum ExprType { /** * Time series expression such as used with Atlas Graph API. Can also be used for analytics * queries on top of event data. */ TIME_SERIES, /** Expression to select a set of events to be passed through. */ EVENTS, /** Expression to select a set of traces to be passed through. */ TRACES }
5,596
0
Create_ds/atlas/atlas-chart/src/main/scala/com/netflix/atlas/chart
Create_ds/atlas/atlas-chart/src/main/scala/com/netflix/atlas/chart/model/VisionType.java
/* * Copyright 2014-2023 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.atlas.chart.model; import java.awt.Color; /** * Convert a color to simulate a type of color blindness for those with normal vision. Based on: * <a href="http://web.archive.org/web/20081014161121/http://www.colorjack.com/labs/colormatrix/">colormatrix</a>. */ public enum VisionType { normal(new double[] { 1.000, 0.000, 0.000, 0.000, // R 0.000, 1.000, 0.000, 0.000, // G 0.000, 0.000, 1.000, 0.000, // B 0.000, 0.000, 0.000, 1.000 // A }), protanopia(new double[] { 0.567, 0.433, 0.000, 0.000, // R 0.558, 0.442, 0.000, 0.000, // G 0.000, 0.242, 0.758, 0.000, // B 0.000, 0.000, 0.000, 1.000 // A }), protanomaly(new double[] { 0.817, 0.183, 0.000, 0.000, // R 0.333, 0.667, 0.000, 0.000, // G 0.000, 0.125, 0.875, 0.000, // B 0.000, 0.000, 0.000, 1.000 // A }), deuteranopia(new double[] { 0.625, 0.375, 0.000, 0.000, // R 0.700, 0.300, 0.000, 0.000, // G 0.000, 0.300, 0.700, 0.000, // B 0.000, 0.000, 0.000, 1.000 // A }), deuteranomaly(new double[] { 0.800, 0.200, 0.000, 0.000, // R 0.258, 0.742, 0.000, 0.000, // G 0.000, 0.142, 0.858, 0.000, // B 0.000, 0.000, 0.000, 1.000 // A }), tritanopia(new double[] { 0.950, 0.050, 0.000, 0.000, // R 0.000, 0.433, 0.567, 0.000, // G 0.000, 0.475, 0.525, 0.000, // B 0.000, 0.000, 0.000, 1.000 // A }), tritanomaly(new double[] { 0.967, 0.033, 0.000, 0.000, // R 0.000, 0.733, 0.267, 0.000, // G 0.000, 0.183, 0.817, 0.000, // B 0.000, 0.000, 0.000, 1.000 // A }), achromatopsia(new double[] { 0.299, 0.587, 0.114, 0.000, // R 0.299, 0.587, 0.114, 0.000, // G 0.299, 0.587, 0.114, 0.000, // B 0.000, 0.000, 0.000, 1.000 // A }), achromatomaly(new double[] { 0.618, 0.320, 0.062, 0.000, // R 0.163, 0.775, 0.062, 0.000, // G 0.163, 0.320, 0.516, 0.000, // B 0.000, 0.000, 0.000, 1.000 // A }); private final double[] m; VisionType(double[] m) { this.m = m; } public Color convert(Color c) { final int cr = c.getRed(); final int cg = c.getGreen(); final int cb = c.getBlue(); final int ca = c.getAlpha(); final int br = (int) (cr * m[0] + cg * m[1] + cb * m[2] + ca * m[3]); final int bg = (int) (cr * m[4] + cg * m[5] + cb * m[6] + ca * m[7]); final int bb = (int) (cr * m[8] + cg * m[9] + cb * m[10] + ca * m[11]); final int ba = (int) (cr * m[12] + cg * m[13] + cb * m[14] + ca * m[15]); return new Color(br, bg, bb, ba); } }
5,597
0
Create_ds/atlas/atlas-chart/src/main/scala/com/netflix/atlas/chart
Create_ds/atlas/atlas-chart/src/main/scala/com/netflix/atlas/chart/model/Layout.java
/* * Copyright 2014-2023 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.atlas.chart.model; /** * Layout mode to use for the chart. */ public enum Layout { /** * Size is specified for the canvas showing the data and the image size is determined * automatically. This mode is the default and is intended to make it easy to get a consistent * canvas size for a set of charts. */ CANVAS(false, false), /** * Size is specified for the image. Other elements will resize or shut off to fit within the * requested size. */ IMAGE(true, true), /** * Width is for the image, but height is for the canvas. This can be useful for pages that * need to perform column spans for some rows. The height will be automatically determined. */ IMAGE_WIDTH(true, false), /** * Height is for the image, but width is for the canvas. */ IMAGE_HEIGHT(false, true); private final boolean fixedWidth; private final boolean fixedHeight; Layout(boolean fixedWidth, boolean fixedHeight) { this.fixedWidth = fixedWidth; this.fixedHeight = fixedHeight; } public boolean isFixedWidth() { return fixedWidth; } public boolean isFixedHeight() { return fixedHeight; } public static Layout create(String name) { return switch (name) { case "canvas" -> Layout.CANVAS; case "image" -> Layout.IMAGE; case "iw" -> Layout.IMAGE_WIDTH; case "ih" -> Layout.IMAGE_HEIGHT; default -> throw new IllegalArgumentException("unknown layout: " + name); }; } }
5,598
0
Create_ds/atlas/atlas-chart/src/main/scala/com/netflix/atlas/chart
Create_ds/atlas/atlas-chart/src/main/scala/com/netflix/atlas/chart/model/TickLabelMode.java
/* * Copyright 2014-2023 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.atlas.chart.model; import java.util.Locale; /** * Mode for how to format the tick labels on Y-axes. */ public enum TickLabelMode { /** * Do no show tick labels. It can be useful to suppress the labels for including the charts * in presentations or support tickets where it is not desirable to share the exact numbers. */ OFF, /** * Use decimal <a href="https://en.wikipedia.org/wiki/Metric_prefix">metric prefixes</a> for * tick labels. */ DECIMAL, /** * Use <a href="https://en.wikipedia.org/wiki/Binary_prefix">binary prefixes</a> for tick * labels. Typically only used for data in bytes such as disk sizes. */ BINARY, /** * Use SI for durations less than a second and 's', 'min', 'hr', 'day', 'mon', 'yr' over that. */ DURATION; /** * Case insensitive conversion of a string name to an enum value. */ public static TickLabelMode apply(String mode) { try { return valueOf(mode.toUpperCase(Locale.US)); } catch (IllegalArgumentException e) { // Make the error message a bit more user friendly throw new IllegalArgumentException("tick_labels: unknown value '" + mode + "', acceptable values are off, decimal, and binary"); } } }
5,599