Search in sources :

Example 1 with UpdateJobExecutionResponse

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

the class IotJobsFleetStatusServiceTest method setupKernel.

@SuppressWarnings("PMD.CloseResource")
@BeforeEach
void setupKernel(ExtensionContext context) throws Exception {
    ignoreExceptionOfType(context, TLSAuthException.class);
    ignoreExceptionOfType(context, PackageDownloadException.class);
    ignoreExceptionUltimateCauseOfType(context, EOFException.class);
    ignoreExceptionUltimateCauseOfType(context, ResourceNotFoundException.class);
    CountDownLatch fssRunning = new CountDownLatch(1);
    CountDownLatch deploymentServiceRunning = new CountDownLatch(1);
    CompletableFuture<Void> cf = new CompletableFuture<>();
    cf.complete(null);
    lenient().when(mockIotJobsClientWrapper.PublishUpdateJobExecution(any(UpdateJobExecutionRequest.class), any(QualityOfService.class))).thenAnswer(invocationOnMock -> {
        verify(mockIotJobsClientWrapper, atLeastOnce()).SubscribeToUpdateJobExecutionAccepted(any(), eq(QualityOfService.AT_LEAST_ONCE), jobsAcceptedHandlerCaptor.capture());
        Consumer<UpdateJobExecutionResponse> jobResponseConsumer = jobsAcceptedHandlerCaptor.getValue();
        UpdateJobExecutionResponse mockJobExecutionResponse = mock(UpdateJobExecutionResponse.class);
        jobResponseConsumer.accept(mockJobExecutionResponse);
        return cf;
    });
    lenient().when(mqttClient.publish(any())).thenReturn(CompletableFuture.completedFuture(0));
    kernel = new Kernel();
    NoOpPathOwnershipHandler.register(kernel);
    ConfigPlatformResolver.initKernelWithMultiPlatformConfig(kernel, IotJobsFleetStatusServiceTest.class.getResource("onlyMain.yaml"));
    kernel.getContext().put(MqttClient.class, mqttClient);
    kernel.getContext().put(ThingGroupHelper.class, thingGroupHelper);
    // Mock out cloud communication
    GreengrassServiceClientFactory mgscf = mock(GreengrassServiceClientFactory.class);
    GreengrassV2DataClient mcf = mock(GreengrassV2DataClient.class);
    lenient().when(mcf.resolveComponentCandidates(any(ResolveComponentCandidatesRequest.class))).thenThrow(ResourceNotFoundException.class);
    lenient().when(mgscf.getGreengrassV2DataClient()).thenReturn(mcf);
    kernel.getContext().put(GreengrassServiceClientFactory.class, mgscf);
    componentNamesToCheck.clear();
    kernel.getContext().addGlobalStateChangeListener((service, oldState, newState) -> {
        if (service.getName().equals(FleetStatusService.FLEET_STATUS_SERVICE_TOPICS) && newState.equals(State.RUNNING)) {
            fssRunning.countDown();
        }
        if (service.getName().equals(DeploymentService.DEPLOYMENT_SERVICE_TOPICS) && newState.equals(State.RUNNING)) {
            deploymentServiceRunning.countDown();
            deploymentService = (DeploymentService) service;
            IotJobsHelper iotJobsHelper = deploymentService.getContext().get(IotJobsHelper.class);
            iotJobsHelper.setIotJobsClientWrapper(mockIotJobsClientWrapper);
        }
        componentNamesToCheck.add(service.getName());
    });
    // set required instances from context
    deviceConfiguration = new DeviceConfiguration(kernel, "ThingName", "xxxxxx-ats.iot.us-east-1.amazonaws.com", "xxxxxx.credentials.iot.us-east-1.amazonaws.com", "privKeyFilePath", "certFilePath", "caFilePath", "us-east-1", "roleAliasName");
    kernel.getContext().put(DeviceConfiguration.class, deviceConfiguration);
    // pre-load contents to package store
    Path localStoreContentPath = Paths.get(IotJobsFleetStatusServiceTest.class.getResource("local_store_content").toURI());
    PreloadComponentStoreHelper.preloadRecipesFromTestResourceDir(localStoreContentPath.resolve("recipes"), kernel.getNucleusPaths().recipePath());
    copyFolderRecursively(localStoreContentPath.resolve("artifacts"), kernel.getNucleusPaths().artifactPath(), REPLACE_EXISTING);
    kernel.launch();
    assertTrue(fssRunning.await(10, TimeUnit.SECONDS));
    assertTrue(deploymentServiceRunning.await(10, TimeUnit.SECONDS));
}
Also used : Path(java.nio.file.Path) UpdateJobExecutionResponse(software.amazon.awssdk.iot.iotjobs.model.UpdateJobExecutionResponse) GreengrassServiceClientFactory(com.aws.greengrass.util.GreengrassServiceClientFactory) CountDownLatch(java.util.concurrent.CountDownLatch) GreengrassV2DataClient(software.amazon.awssdk.services.greengrassv2data.GreengrassV2DataClient) CompletableFuture(java.util.concurrent.CompletableFuture) IotJobsHelper(com.aws.greengrass.deployment.IotJobsHelper) UpdateJobExecutionRequest(software.amazon.awssdk.iot.iotjobs.model.UpdateJobExecutionRequest) QualityOfService(software.amazon.awssdk.crt.mqtt.QualityOfService) Kernel(com.aws.greengrass.lifecyclemanager.Kernel) DeviceConfiguration(com.aws.greengrass.deployment.DeviceConfiguration) ResolveComponentCandidatesRequest(software.amazon.awssdk.services.greengrassv2data.model.ResolveComponentCandidatesRequest) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 2 with UpdateJobExecutionResponse

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

