Search in sources :

Example 1 with JobExecutionsChangedSubscriptionRequest

use of software.amazon.awssdk.iot.iotjobs.model.JobExecutionsChangedSubscriptionRequest in project aws-greengrass-nucleus by aws-greengrass.

the class IotJobsHelper method subscribeToEventNotifications.

/**
 * Subscribe to $aws/things/{thingName}/jobs/notify topic.
 *
 * @param eventHandler The handler which run when an event is received
 * @throws ExecutionException   When subscribe failed with an exception
 * @throws InterruptedException When this thread was interrupted
 * @throws TimeoutException     if the operation does not complete within the given time
 */
protected void subscribeToEventNotifications(Consumer<JobExecutionsChangedEvent> eventHandler) throws InterruptedException {
    logger.atDebug().log("Subscribing to deployment job event notifications.");
    JobExecutionsChangedSubscriptionRequest request = new JobExecutionsChangedSubscriptionRequest();
    request.thingName = this.thingName;
    while (true) {
        CompletableFuture<Integer> subscribed = iotJobsClientWrapper.SubscribeToJobExecutionsChangedEvents(request, QualityOfService.AT_LEAST_ONCE, eventHandler);
        try {
            subscribed.get(mqttClient.getMqttOperationTimeoutMillis(), TimeUnit.MILLISECONDS);
            logger.atDebug().log("Subscribed to deployment job event notifications.");
            break;
        } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof MqttException || cause instanceof TimeoutException) {
                logger.atWarn().setCause(cause).log(SUBSCRIPTION_EVENT_NOTIFICATIONS_RETRY);
            }
            if (cause instanceof InterruptedException) {
                logger.atWarn().log(SUBSCRIPTION_EVENT_NOTIFICATIONS_INTERRUPTED);
                break;
            }
        } catch (InterruptedException e) {
            logger.atWarn().log(SUBSCRIPTION_EVENT_NOTIFICATIONS_INTERRUPTED);
            throw e;
        } catch (TimeoutException e) {
            logger.atWarn().setCause(e).log(SUBSCRIPTION_EVENT_NOTIFICATIONS_RETRY);
        }
        try {
            // Wait for sometime and then try to subscribe again
            Thread.sleep(waitTimeToSubscribeAgain + RANDOM.nextInt(10_000));
        } catch (InterruptedException interruptedException) {
            logger.atWarn().log(SUBSCRIPTION_EVENT_NOTIFICATIONS_INTERRUPTED);
            break;
        }
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) JobExecutionsChangedSubscriptionRequest(software.amazon.awssdk.iot.iotjobs.model.JobExecutionsChangedSubscriptionRequest) MqttException(software.amazon.awssdk.crt.mqtt.MqttException) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException)

Example 2 with JobExecutionsChangedSubscriptionRequest

use of software.amazon.awssdk.iot.iotjobs.model.JobExecutionsChangedSubscriptionRequest in project aws-greengrass-nucleus by aws-greengrass.

the class IotJobsHelperTest method GIVEN_jobsClient_and_mqttConnection_WHEN_mqtt_connected_THEN_subscribe_to_eventNotifications.

@Test
void GIVEN_jobsClient_and_mqttConnection_WHEN_mqtt_connected_THEN_subscribe_to_eventNotifications() throws Exception {
    iotJobsHelper.postInject();
    CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.completedFuture(1);
    when(mockIotJobsClientWrapper.SubscribeToJobExecutionsChangedEvents(any(JobExecutionsChangedSubscriptionRequest.class), eq(QualityOfService.AT_LEAST_ONCE), eq(eventConsumer))).thenReturn(integerCompletableFuture);
    iotJobsHelper.subscribeToEventNotifications(eventConsumer);
    ArgumentCaptor<JobExecutionsChangedSubscriptionRequest> requestArgumentCaptor = ArgumentCaptor.forClass(JobExecutionsChangedSubscriptionRequest.class);
    verify(mockIotJobsClientWrapper).SubscribeToJobExecutionsChangedEvents(requestArgumentCaptor.capture(), eq(QualityOfService.AT_LEAST_ONCE), eq(eventConsumer));
    JobExecutionsChangedSubscriptionRequest actualRequest = requestArgumentCaptor.getValue();
    assertEquals(TEST_THING_NAME, actualRequest.thingName);
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) JobExecutionsChangedSubscriptionRequest(software.amazon.awssdk.iot.iotjobs.model.JobExecutionsChangedSubscriptionRequest) Test(org.junit.jupiter.api.Test)

Example 3 with JobExecutionsChangedSubscriptionRequest

use of software.amazon.awssdk.iot.iotjobs.model.JobExecutionsChangedSubscriptionRequest in project aws-iot-device-sdk-java-v2 by aws.

the class IotJobsClient method SubscribeToJobExecutionsChangedEvents.

/**
 * Subscribes to JobExecutionsChanged notifications for a given IoT thing.
 *
 * Once subscribed, `handler` is invoked each time a message matching
 * the `topic` is received. It is possible for such messages to arrive before
 * the SUBACK is received.
 *
 * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-jobexecutionschanged
 *
 * @param request Subscription request configuration
 * @param qos Maximum requested QoS that server may use when sending messages to the client.
 *            The server may grant a lower QoS in the SUBACK
 * @param handler callback function to invoke with messages received on the subscription topic
 * @param exceptionHandler callback function to invoke if an exception occurred deserializing a message
 *
 * @return a future containing the MQTT packet id used to perform the subscribe operation
 */
public CompletableFuture<Integer> SubscribeToJobExecutionsChangedEvents(JobExecutionsChangedSubscriptionRequest request, QualityOfService qos, Consumer<JobExecutionsChangedEvent> handler, Consumer<Exception> exceptionHandler) {
    String topic = "$aws/things/{thingName}/jobs/notify";
    if (request.thingName == null) {
        CompletableFuture<Integer> result = new CompletableFuture<Integer>();
        result.completeExceptionally(new MqttException("JobExecutionsChangedSubscriptionRequest must have a non-null thingName"));
        return result;
    }
    topic = topic.replace("{thingName}", request.thingName);
    Consumer<MqttMessage> messageHandler = (message) -> {
        try {
            String payload = new String(message.getPayload(), StandardCharsets.UTF_8);
            JobExecutionsChangedEvent response = gson.fromJson(payload, JobExecutionsChangedEvent.class);
            handler.accept(response);
        } catch (Exception e) {
            if (exceptionHandler != null) {
                exceptionHandler.accept(e);
            }
        }
    };
    return connection.subscribe(topic, qos, messageHandler);
}
Also used : JobExecutionData(software.amazon.awssdk.iot.iotjobs.model.JobExecutionData) UpdateJobExecutionRequest(software.amazon.awssdk.iot.iotjobs.model.UpdateJobExecutionRequest) NextJobExecutionChangedSubscriptionRequest(software.amazon.awssdk.iot.iotjobs.model.NextJobExecutionChangedSubscriptionRequest) HashMap(java.util.HashMap) EnumSerializer(software.amazon.awssdk.iot.EnumSerializer) CompletableFuture(java.util.concurrent.CompletableFuture) RejectedError(software.amazon.awssdk.iot.iotjobs.model.RejectedError) JobExecutionState(software.amazon.awssdk.iot.iotjobs.model.JobExecutionState) StartNextPendingJobExecutionSubscriptionRequest(software.amazon.awssdk.iot.iotjobs.model.StartNextPendingJobExecutionSubscriptionRequest) GsonBuilder(com.google.gson.GsonBuilder) ByteBuffer(java.nio.ByteBuffer) DescribeJobExecutionRequest(software.amazon.awssdk.iot.iotjobs.model.DescribeJobExecutionRequest) DescribeJobExecutionSubscriptionRequest(software.amazon.awssdk.iot.iotjobs.model.DescribeJobExecutionSubscriptionRequest) UpdateJobExecutionSubscriptionRequest(software.amazon.awssdk.iot.iotjobs.model.UpdateJobExecutionSubscriptionRequest) GetPendingJobExecutionsSubscriptionRequest(software.amazon.awssdk.iot.iotjobs.model.GetPendingJobExecutionsSubscriptionRequest) QualityOfService(software.amazon.awssdk.crt.mqtt.QualityOfService) GetPendingJobExecutionsResponse(software.amazon.awssdk.iot.iotjobs.model.GetPendingJobExecutionsResponse) Gson(com.google.gson.Gson) JobStatus(software.amazon.awssdk.iot.iotjobs.model.JobStatus) GetPendingJobExecutionsRequest(software.amazon.awssdk.iot.iotjobs.model.GetPendingJobExecutionsRequest) StartNextPendingJobExecutionRequest(software.amazon.awssdk.iot.iotjobs.model.StartNextPendingJobExecutionRequest) MqttClientConnection(software.amazon.awssdk.crt.mqtt.MqttClientConnection) DescribeJobExecutionResponse(software.amazon.awssdk.iot.iotjobs.model.DescribeJobExecutionResponse) RejectedErrorCode(software.amazon.awssdk.iot.iotjobs.model.RejectedErrorCode) MqttException(software.amazon.awssdk.crt.mqtt.MqttException) StandardCharsets(java.nio.charset.StandardCharsets) Consumer(java.util.function.Consumer) JobExecutionsChangedEvent(software.amazon.awssdk.iot.iotjobs.model.JobExecutionsChangedEvent) MqttMessage(software.amazon.awssdk.crt.mqtt.MqttMessage) NextJobExecutionChangedEvent(software.amazon.awssdk.iot.iotjobs.model.NextJobExecutionChangedEvent) StartNextJobExecutionResponse(software.amazon.awssdk.iot.iotjobs.model.StartNextJobExecutionResponse) JobExecutionsChangedSubscriptionRequest(software.amazon.awssdk.iot.iotjobs.model.JobExecutionsChangedSubscriptionRequest) Timestamp(software.amazon.awssdk.iot.Timestamp) JobExecutionSummary(software.amazon.awssdk.iot.iotjobs.model.JobExecutionSummary) UpdateJobExecutionResponse(software.amazon.awssdk.iot.iotjobs.model.UpdateJobExecutionResponse) UnsupportedEncodingException(java.io.UnsupportedEncodingException) MqttMessage(software.amazon.awssdk.crt.mqtt.MqttMessage) CompletableFuture(java.util.concurrent.CompletableFuture) MqttException(software.amazon.awssdk.crt.mqtt.MqttException) JobExecutionsChangedEvent(software.amazon.awssdk.iot.iotjobs.model.JobExecutionsChangedEvent) MqttException(software.amazon.awssdk.crt.mqtt.MqttException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Aggregations

JobExecutionsChangedSubscriptionRequest (software.amazon.awssdk.iot.iotjobs.model.JobExecutionsChangedSubscriptionRequest)3 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 MqttException (software.amazon.awssdk.crt.mqtt.MqttException)2 Gson (com.google.gson.Gson)1 GsonBuilder (com.google.gson.GsonBuilder)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 ByteBuffer (java.nio.ByteBuffer)1 StandardCharsets (java.nio.charset.StandardCharsets)1 HashMap (java.util.HashMap)1 CompletableFuture (java.util.concurrent.CompletableFuture)1 ExecutionException (java.util.concurrent.ExecutionException)1 TimeoutException (java.util.concurrent.TimeoutException)1 Consumer (java.util.function.Consumer)1 Test (org.junit.jupiter.api.Test)1 MqttClientConnection (software.amazon.awssdk.crt.mqtt.MqttClientConnection)1 MqttMessage (software.amazon.awssdk.crt.mqtt.MqttMessage)1 QualityOfService (software.amazon.awssdk.crt.mqtt.QualityOfService)1 EnumSerializer (software.amazon.awssdk.iot.EnumSerializer)1 Timestamp (software.amazon.awssdk.iot.Timestamp)1 DescribeJobExecutionRequest (software.amazon.awssdk.iot.iotjobs.model.DescribeJobExecutionRequest)1