the class IotJobsClient method SubscribeToUpdateJobExecutionAccepted.

/**
 * Subscribes to the accepted topic for the UpdateJobExecution operation
 *
 * Once subscribed, `handler` is invoked each time a message matching
 * the `topic` is received. It is possible for such messages to arrive before
 * the SUBACK is received.
 *
 * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-updatejobexecution
 *
 * @param request Subscription request configuration
 * @param qos Maximum requested QoS that server may use when sending messages to the client.
 *            The server may grant a lower QoS in the SUBACK
 * @param handler callback function to invoke with messages received on the subscription topic
 * @param exceptionHandler callback function to invoke if an exception occurred deserializing a message
 *
 * @return a future containing the MQTT packet id used to perform the subscribe operation
 */
public CompletableFuture<Integer> SubscribeToUpdateJobExecutionAccepted(UpdateJobExecutionSubscriptionRequest request, QualityOfService qos, Consumer<UpdateJobExecutionResponse> handler, Consumer<Exception> exceptionHandler) {
    String topic = "$aws/things/{thingName}/jobs/{jobId}/update/accepted";
    if (request.jobId == null) {
        CompletableFuture<Integer> result = new CompletableFuture<Integer>();
        result.completeExceptionally(new MqttException("UpdateJobExecutionSubscriptionRequest must have a non-null jobId"));
        return result;
    }
    topic = topic.replace("{jobId}", request.jobId);
    if (request.thingName == null) {
        CompletableFuture<Integer> result = new CompletableFuture<Integer>();
        result.completeExceptionally(new MqttException("UpdateJobExecutionSubscriptionRequest must have a non-null thingName"));
        return result;
    }
    topic = topic.replace("{thingName}", request.thingName);
    Consumer<MqttMessage> messageHandler = (message) -> {
        try {
            String payload = new String(message.getPayload(), StandardCharsets.UTF_8);
            UpdateJobExecutionResponse response = gson.fromJson(payload, UpdateJobExecutionResponse.class);
            handler.accept(response);
        } catch (Exception e) {
            if (exceptionHandler != null) {
                exceptionHandler.accept(e);
            }
        }
    };
    return connection.subscribe(topic, qos, messageHandler);
}
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) UpdateJobExecutionResponse(software.amazon.awssdk.iot.iotjobs.model.UpdateJobExecutionResponse) MqttException(software.amazon.awssdk.crt.mqtt.MqttException) MqttException(software.amazon.awssdk.crt.mqtt.MqttException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 3 with UpdateJobExecutionResponse

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

the class IotJobsHelperTest method GIVEN_jobsClient_and_mqttConnection_WHEN_mqtt_connected_THEN_update_jobStatus_successfully.

@Test
void GIVEN_jobsClient_and_mqttConnection_WHEN_mqtt_connected_THEN_update_jobStatus_successfully() throws Exception {
    iotJobsHelper.postInject();
    String TEST_JOB_ID = "statusUpdateSuccess";
    HashMap<String, String> statusDetails = new HashMap<>();
    statusDetails.put("type", "test");
    CompletableFuture cf = new CompletableFuture();
    cf.complete(null);
    ArgumentCaptor<UpdateJobExecutionSubscriptionRequest> requestArgumentCaptor = ArgumentCaptor.forClass(UpdateJobExecutionSubscriptionRequest.class);
    when(mockIotJobsClientWrapper.PublishUpdateJobExecution(any(), any())).thenAnswer(invocationOnMock -> {
        verify(mockIotJobsClientWrapper).SubscribeToUpdateJobExecutionAccepted(requestArgumentCaptor.capture(), eq(QualityOfService.AT_LEAST_ONCE), updateJobExecutionResponseCaptor.capture());
        Consumer<UpdateJobExecutionResponse> jobResponseConsumer = updateJobExecutionResponseCaptor.getValue();
        UpdateJobExecutionResponse mockJobExecutionResponse = mock(UpdateJobExecutionResponse.class);
        jobResponseConsumer.accept(mockJobExecutionResponse);
        return cf;
    });
    iotJobsHelper.updateJobStatus(TEST_JOB_ID, JobStatus.IN_PROGRESS, statusDetails);
    verify(mockIotJobsClientWrapper).SubscribeToUpdateJobExecutionAccepted(requestArgumentCaptor.capture(), eq(QualityOfService.AT_LEAST_ONCE), updateJobExecutionResponseCaptor.capture());
    UpdateJobExecutionSubscriptionRequest actualRequest = requestArgumentCaptor.getValue();
    assertEquals(TEST_JOB_ID, actualRequest.jobId);
    assertEquals(TEST_THING_NAME, actualRequest.thingName);
    verify(mockWrapperMqttClientConnection).unsubscribe(eq(String.format(JOB_UPDATE_ACCEPTED_TOPIC, TEST_THING_NAME, TEST_JOB_ID)));
    ArgumentCaptor<UpdateJobExecutionRequest> publishRequestCaptor = ArgumentCaptor.forClass(UpdateJobExecutionRequest.class);
    verify(mockIotJobsClientWrapper).PublishUpdateJobExecution(publishRequestCaptor.capture(), eq(QualityOfService.AT_LEAST_ONCE));
    UpdateJobExecutionRequest publishRequest = publishRequestCaptor.getValue();
    assertEquals(TEST_JOB_ID, publishRequest.jobId);
    assertEquals(JobStatus.IN_PROGRESS, publishRequest.status);
    assertEquals(statusDetails, publishRequest.statusDetails);
    assertEquals(TEST_THING_NAME, publishRequest.thingName);
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) UpdateJobExecutionResponse(software.amazon.awssdk.iot.iotjobs.model.UpdateJobExecutionResponse) HashMap(java.util.HashMap) UpdateJobExecutionSubscriptionRequest(software.amazon.awssdk.iot.iotjobs.model.UpdateJobExecutionSubscriptionRequest) UpdateJobExecutionRequest(software.amazon.awssdk.iot.iotjobs.model.UpdateJobExecutionRequest) Test(org.junit.jupiter.api.Test)

Example 4 with UpdateJobExecutionResponse

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

the class IotJobsClientWrapper method SubscribeToUpdateJobExecutionAccepted.

@Override
public CompletableFuture<Integer> SubscribeToUpdateJobExecutionAccepted(UpdateJobExecutionSubscriptionRequest request, QualityOfService qos, Consumer<UpdateJobExecutionResponse> handler, Consumer<Exception> exceptionHandler) {
    if (request.jobId == null || request.thingName == null) {
        CompletableFuture result = new CompletableFuture();
        result.completeExceptionally(new MqttException("UpdateJobExecutionSubscriptionRequest must have a non-null jobId and a non-null thingName"));
        return result;
    }
    String topic = String.format(JOB_UPDATE_ACCEPTED_TOPIC, request.thingName, request.jobId);
    Consumer<MqttMessage> messageHandler = updateJobExecutionCbs.computeIfAbsent(new Pair<>(handler, exceptionHandler), (k) -> (message) -> {
        try {
            String payload = new String(message.getPayload(), StandardCharsets.UTF_8);
            UpdateJobExecutionResponse response = this.gson.fromJson(payload, UpdateJobExecutionResponse.class);
            handler.accept(response);
        } catch (Exception e) {
            if (exceptionHandler != null) {
                exceptionHandler.accept(e);
            }
        }
    });
    return this.connection.subscribe(topic, qos, messageHandler);
}
Also used : MqttMessage(software.amazon.awssdk.crt.mqtt.MqttMessage) CompletableFuture(java.util.concurrent.CompletableFuture) UpdateJobExecutionResponse(software.amazon.awssdk.iot.iotjobs.model.UpdateJobExecutionResponse) MqttException(software.amazon.awssdk.crt.mqtt.MqttException) MqttException(software.amazon.awssdk.crt.mqtt.MqttException)

Aggregations

CompletableFuture (java.util.concurrent.CompletableFuture)4 UpdateJobExecutionResponse (software.amazon.awssdk.iot.iotjobs.model.UpdateJobExecutionResponse)4 UpdateJobExecutionRequest (software.amazon.awssdk.iot.iotjobs.model.UpdateJobExecutionRequest)3 HashMap (java.util.HashMap)2 MqttException (software.amazon.awssdk.crt.mqtt.MqttException)2 MqttMessage (software.amazon.awssdk.crt.mqtt.MqttMessage)2 QualityOfService (software.amazon.awssdk.crt.mqtt.QualityOfService)2 DeviceConfiguration (com.aws.greengrass.deployment.DeviceConfiguration)1 IotJobsHelper (com.aws.greengrass.deployment.IotJobsHelper)1 Kernel (com.aws.greengrass.lifecyclemanager.Kernel)1 GreengrassServiceClientFactory (com.aws.greengrass.util.GreengrassServiceClientFactory)1 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 Path (java.nio.file.Path)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 Consumer (java.util.function.Consumer)1 BeforeEach (org.junit.jupiter.api.BeforeEach)1