index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs/IotJobsClient.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.iot.iotjobs; import java.util.HashMap; import software.amazon.awssdk.iot.iotjobs.model.DescribeJobExecutionRequest; import software.amazon.awssdk.iot.iotjobs.model.DescribeJobExecutionResponse; import software.amazon.awssdk.iot.iotjobs.model.DescribeJobExecutionSubscriptionRequest; import software.amazon.awssdk.iot.iotjobs.model.GetPendingJobExecutionsRequest; import software.amazon.awssdk.iot.iotjobs.model.GetPendingJobExecutionsResponse; import software.amazon.awssdk.iot.iotjobs.model.GetPendingJobExecutionsSubscriptionRequest; import software.amazon.awssdk.iot.iotjobs.model.JobExecutionData; import software.amazon.awssdk.iot.iotjobs.model.JobExecutionState; import software.amazon.awssdk.iot.iotjobs.model.JobExecutionSummary; import software.amazon.awssdk.iot.iotjobs.model.JobExecutionsChangedEvent; import software.amazon.awssdk.iot.iotjobs.model.JobExecutionsChangedSubscriptionRequest; import software.amazon.awssdk.iot.iotjobs.model.JobStatus; import software.amazon.awssdk.iot.iotjobs.model.NextJobExecutionChangedEvent; import software.amazon.awssdk.iot.iotjobs.model.NextJobExecutionChangedSubscriptionRequest; import software.amazon.awssdk.iot.iotjobs.model.RejectedError; import software.amazon.awssdk.iot.iotjobs.model.RejectedErrorCode; import software.amazon.awssdk.iot.iotjobs.model.StartNextJobExecutionResponse; import software.amazon.awssdk.iot.iotjobs.model.StartNextPendingJobExecutionRequest; import software.amazon.awssdk.iot.iotjobs.model.StartNextPendingJobExecutionSubscriptionRequest; import software.amazon.awssdk.iot.iotjobs.model.UpdateJobExecutionRequest; import software.amazon.awssdk.iot.iotjobs.model.UpdateJobExecutionResponse; import software.amazon.awssdk.iot.iotjobs.model.UpdateJobExecutionSubscriptionRequest; import java.nio.charset.StandardCharsets; import software.amazon.awssdk.crt.mqtt.MqttClientConnection; import software.amazon.awssdk.crt.mqtt.QualityOfService; import software.amazon.awssdk.crt.mqtt.MqttException; import software.amazon.awssdk.crt.mqtt.MqttMessage; import software.amazon.awssdk.iot.Timestamp; import software.amazon.awssdk.iot.EnumSerializer; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; /** * The AWS IoT jobs service can be used to define a set of remote operations that are sent to and executed on one or more devices connected to AWS IoT. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#jobs-mqtt-api * */ public class IotJobsClient { private MqttClientConnection connection = null; private final Gson gson = getGson(); /** * Constructs a new IotJobsClient * @param connection The connection to use */ public IotJobsClient(MqttClientConnection connection) { this.connection = connection; } private Gson getGson() { GsonBuilder gson = new GsonBuilder(); gson.disableHtmlEscaping(); gson.registerTypeAdapter(Timestamp.class, new Timestamp.Serializer()); gson.registerTypeAdapter(Timestamp.class, new Timestamp.Deserializer()); addTypeAdapters(gson); return gson.create(); } private void addTypeAdapters(GsonBuilder gson) { gson.registerTypeAdapter(JobStatus.class, new EnumSerializer<JobStatus>()); gson.registerTypeAdapter(RejectedErrorCode.class, new EnumSerializer<RejectedErrorCode>()); } /** * Subscribes to JobExecutionsChanged notifications for a given IoT thing. * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-jobexecutionschanged * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * @param exceptionHandler callback function to invoke if an exception occurred deserializing a message * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToJobExecutionsChangedEvents( JobExecutionsChangedSubscriptionRequest request, QualityOfService qos, Consumer<JobExecutionsChangedEvent> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/jobs/notify"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("JobExecutionsChangedSubscriptionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); JobExecutionsChangedEvent response = gson.fromJson(payload, JobExecutionsChangedEvent.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * Subscribes to JobExecutionsChanged notifications for a given IoT thing. * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-jobexecutionschanged * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToJobExecutionsChangedEvents( JobExecutionsChangedSubscriptionRequest request, QualityOfService qos, Consumer<JobExecutionsChangedEvent> handler) { return SubscribeToJobExecutionsChangedEvents(request, qos, handler, null); } /** * Subscribes to the accepted topic for the StartNextPendingJobExecution operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-startnextpendingjobexecution * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * @param exceptionHandler callback function to invoke if an exception occurred deserializing a message * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToStartNextPendingJobExecutionAccepted( StartNextPendingJobExecutionSubscriptionRequest request, QualityOfService qos, Consumer<StartNextJobExecutionResponse> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/jobs/start-next/accepted"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("StartNextPendingJobExecutionSubscriptionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); StartNextJobExecutionResponse response = gson.fromJson(payload, StartNextJobExecutionResponse.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * Subscribes to the accepted topic for the StartNextPendingJobExecution operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-startnextpendingjobexecution * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToStartNextPendingJobExecutionAccepted( StartNextPendingJobExecutionSubscriptionRequest request, QualityOfService qos, Consumer<StartNextJobExecutionResponse> handler) { return SubscribeToStartNextPendingJobExecutionAccepted(request, qos, handler, null); } /** * Subscribes to the rejected topic for the DescribeJobExecution operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-describejobexecution * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * @param exceptionHandler callback function to invoke if an exception occurred deserializing a message * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToDescribeJobExecutionRejected( DescribeJobExecutionSubscriptionRequest request, QualityOfService qos, Consumer<RejectedError> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/jobs/{jobId}/get/rejected"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("DescribeJobExecutionSubscriptionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); if (request.jobId == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("DescribeJobExecutionSubscriptionRequest must have a non-null jobId")); return result; } topic = topic.replace("{jobId}", request.jobId); Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); RejectedError response = gson.fromJson(payload, RejectedError.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * Subscribes to the rejected topic for the DescribeJobExecution operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-describejobexecution * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToDescribeJobExecutionRejected( DescribeJobExecutionSubscriptionRequest request, QualityOfService qos, Consumer<RejectedError> handler) { return SubscribeToDescribeJobExecutionRejected(request, qos, handler, null); } /** * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-nextjobexecutionchanged * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * @param exceptionHandler callback function to invoke if an exception occurred deserializing a message * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToNextJobExecutionChangedEvents( NextJobExecutionChangedSubscriptionRequest request, QualityOfService qos, Consumer<NextJobExecutionChangedEvent> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/jobs/notify-next"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("NextJobExecutionChangedSubscriptionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); NextJobExecutionChangedEvent response = gson.fromJson(payload, NextJobExecutionChangedEvent.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-nextjobexecutionchanged * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToNextJobExecutionChangedEvents( NextJobExecutionChangedSubscriptionRequest request, QualityOfService qos, Consumer<NextJobExecutionChangedEvent> handler) { return SubscribeToNextJobExecutionChangedEvents(request, qos, handler, null); } /** * Subscribes to the rejected topic for the UpdateJobExecution operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-updatejobexecution * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * @param exceptionHandler callback function to invoke if an exception occurred deserializing a message * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToUpdateJobExecutionRejected( UpdateJobExecutionSubscriptionRequest request, QualityOfService qos, Consumer<RejectedError> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/jobs/{jobId}/update/rejected"; if (request.jobId == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("UpdateJobExecutionSubscriptionRequest must have a non-null jobId")); return result; } topic = topic.replace("{jobId}", request.jobId); if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("UpdateJobExecutionSubscriptionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); RejectedError response = gson.fromJson(payload, RejectedError.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * Subscribes to the rejected topic for the UpdateJobExecution operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-updatejobexecution * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToUpdateJobExecutionRejected( UpdateJobExecutionSubscriptionRequest request, QualityOfService qos, Consumer<RejectedError> handler) { return SubscribeToUpdateJobExecutionRejected(request, qos, handler, null); } /** * Subscribes to the accepted topic for the UpdateJobExecution operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-updatejobexecution * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * @param exceptionHandler callback function to invoke if an exception occurred deserializing a message * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToUpdateJobExecutionAccepted( UpdateJobExecutionSubscriptionRequest request, QualityOfService qos, Consumer<UpdateJobExecutionResponse> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/jobs/{jobId}/update/accepted"; if (request.jobId == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("UpdateJobExecutionSubscriptionRequest must have a non-null jobId")); return result; } topic = topic.replace("{jobId}", request.jobId); if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("UpdateJobExecutionSubscriptionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); UpdateJobExecutionResponse response = gson.fromJson(payload, UpdateJobExecutionResponse.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * Subscribes to the accepted topic for the UpdateJobExecution operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-updatejobexecution * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToUpdateJobExecutionAccepted( UpdateJobExecutionSubscriptionRequest request, QualityOfService qos, Consumer<UpdateJobExecutionResponse> handler) { return SubscribeToUpdateJobExecutionAccepted(request, qos, handler, null); } /** * Updates the status of a job execution. You can optionally create a step timer by setting a value for the stepTimeoutInMinutes property. If you don't update the value of this property by running UpdateJobExecution again, the job execution times out when the step timer expires. * * If the device is offline, the PUBLISH packet will be sent once the connection resumes. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-updatejobexecution * * @param request Message to be serialized and sent * @param qos Quality of Service for delivering this message * @return a future containing the MQTT packet id used to perform the publish operation * * * For QoS 0, completes as soon as the packet is sent. * * For QoS 1, completes when PUBACK is received. * * QoS 2 is not supported by AWS IoT. */ public CompletableFuture<Integer> PublishUpdateJobExecution( UpdateJobExecutionRequest request, QualityOfService qos) { String topic = "$aws/things/{thingName}/jobs/{jobId}/update"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("UpdateJobExecutionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); if (request.jobId == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("UpdateJobExecutionRequest must have a non-null jobId")); return result; } topic = topic.replace("{jobId}", request.jobId); String payloadJson = gson.toJson(request); MqttMessage message = new MqttMessage(topic, payloadJson.getBytes(StandardCharsets.UTF_8)); return connection.publish(message, qos, false); } /** * Subscribes to the accepted topic for the DescribeJobExecution operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-describejobexecution * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * @param exceptionHandler callback function to invoke if an exception occurred deserializing a message * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToDescribeJobExecutionAccepted( DescribeJobExecutionSubscriptionRequest request, QualityOfService qos, Consumer<DescribeJobExecutionResponse> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/jobs/{jobId}/get/accepted"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("DescribeJobExecutionSubscriptionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); if (request.jobId == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("DescribeJobExecutionSubscriptionRequest must have a non-null jobId")); return result; } topic = topic.replace("{jobId}", request.jobId); Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); DescribeJobExecutionResponse response = gson.fromJson(payload, DescribeJobExecutionResponse.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * Subscribes to the accepted topic for the DescribeJobExecution operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-describejobexecution * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToDescribeJobExecutionAccepted( DescribeJobExecutionSubscriptionRequest request, QualityOfService qos, Consumer<DescribeJobExecutionResponse> handler) { return SubscribeToDescribeJobExecutionAccepted(request, qos, handler, null); } /** * Gets the list of all jobs for a thing that are not in a terminal state. * * If the device is offline, the PUBLISH packet will be sent once the connection resumes. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-getpendingjobexecutions * * @param request Message to be serialized and sent * @param qos Quality of Service for delivering this message * @return a future containing the MQTT packet id used to perform the publish operation * * * For QoS 0, completes as soon as the packet is sent. * * For QoS 1, completes when PUBACK is received. * * QoS 2 is not supported by AWS IoT. */ public CompletableFuture<Integer> PublishGetPendingJobExecutions( GetPendingJobExecutionsRequest request, QualityOfService qos) { String topic = "$aws/things/{thingName}/jobs/get"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("GetPendingJobExecutionsRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); String payloadJson = gson.toJson(request); MqttMessage message = new MqttMessage(topic, payloadJson.getBytes(StandardCharsets.UTF_8)); return connection.publish(message, qos, false); } /** * Subscribes to the accepted topic for the GetPendingJobsExecutions operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-getpendingjobexecutions * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * @param exceptionHandler callback function to invoke if an exception occurred deserializing a message * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToGetPendingJobExecutionsAccepted( GetPendingJobExecutionsSubscriptionRequest request, QualityOfService qos, Consumer<GetPendingJobExecutionsResponse> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/jobs/get/accepted"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("GetPendingJobExecutionsSubscriptionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); GetPendingJobExecutionsResponse response = gson.fromJson(payload, GetPendingJobExecutionsResponse.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * Subscribes to the accepted topic for the GetPendingJobsExecutions operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-getpendingjobexecutions * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToGetPendingJobExecutionsAccepted( GetPendingJobExecutionsSubscriptionRequest request, QualityOfService qos, Consumer<GetPendingJobExecutionsResponse> handler) { return SubscribeToGetPendingJobExecutionsAccepted(request, qos, handler, null); } /** * Subscribes to the rejected topic for the StartNextPendingJobExecution operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-startnextpendingjobexecution * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * @param exceptionHandler callback function to invoke if an exception occurred deserializing a message * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToStartNextPendingJobExecutionRejected( StartNextPendingJobExecutionSubscriptionRequest request, QualityOfService qos, Consumer<RejectedError> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/jobs/start-next/rejected"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("StartNextPendingJobExecutionSubscriptionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); RejectedError response = gson.fromJson(payload, RejectedError.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * Subscribes to the rejected topic for the StartNextPendingJobExecution operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-startnextpendingjobexecution * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToStartNextPendingJobExecutionRejected( StartNextPendingJobExecutionSubscriptionRequest request, QualityOfService qos, Consumer<RejectedError> handler) { return SubscribeToStartNextPendingJobExecutionRejected(request, qos, handler, null); } /** * Subscribes to the rejected topic for the GetPendingJobsExecutions operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-getpendingjobexecutions * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * @param exceptionHandler callback function to invoke if an exception occurred deserializing a message * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToGetPendingJobExecutionsRejected( GetPendingJobExecutionsSubscriptionRequest request, QualityOfService qos, Consumer<RejectedError> handler, Consumer<Exception> exceptionHandler) { String topic = "$aws/things/{thingName}/jobs/get/rejected"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("GetPendingJobExecutionsSubscriptionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); Consumer<MqttMessage> messageHandler = (message) -> { try { String payload = new String(message.getPayload(), StandardCharsets.UTF_8); RejectedError response = gson.fromJson(payload, RejectedError.class); handler.accept(response); } catch (Exception e) { if (exceptionHandler != null) { exceptionHandler.accept(e); } } }; return connection.subscribe(topic, qos, messageHandler); } /** * Subscribes to the rejected topic for the GetPendingJobsExecutions operation * * Once subscribed, `handler` is invoked each time a message matching * the `topic` is received. It is possible for such messages to arrive before * the SUBACK is received. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-getpendingjobexecutions * * @param request Subscription request configuration * @param qos Maximum requested QoS that server may use when sending messages to the client. * The server may grant a lower QoS in the SUBACK * @param handler callback function to invoke with messages received on the subscription topic * * @return a future containing the MQTT packet id used to perform the subscribe operation */ public CompletableFuture<Integer> SubscribeToGetPendingJobExecutionsRejected( GetPendingJobExecutionsSubscriptionRequest request, QualityOfService qos, Consumer<RejectedError> handler) { return SubscribeToGetPendingJobExecutionsRejected(request, qos, handler, null); } /** * Gets and starts the next pending job execution for a thing (status IN_PROGRESS or QUEUED). * * If the device is offline, the PUBLISH packet will be sent once the connection resumes. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-startnextpendingjobexecution * * @param request Message to be serialized and sent * @param qos Quality of Service for delivering this message * @return a future containing the MQTT packet id used to perform the publish operation * * * For QoS 0, completes as soon as the packet is sent. * * For QoS 1, completes when PUBACK is received. * * QoS 2 is not supported by AWS IoT. */ public CompletableFuture<Integer> PublishStartNextPendingJobExecution( StartNextPendingJobExecutionRequest request, QualityOfService qos) { String topic = "$aws/things/{thingName}/jobs/start-next"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("StartNextPendingJobExecutionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); String payloadJson = gson.toJson(request); MqttMessage message = new MqttMessage(topic, payloadJson.getBytes(StandardCharsets.UTF_8)); return connection.publish(message, qos, false); } /** * Gets detailed information about a job execution. * * If the device is offline, the PUBLISH packet will be sent once the connection resumes. * * AWS documentation: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-api.html#mqtt-describejobexecution * * @param request Message to be serialized and sent * @param qos Quality of Service for delivering this message * @return a future containing the MQTT packet id used to perform the publish operation * * * For QoS 0, completes as soon as the packet is sent. * * For QoS 1, completes when PUBACK is received. * * QoS 2 is not supported by AWS IoT. */ public CompletableFuture<Integer> PublishDescribeJobExecution( DescribeJobExecutionRequest request, QualityOfService qos) { String topic = "$aws/things/{thingName}/jobs/{jobId}/get"; if (request.thingName == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("DescribeJobExecutionRequest must have a non-null thingName")); return result; } topic = topic.replace("{thingName}", request.thingName); if (request.jobId == null) { CompletableFuture<Integer> result = new CompletableFuture<Integer>(); result.completeExceptionally(new MqttException("DescribeJobExecutionRequest must have a non-null jobId")); return result; } topic = topic.replace("{jobId}", request.jobId); String payloadJson = gson.toJson(request); MqttMessage message = new MqttMessage(topic, payloadJson.getBytes(StandardCharsets.UTF_8)); return connection.publish(message, qos, false); } }
800
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs/model/GetPendingJobExecutionsResponse.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.iot.iotjobs.model; import java.util.List; import software.amazon.awssdk.iot.Timestamp; import software.amazon.awssdk.iot.iotjobs.model.JobExecutionSummary; /** * Response payload to a GetPendingJobExecutions request. * */ public class GetPendingJobExecutionsResponse { /** * A list of JobExecutionSummary objects with status QUEUED. * */ public List<software.amazon.awssdk.iot.iotjobs.model.JobExecutionSummary> queuedJobs; /** * The time when the message was sent. * */ public Timestamp timestamp; /** * A client token used to correlate requests and responses. * */ public String clientToken; /** * A list of JobExecutionSummary objects with status IN_PROGRESS. * */ public List<software.amazon.awssdk.iot.iotjobs.model.JobExecutionSummary> inProgressJobs; }
801
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs/model/DescribeJobExecutionSubscriptionRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.iot.iotjobs.model; /** * Data needed to subscribe to DescribeJobExecution responses. * */ public class DescribeJobExecutionSubscriptionRequest { /** * Name of the IoT Thing that you want to subscribe to DescribeJobExecution response events for. * */ public String thingName; /** * Job ID that you want to subscribe to DescribeJobExecution response events for. * */ public String jobId; }
802
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs/model/JobExecutionData.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.iot.iotjobs.model; import java.util.HashMap; import software.amazon.awssdk.iot.Timestamp; import software.amazon.awssdk.iot.iotjobs.model.JobStatus; /** * Data about a job execution. * */ public class JobExecutionData { /** * The unique identifier you assigned to this job when it was created. * */ public String jobId; /** * The content of the job document. * */ public HashMap<String, Object> jobDocument; /** * The status of the job execution. Can be one of: QUEUED, IN_PROGRESS, FAILED, SUCCEEDED, CANCELED, TIMED_OUT, REJECTED, or REMOVED. * */ public JobStatus status; /** * The version of the job execution. Job execution versions are incremented each time they are updated by a device. * */ public Integer versionNumber; /** * The time when the job execution was enqueued. * */ public Timestamp queuedAt; /** * The name of the thing that is executing the job. * */ public String thingName; /** * A number that identifies a job execution on a device. It can be used later in commands that return or update job execution information. * */ public Long executionNumber; /** * A collection of name-value pairs that describe the status of the job execution. * */ public HashMap<String, String> statusDetails; /** * The time when the job execution started. * */ public Timestamp lastUpdatedAt; /** * The time when the job execution started. * */ public Timestamp startedAt; }
803
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs/model/DescribeJobExecutionRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.iot.iotjobs.model; /** * Data needed to make a DescribeJobExecution request. * */ public class DescribeJobExecutionRequest { /** * Optional. A number that identifies a job execution on a device. If not specified, the latest job execution is returned. * */ public Long executionNumber; /** * The name of the thing associated with the device. * */ public String thingName; /** * Optional. Unless set to false, the response contains the job document. The default is true. * */ public Boolean includeJobDocument; /** * The unique identifier assigned to this job when it was created. Or use $next to return the next pending job execution for a thing (status IN_PROGRESS or QUEUED). In this case, any job executions with status IN_PROGRESS are returned first. Job executions are returned in the order in which they were created. * */ public String jobId; /** * An opaque string used to correlate requests and responses. Enter an arbitrary value here and it is reflected in the response. * */ public String clientToken; }
804
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs/model/StartNextJobExecutionResponse.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.iot.iotjobs.model; import software.amazon.awssdk.iot.Timestamp; import software.amazon.awssdk.iot.iotjobs.model.JobExecutionData; /** * Response payload to a StartNextJobExecution request. * */ public class StartNextJobExecutionResponse { /** * A client token used to correlate requests and responses. * */ public String clientToken; /** * The time when the message was sent to the device. * */ public Timestamp timestamp; /** * Contains data about a job execution. * */ public JobExecutionData execution; }
805
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs/model/StartNextPendingJobExecutionSubscriptionRequest.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.iot.iotjobs.model; /** * Data needed to subscribe to StartNextPendingJobExecution responses. * */ public class StartNextPendingJobExecutionSubscriptionRequest { /** * Name of the IoT Thing that you want to subscribe to StartNextPendingJobExecution response events for. * */ public String thingName; }
806
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs/model/RejectedErrorCode.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.iot.iotjobs.model; /** * A value indicating the kind of error encountered while processing an AWS IoT Jobs request * */ public enum RejectedErrorCode { /** * Enum value is an unknown value */ UNKNOWN_ENUM_VALUE("UNKNOWN_ENUM_VALUE"), /** * The request was sent to a topic in the AWS IoT Jobs namespace that does not map to any API. */ INVALID_TOPIC("InvalidTopic"), /** * An update attempted to change the job execution to a state that is invalid because of the job execution's current state. In this case, the body of the error message also contains the executionState field. */ INVALID_STATE_TRANSITION("InvalidStateTransition"), /** * The JobExecution specified by the request topic does not exist. */ RESOURCE_NOT_FOUND("ResourceNotFound"), /** * The contents of the request were invalid. The message contains details about the error. */ INVALID_REQUEST("InvalidRequest"), /** * The request was throttled. */ REQUEST_THROTTLED("RequestThrottled"), /** * There was an internal error during the processing of the request. */ INTERNAL_ERROR("InternalError"), /** * Occurs when a command to describe a job is performed on a job that is in a terminal state. */ TERMINAL_STATE_REACHED("TerminalStateReached"), /** * The contents of the request could not be interpreted as valid UTF-8-encoded JSON. */ INVALID_JSON("InvalidJson"), /** * The expected version specified in the request does not match the version of the job execution in the AWS IoT Jobs service. In this case, the body of the error message also contains the executionState field. */ VERSION_MISMATCH("VersionMismatch"); private String value; private RejectedErrorCode(String value) { this.value = value; } @Override public String toString() { return value; } /** * Returns The enum associated with the given string or UNKNOWN_ENUM_VALUE * if no enum is found. * @param val The string to use * @return The enum associated with the string or UNKNOWN_ENUM_VALUE */ static RejectedErrorCode fromString(String val) { for (RejectedErrorCode e : RejectedErrorCode.class.getEnumConstants()) { if (e.toString().compareTo(val) == 0) { return e; } } return UNKNOWN_ENUM_VALUE; } }
807
0
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs
Create_ds/aws-iot-device-sdk-java-v2/sdk/src/main/java/software/amazon/awssdk/iot/iotjobs/model/JobExecutionState.java
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. * * This file is generated. */ package software.amazon.awssdk.iot.iotjobs.model; import java.util.HashMap; import software.amazon.awssdk.iot.iotjobs.model.JobStatus; /** * Data about the state of a job execution. * */ public class JobExecutionState { /** * A collection of name-value pairs that describe the status of the job execution. * */ public HashMap<String, String> statusDetails; /** * The version of the job execution. Job execution versions are incremented each time they are updated by a device. * */ public Integer versionNumber; /** * The status of the job execution. Can be one of: QUEUED, IN_PROGRESS, FAILED, SUCCEEDED, CANCELED, TIMED_OUT, REJECTED, or REMOVED. * */ public JobStatus status; }
808
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; }
809
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; }
810
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; }
811
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; }
812
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; }
813
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; }
814
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; } }
815
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; }
816
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; }
817
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; }
818
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; }
819
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; }
820
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; }
821
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; }
822
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); } }
823
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; }
824
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; }
825
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; }
826
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; }
827
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; }
828
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; }
829
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; }
830
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; }
831
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; }
832
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; }
833
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; }
834
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; }
835
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; }
836
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; }
837
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; }
838
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; }
839
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; }
840
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; }
841
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; }
842
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; }
843
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; }
844
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; }
845
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; }
846
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; }
847
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; }
848
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; }
849
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(); } } }
850
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; } }
851
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); } }
852
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); } }
853
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); } }
854
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); } }
855
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); } }
856
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; }
857
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 { }
858
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 { }
859
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; }
860
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; }
861
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; }
862
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; }
863
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; }
864
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; }
865
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 { }
866
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()); } }
867
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); } }
868
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); } }
869
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); } }
870
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; } }
871
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); } }
872
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); } }
873
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); } }
874
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()); } } }
875
0
Create_ds/camel-karavan/karavan-vscode
Create_ds/camel-karavan/karavan-vscode/snippets/camel-main-org.apache.camel.Processor.java
import org.apache.camel.BindToRegistry; import org.apache.camel.Configuration; import org.apache.camel.Exchange; import org.apache.camel.Processor; @Configuration @BindToRegistry("NAME") public class NAME implements Processor { public void process(Exchange exchange) throws Exception { exchange.getIn().setBody("Hello World"); } }
876
0
Create_ds/camel-karavan/karavan-vscode
Create_ds/camel-karavan/karavan-vscode/snippets/spring-boot-org.apache.camel.Processor.java
import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.springframework.stereotype.Component; @Component("NAME") public class NAME implements Processor { public void process(Exchange exchange) throws Exception { exchange.getIn().setBody("Hello World"); } }
877
0
Create_ds/camel-karavan/karavan-vscode
Create_ds/camel-karavan/karavan-vscode/snippets/camel-main-org.apache.camel.AggregationStrategy.java
import org.apache.camel.AggregationStrategy; import org.apache.camel.Configuration; import org.apache.camel.BindToRegistry; import org.apache.camel.Exchange; @Configuration @BindToRegistry("NAME") public class NAME implements AggregationStrategy { @Override public Exchange aggregate(Exchange oldExchange, Exchange newExchange) { if (oldExchange == null) { return newExchange; } String oldBody = oldExchange.getIn().getBody(String.class); String newBody = newExchange.getIn().getBody(String.class); oldExchange.getIn().setBody(oldBody + "+" + newBody); return oldExchange; } }
878
0
Create_ds/camel-karavan/karavan-vscode
Create_ds/camel-karavan/karavan-vscode/snippets/quarkus-org.apache.camel.AggregationStrategy.java
import org.apache.camel.AggregationStrategy ; import org.apache.camel.Exchange; import javax.inject.Named; import javax.inject.Singleton; @Singleton @Named("NAME") public class NAME implements AggregationStrategy { @Override public Exchange aggregate(Exchange oldExchange, Exchange newExchange) { if (oldExchange == null) { return newExchange; } String oldBody = oldExchange.getIn().getBody(String.class); String newBody = newExchange.getIn().getBody(String.class); oldExchange.getIn().setBody(oldBody + "+" + newBody); return oldExchange; } }
879
0
Create_ds/camel-karavan/karavan-vscode
Create_ds/camel-karavan/karavan-vscode/snippets/spring-boot-org.apache.camel.AggregationStrategy.java
import org.apache.camel.AggregationStrategy; import org.apache.camel.Exchange; import org.springframework.stereotype.Component; @Component("NAME") public class NAME implements AggregationStrategy { @Override public Exchange aggregate(Exchange oldExchange, Exchange newExchange) { if (oldExchange == null) { return newExchange; } String oldBody = oldExchange.getIn().getBody(String.class); String newBody = newExchange.getIn().getBody(String.class); oldExchange.getIn().setBody(oldBody + "+" + newBody); return oldExchange; } }
880
0
Create_ds/camel-karavan/karavan-vscode
Create_ds/camel-karavan/karavan-vscode/snippets/quarkus-org.apache.camel.Processor.java
import org.apache.camel.Exchange; import org.apache.camel.Processor; import javax.inject.Named; import javax.inject.Singleton; @Singleton @Named("NAME") public class NAME implements Processor { public void process(Exchange exchange) throws Exception { exchange.getIn().setBody("Hello World"); } }
881
0
Create_ds/camel-karavan/karavan-demo/expose-pod-service
Create_ds/camel-karavan/karavan-demo/expose-pod-service/quarkus/Responseprocessor.java
import org.apache.camel.Exchange; import org.apache.camel.Processor; import javax.inject.Named; import javax.inject.Singleton; import java.lang.String; @Singleton @Named("ResponseProcessor") public class Responseprocessor implements Processor { public void process(Exchange exchange) throws Exception { if(exchange.getIn().getBody(String.class).contains("quit")) { System.out.println("received Quit"); exchange.getOut().setHeader("CamelNettyCloseChannelWhenComplete", true); } else { exchange.getOut().setBody("Hello from Karavan Pod"); } } }
882
0
Create_ds/camel-karavan/karavan-demo/expose-pod-service
Create_ds/camel-karavan/karavan-demo/expose-pod-service/spring/Responseprocessor.java
import org.apache.camel.Exchange; import org.apache.camel.Processor; import javax.inject.Named; import javax.inject.Singleton; import java.lang.String; @Singleton @Named("ResponseProcessor") public class Responseprocessor implements Processor { public void process(Exchange exchange) throws Exception { if(exchange.getIn().getBody(String.class).contains("quit")) { System.out.println("received Quit"); exchange.getOut().setHeader("CamelNettyCloseChannelWhenComplete", true); } else { exchange.getOut().setBody("Hello from Karavan Pod"); } } }
883
0
Create_ds/camel-karavan/karavan-demo/rest-service
Create_ds/camel-karavan/karavan-demo/rest-service/quarkus/GetUserById.java
import org.apache.camel.Exchange; import org.apache.camel.Processor; import javax.inject.Named; import javax.inject.Singleton; @Singleton @Named("GetUserById") public class GetUserById implements Processor { public void process(Exchange exchange) throws Exception { exchange.getOut().setBody("{\"username\":\"Karavan\"" +exchange.getIn().getHeader(Exchange.HTTP_PATH) + "}"); exchange.getOut().setHeader(Exchange.HTTP_RESPONSE_CODE, "200"); } }
884
0
Create_ds/camel-karavan/karavan-demo/rest-service
Create_ds/camel-karavan/karavan-demo/rest-service/quarkus/DeleteUserById.java
import org.apache.camel.Exchange; import org.apache.camel.Processor; import javax.inject.Named; import javax.inject.Singleton; @Singleton @Named("DeleteUserById") public class DeleteUserById implements Processor { public void process(Exchange exchange) throws Exception { exchange.getOut().setHeader(Exchange.HTTP_RESPONSE_CODE, "200"); exchange.getOut().setBody("User Deleted"); } }
885
0
Create_ds/camel-karavan/karavan-demo/rest-service
Create_ds/camel-karavan/karavan-demo/rest-service/quarkus/CreateNewUser.java
import org.apache.camel.Exchange; import org.apache.camel.Processor; import javax.inject.Named; import javax.inject.Singleton; @Singleton @Named("CreateNewUser") public class CreateNewUser implements Processor { public void process(Exchange exchange) throws Exception { exchange.getOut().setHeader(Exchange.HTTP_RESPONSE_CODE, "202"); } }
886
0
Create_ds/camel-karavan/karavan-demo/rest-service
Create_ds/camel-karavan/karavan-demo/rest-service/quarkus/GetAllUsers.java
import org.apache.camel.Exchange; import org.apache.camel.Processor; import javax.inject.Named; import javax.inject.Singleton; @Singleton @Named("GetAllUsers") public class GetAllUsers implements Processor { public void process(Exchange exchange) throws Exception { exchange.getOut().setBody("[{\"username\":\"Karavan1\"},{\"username\":\"Karavan2\"}]"); exchange.getOut().setHeader(Exchange.HTTP_RESPONSE_CODE, "200"); } }
887
0
Create_ds/camel-karavan/karavan-demo
Create_ds/camel-karavan/karavan-demo/aggregator/Aggregator.java
import org.apache.camel.BindToRegistry; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.Exchange; import org.apache.camel.AggregationStrategy; import java.util.ArrayList; @BindToRegistry("aggregator") public class Aggregator implements AggregationStrategy { public Exchange aggregate(Exchange oldExchange, Exchange newExchange) { if (oldExchange == null) { return newExchange; } String oldBody = oldExchange.getIn().getBody(String.class); String newBody = newExchange.getIn().getBody(String.class); oldExchange.getIn().setBody(oldBody + "+" + newBody); return oldExchange; } }
888
0
Create_ds/camel-karavan/karavan-generator/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-generator/src/main/java/org/apache/camel/karavan/generator/KameletGenerator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.camel.karavan.generator; import org.apache.camel.kamelets.catalog.KameletsCatalog; import org.apache.camel.v1.Kamelet; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class KameletGenerator extends AbstractGenerator { public static void generate(String... paths) throws Exception { KameletGenerator g = new KameletGenerator(); for (String path : paths) { g.createKamelets(path + "/kamelets", true); } } public void createKamelets(String folder, boolean singleFile) { clearDirectory(Paths.get(folder).toFile()); KameletsCatalog catalog = new KameletsCatalog(); StringBuilder list = new StringBuilder(); StringBuilder sources = new StringBuilder(); List<Map.Entry<String, Kamelet>> kamelets = new ArrayList<>(catalog.getKamelets().entrySet()); for (int i = 0; i < kamelets.size() ; i++) { Map.Entry<String, Kamelet> k = kamelets.get(i); String name = k.getValue().getMetadata().getName(); list.append(name).append("\n"); if (singleFile) { sources.append(readKamelet(name)).append(i != kamelets.size() - 1 ? "\n---\n": "\n"); } else { saveKamelet(folder, name); } } saveFile(folder, "kamelets.properties", list.toString()); if (singleFile) { saveFile(folder, "kamelets.yaml", sources.toString()); } } public String readKamelet(String name) { String fileName = name + ".kamelet.yaml"; InputStream inputStream = KameletsCatalog.class.getResourceAsStream("/kamelets/" + fileName); return new BufferedReader( new InputStreamReader(inputStream, StandardCharsets.UTF_8)) .lines() .filter(s -> !s.startsWith("#")) .collect(Collectors.joining("\n")); } public void saveKamelet(String folder, String name) { // LOGGER.info("Creating kamelet " + name); String fileName = name + ".kamelet.yaml"; InputStream inputStream = KameletsCatalog.class.getResourceAsStream("/kamelets/" + fileName); try { File targetFile = Paths.get(folder, fileName).toFile(); Files.copy(inputStream, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null){ try { inputStream.close(); } catch (Exception ex){ } } } } void clearDirectory(File directoryToBeDeleted) { File[] allContents = directoryToBeDeleted.listFiles(); if (allContents != null) { for (File file : allContents) { if (!file.getName().endsWith("gitignore")) file.delete(); } } } }
889
0
Create_ds/camel-karavan/karavan-generator/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-generator/src/main/java/org/apache/camel/karavan/generator/CamelDefinitionApiGenerator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.camel.karavan.generator; import io.vertx.core.json.JsonObject; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import static java.util.stream.Collectors.toList; public final class CamelDefinitionApiGenerator extends AbstractGenerator { final static String modelHeader = "karavan-generator/src/main/resources/CamelDefinitionApi.header.ts"; final static String modelFooter = "karavan-generator/src/main/resources/CamelDefinitionApi.footer.ts"; final static String modelTemplate = "karavan-generator/src/main/resources/CamelDefinitionApi.ts"; final static String targetModel = "karavan-core/src/core/api/CamelDefinitionApi.ts"; public static void main(String[] args) throws Exception { CamelDefinitionApiGenerator.generate(); System.exit(0); } public static void generate() throws Exception { CamelDefinitionApiGenerator g = new CamelDefinitionApiGenerator(); g.createCamelDefinitions(); } private void createCamelDefinitions() throws Exception { StringBuilder camelModel = new StringBuilder(); camelModel.append(readFileText(modelHeader)); String camelYamlDSL = getCamelYamlDSL(); JsonObject definitions = new JsonObject(camelYamlDSL).getJsonObject("items").getJsonObject("definitions"); List<String> modelList = getClasses(definitions, "org.apache.camel"); modelList.forEach(classFullName -> { String className = classSimple(classFullName); camelModel.append(" ").append(className).append(",\n"); }); camelModel.append("} from '../model/CamelDefinition';\n"); camelModel.append("import {CamelUtil} from './CamelUtil';\n\n"); camelModel.append("export class CamelDefinitionApi { \n\n"); // generate create functions for Definitions modelList.forEach(classFullName -> { String model = generateModelApi(classFullName, definitions.getJsonObject(classFullName)); camelModel.append(model).append(System.lineSeparator()); }); // generate createStep function Map<String, String> stepNames = getProcessorStepNameMap(); StringBuilder cs = new StringBuilder( " static createStep = (name: string, body: any, clone: boolean = false): CamelElement => {\n" + " const newBody = CamelUtil.camelizeBody(name, body, clone);\n" + " switch (name) { \n" ); getClasses(definitions, "org.apache.camel") .forEach(className -> { String code = String.format(" case '%1$s': return CamelDefinitionApi.create%1$s(newBody);\n", classSimple(className)); cs.append(code); }); cs.append( " default: return new CamelElement('');\n" + " }\n" + " }\n\n"); camelModel.append(cs); // generate createExpression function StringBuilder ce = new StringBuilder( " static createExpression = (name: string, body: any): CamelElement => {\n" + " const newBody = CamelUtil.camelizeBody(name, body, false);\n" + " delete newBody.expressionName;\n" + " delete newBody.dslName;\n" + " switch (name) { \n" ); stepNames.entrySet().stream().filter(e-> e.getKey().endsWith("Expression")).forEach(e -> { String className = e.getKey(); String stepName = e.getValue(); String code = String.format(" case '%1$s': return CamelDefinitionApi.create%1$s(newBody);\n", className); ce.append(code); }); ce.append( " default: return new SimpleExpression(newBody);\n" + " }\n" + " }\n\n"); camelModel.append(ce); // generate createDataFormat function StringBuilder df = new StringBuilder( " static createDataFormat = (name: string, body: any): CamelElement => {\n" + " const newBody = CamelUtil.camelizeBody(name, body, false);\n" + " delete newBody.dataFormatName;\n" + " delete newBody.dslName;\n" + " switch (name) { \n" ); stepNames.entrySet().stream().filter(e-> e.getKey().endsWith("DataFormat")).forEach(e -> { String className = e.getKey(); String stepName = e.getValue(); String code = String.format(" case '%1$s': return CamelDefinitionApi.create%1$s(newBody);\n", className); df.append(code); }); df.append( " default: return new JsonDataFormat(newBody);\n" + " }\n" + " }\n"); camelModel.append(df); camelModel.append(readFileText(modelFooter)); camelModel.append("}\n"); writeFileText(targetModel, camelModel.toString()); } private String generateModelApi(String classFullName, JsonObject obj) { String className = classSimple(classFullName); String stepName = getStepNameForClass(className); Map<String, JsonObject> properties = getClassProperties(stepName, obj); List<String> attrs = new ArrayList<>(); AtomicBoolean hasId = new AtomicBoolean(false); properties.keySet().stream().sorted(getComparator(stepName)).forEach(name -> { JsonObject aValue = properties.get(name); if ("id".equals(name)) { hasId.set(true); } boolean attributeIsArray = isAttributeRefArray(aValue); String attributeArrayClass = getAttributeArrayClass(name, aValue); if (attributeIsArray && name.equals("steps") && ! className.equals("ChoiceDefinition") && ! className.equals("SwitchDefinition") && ! className.equals("KameletDefinition")) { attrs.add(" def.steps = CamelDefinitionApi.createSteps(element?.steps);"); } else if (attributeIsArray && !name.equals("steps") && !attributeArrayClass.equals("string")) { String code = String.format( " def.%1$s = element && element?.%1$s ? element?.%1$s.map((x:any) => CamelDefinitionApi.create%2$s(x)) :[];" , name, attributeArrayClass); attrs.add(code); } else if (isAttributeRef(aValue) && !getAttributeClass(aValue).equals("SagaActionUriDefinition") // SagaActionUriDefinition is exception && !getAttributeClass(aValue).equals("ToDefinition") // exception for ToDefinition (in REST Methods) && !getAttributeClass(aValue).equals("ToDynamicDefinition") // exception for ToDynamicDefinition (in REST Methods) ) { String attributeClass = getAttributeClass(aValue); String template = attributeClass.equals("ExpressionDefinition") ? " def.%1$s = CamelDefinitionApi.create%2$s(element.%1$s); \n" : " if (element?.%1$s !== undefined) { \n" + " def.%1$s = CamelDefinitionApi.create%2$s(element.%1$s); \n" + " }"; String code = String.format(template, name, getAttributeClass(aValue)); attrs.add(code); } else { } }); String stringToRequired = getStringToRequired(obj, className); String s2 = stringToRequired.isEmpty() ? "" : "\n" + stringToRequired; String s3 = attrs.size() > 0 ? "\n" + attrs.stream().collect(Collectors.joining("\n")) : ""; return String.format(readFileText(modelTemplate), className, s2, s3); } private String getStringToRequired(JsonObject obj, String className) { if (className.equals("FromDefinition")) { return " if (element && typeof element === 'string') {\n" + " element = { uri: element};\n" + " }"; } else if (obj.containsKey("oneOf") && obj.containsKey("required")) { List<String> list = obj.getJsonArray("required").getList(); list = list.stream().filter(o -> !o.equals("steps")).collect(toList()); return " if (element && typeof element === 'string') {\n" + " element = {" + list.get(0) + ": element};\n" + " }"; } else { return ""; } } }
890
0
Create_ds/camel-karavan/karavan-generator/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-generator/src/main/java/org/apache/camel/karavan/generator/CamelDefinitionGenerator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.camel.karavan.generator; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import java.util.*; import java.util.stream.Collectors; public final class CamelDefinitionGenerator extends AbstractGenerator { final static String modelHeader = "karavan-generator/src/main/resources/CamelDefinition.header.ts"; final static String modelTemplate = "karavan-generator/src/main/resources/CamelDefinition.ts"; final static String targetModel = "karavan-core/src/core/model/CamelDefinition.ts"; public static void main(String[] args) throws Exception { CamelDefinitionGenerator.generate(); System.exit(0); } public static void generate() throws Exception { CamelDefinitionGenerator g = new CamelDefinitionGenerator(); g.createCamelDefinitions(); } private void createCamelDefinitions() throws Exception { StringBuilder camelModel = new StringBuilder(); camelModel.append(readFileText(modelHeader)); String camelYamlDSL = getCamelYamlDSL(); JsonObject definitions = new JsonObject(camelYamlDSL).getJsonObject("items").getJsonObject("definitions"); // Prepare stepNames map Map<String, String> stepNames = getProcessorStepNameMap(); List<String> modelList = getClasses(definitions, "org.apache.camel"); modelList.forEach(className -> { String model = generateModel(className, definitions.getJsonObject(className), definitions, getDslMetadata()); camelModel.append(model).append(System.lineSeparator()); }); writeFileText(targetModel, camelModel.toString()); } private String generateModel(String classFullName, JsonObject obj, JsonObject definitions, Map<String, JsonObject> dslMetadata) { String className = classSimple(classFullName); String stepName = getStepNameForClass(className); Map<String, JsonObject> properties = getClassProperties(stepName, obj); List<String> required = obj.containsKey("required") ? obj.getJsonArray("required").getList() : List.of(); List<String> attrs = new ArrayList<>(); if (className.endsWith("Definition")) { attrs.add(" stepName?: string = '" + stepName + "'"); } else if (className.endsWith("Expression")) { attrs.add(" expressionName?: string = '" + stepName + "'"); } else if (className.endsWith("DataFormat")) { attrs.add(" dataFormatName?: string = '" + stepName + "'"); } properties.keySet().stream().sorted(getComparator(stepName)).forEach(name -> { JsonObject attributeValue = properties.get(name); boolean req = required.contains(name); String generatedValue = ("id".equals(name) && stepName != null && !"routeConfiguration".equals(stepName)) ? "'" + stepName + "-' + uuidv4().substring(0,4)" : null; String attributeType = getAttributeType(name, attributeValue, req, definitions, generatedValue); String r = req ? "" : "?"; name = name.equals("constructor") ? "_constructor" : name; // exception for YAMLDataFormat if (className.equals("ChoiceDefinition") && name.equals("steps")) { // exception for ChoiceDefinition } else if (className.equals("SwitchDefinition") && name.equals("steps")) { // exception for SwitchDefinition } else if (className.equals("KameletDefinition") && name.equals("steps")) { // exception for KameletDefinition } else if (!Objects.equals(attributeType, "null")) { attrs.add(" " + name + r + ": " + attributeType); } }); String s2 = String.join(";\n", attrs) + ((attrs.isEmpty()) ? "" : ";"); return String.format(readFileText(modelTemplate), className, s2); } private String getAttributeType(String stepName, JsonObject attribute, boolean required, JsonObject definitions, String generatedValue) { if (attribute.containsKey("$ref")) { String classFullName = attribute.getString("$ref"); JsonObject clazz = getDefinition(definitions, classFullName); String oneOfString = (clazz.containsKey("oneOf") && clazz.getJsonArray("oneOf").getJsonObject(0).getString("type").equals("string")) ? " | string" : ""; String className = classSimple(classFullName); if (className.equals("SagaActionUriDefinition")) return "string" + (required ? " = ''" : ""); // exception for SagaActionUriDefinition if (className.equals("ToDefinition")) return "string" + (required ? " = ''" : ""); // exception for ToDefinition (in REST Methods) if (className.equals("ToDynamicDefinition")) return "string" + (required ? " = ''" : ""); // exception for ToDynamicDefinition (in REST Methods) return className + (required ? " = new " + className + "()" : oneOfString); } else if (attribute.containsKey("type") && attribute.getString("type").equals("array")) { JsonObject items = attribute.getJsonObject("items"); if (items.containsKey("$ref") && items.getString("$ref").equals("#/items/definitions/org.apache.camel.model.ProcessorDefinition")) { return "CamelElement[] = []"; } else if (items.containsKey("$ref")) { String className = classSimple(items.getString("$ref")); return className + "[] = []"; } else if (items.containsKey("properties") && items.getJsonObject("properties").containsKey(stepName)) { String className = classSimple(items.getJsonObject("properties").getJsonObject(stepName).getString("$ref")); return className + "[] = []"; } else { return items.getString("type") + "[] = []"; } } else if (attribute.containsKey("type") && attribute.getString("type").equals("object")) { return "any = {}"; } else { String defaultValue = generatedValue != null ? " = " + generatedValue : (required ? " = ''" : ""); return attribute.getString("type") + defaultValue; } } }
891
0
Create_ds/camel-karavan/karavan-generator/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-generator/src/main/java/org/apache/camel/karavan/generator/ElementProp.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.camel.karavan.generator; public class ElementProp { final String name; final String type; final boolean isObject; final boolean isArray; final boolean isArrayTypeClass; final String arrayType; final boolean isProcessor; final String typeCode; public ElementProp(String name, String type, boolean isObject, boolean isArray, boolean isArrayTypeClass, String arrayType, boolean isProcessor, String typeCode) { this.name = name; this.type = type; this.isObject = isObject; this.isArray = isArray; this.isArrayTypeClass = isArrayTypeClass; this.arrayType = arrayType; this.isProcessor = isProcessor; this.typeCode = typeCode; } @Override public String toString() { return "ElementProp{" + "name='" + name + '\'' + ", type='" + type + '\'' + ", isObject=" + isObject + ", isArray=" + isArray + ", isArrayTypeClass=" + isArrayTypeClass + ", arrayType='" + arrayType + '\'' + ", isProcessor=" + isProcessor + ", typeCode='" + typeCode + '\'' + '}'; } }
892
0
Create_ds/camel-karavan/karavan-generator/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-generator/src/main/java/org/apache/camel/karavan/generator/AbstractGenerator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.camel.karavan.generator; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.catalog.CamelCatalog; import org.apache.camel.dsl.yaml.YamlRoutesBuilderLoader; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.*; import java.util.logging.Logger; import java.util.stream.Collectors; public class AbstractGenerator { Logger LOGGER = Logger.getLogger(AbstractGenerator.class.getName()); protected static boolean print = false; protected void print(String line){ if (print) { System.out.println(line); } } protected Vertx vertx = Vertx.vertx(); protected JsonObject getDefinitions(String source) { Buffer buffer = vertx.fileSystem().readFileBlocking(source); return new JsonObject(buffer).getJsonObject("items").getJsonObject("definitions"); } protected JsonObject getDefinitions(){ String camelYamlDSL = getCamelYamlDSL(); return new JsonObject(camelYamlDSL).getJsonObject("items").getJsonObject("definitions"); } protected String getStepNameForClass (String className) { if (className.equals("CatchDefinition")) { className = "doCatch"; } else if (className.equals("ConvertBodyDefinition")) { className = "convertBodyTo"; } else if (className.equals("TryDefinition")) { className = "doTry"; } else if (className.equals("FinallyDefinition")) { className = "doFinally"; } else if (className.equals("ToDynamicDefinition")) { className = "toD"; } else if (className.equals("SamplingDefinition")) { className = "sample"; } else if (className.equals("BeanPropertiesDefinition")) { className = "properties"; } else if (className.endsWith("Definition")) { className = className.substring(0, className.length() - 10); } else if (className.endsWith("DataFormat")){ return getDataFormatStepNameForClass().get(className); } else if (className.endsWith("Expression")){ return getExpressionStepNameForClass().get(className); } return deCapitalize(className); } protected Map<String, String> getDataFormatStepNameForClass(){ Map<String, String> stepNames = new LinkedHashMap<>(); JsonObject definitions = getDefinitions(); JsonObject props = definitions.getJsonObject("org.apache.camel.model.dataformat.DataFormatsDefinition").getJsonObject("properties"); props.getMap().keySet().forEach(key -> { String className = classSimple(props.getJsonObject(key).getString("$ref")); stepNames.put(className, key); }); return stepNames; } protected Map<String, String> getExpressionStepNameForClass(){ Map<String, String> stepNames = new LinkedHashMap<>(); JsonObject definitions = getDefinitions(); JsonArray props = definitions.getJsonObject("org.apache.camel.model.language.ExpressionDefinition").getJsonArray("anyOf").getJsonObject(0).getJsonArray("oneOf"); for (int i =0; i < props.size(); i++) { JsonObject prop = props.getJsonObject(i); String key = prop.getJsonObject("properties").getMap().keySet().iterator().next(); String fullClassName = prop.getJsonObject("properties").getJsonObject(key).getString("$ref"); String className = classSimple(fullClassName); stepNames.put(className, key); } return stepNames; } private Map<String, JsonObject> getJsonObjectProperties (JsonObject val) { Map<String, JsonObject> properties = new LinkedHashMap<>(); val.getMap().keySet().forEach(s -> { JsonObject value = val.getJsonObject(s); if (!value.getMap().isEmpty()) { properties.put(s, val.getJsonObject(s)); } else if (s.equals("expression")){ properties.put(s, JsonObject.of("$ref", "#/items/definitions/org.apache.camel.model.language.ExpressionDefinition")); } }); return properties; } protected Map<String, JsonObject> getClassProperties (String stepName, JsonObject obj) { Map<String, JsonObject> properties = new LinkedHashMap<>(); obj.getMap().keySet().forEach(key -> { if (key.equals("oneOf")) { JsonObject val = obj.getJsonArray("oneOf").getJsonObject(1).getJsonObject("properties"); properties.putAll(getJsonObjectProperties(val)); } else if (key.equals("properties")) { JsonObject val = obj.getJsonObject("properties"); properties.putAll(getJsonObjectProperties(val)); } else if (key.equals("anyOf")) { JsonArray vals = obj.getJsonArray("anyOf").getJsonObject(0).getJsonArray("oneOf"); for (int i = 0; i < vals.size(); i++){ JsonObject data = vals.getJsonObject(i); if (!data.containsKey("not") && data.containsKey("type")) { JsonObject val = data.getJsonObject("properties"); properties.putAll(getJsonObjectProperties(val)); } } } }); return properties; } protected Comparator<String> getComparator(String stepName) { String json = getMetaModel(stepName); if (json != null) { JsonObject props = new JsonObject(json).getJsonObject("properties"); List propsLowerCase = props.getMap().keySet().stream().map(String::toLowerCase).collect(Collectors.toList()); return Comparator.comparing(e -> { if (propsLowerCase.contains(e.toLowerCase())) return propsLowerCase.indexOf(e.toLowerCase()); else return propsLowerCase.size() + 1; }); } return Comparator.comparing(s -> 0); } // protected Map<String, String> getStepNames(){ // // Prepare stepNames map // JsonObject definitions = getDefinitions(); // Map<String, String> stepNames = getProcessorStepName(new JsonObject(getCamelYamlDSL()).getJsonObject("items").getJsonObject("properties")); // stepNames.putAll(getProcessorStepName(definitions.getJsonObject("org.apache.camel.model.ProcessorDefinition").getJsonObject("properties"))); // stepNames.putAll(getProcessorStepName(definitions.getJsonObject("org.apache.camel.model.language.ExpressionDefinition").getJsonObject("properties"))); // stepNames.putAll(getProcessorStepName(definitions.getJsonObject("org.apache.camel.model.language.ExpressionDefinition").getJsonObject("properties"))); // stepNames.putAll(getProcessorStepName(definitions.getJsonObject("org.apache.camel.model.dataformat.DataFormatsDefinition").getJsonObject("properties"))); // return stepNames; // } protected Map<String, JsonObject> getDslMetadata(){ // Generate DSL Metadata String camelYamlDSL = getCamelYamlDSL(); JsonObject definitions = new JsonObject(camelYamlDSL).getJsonObject("items").getJsonObject("definitions"); // Prepare stepNames map Map<String, String> stepNames = getProcessorStepNameMap(); Map<String, JsonObject> classProps = new LinkedHashMap<>(); Map<String, Object> defsMap = new LinkedHashMap<>(); defsMap.putAll(definitions.getJsonObject("org.apache.camel.model.ProcessorDefinition").getJsonObject("properties").getMap()); defsMap.putAll(new JsonObject(camelYamlDSL).getJsonObject("items").getJsonObject("properties").getMap()); classProps.clear(); defsMap.forEach((s, o) -> { String ref = ((Map) o).get("$ref").toString(); String name = classSimple(ref); JsonObject obj = getDefinition(definitions, ref); JsonObject props = obj.containsKey("oneOf") ? obj.getJsonArray("oneOf").getJsonObject(1).getJsonObject("properties") : obj.getJsonObject("properties"); classProps.put(name, props); }); // add additional classes getClasses(definitions, "org.apache.camel.model").forEach(s -> { String className = classSimple(s); if (!stepNames.containsKey(className)) { String stepName = deCapitalize(className.replace("Definition", "")); stepNames.put(className, stepName); } }); definitions.getMap().forEach((s, o) -> { if (s.startsWith("org.apache.camel.model.") && s.endsWith("Definition")) { String name = classSimple(s); JsonObject obj = getDefinition(definitions, s); JsonObject props = obj.containsKey("oneOf") ? obj.getJsonArray("oneOf").getJsonObject(1).getJsonObject("properties") : obj.getJsonObject("properties"); classProps.put(name, props); } }); return classProps; } protected String getCamelYamlDSL() { try { InputStream inputStream = YamlRoutesBuilderLoader.class.getResourceAsStream("/schema/camelYamlDsl.json"); String data = new BufferedReader(new InputStreamReader(inputStream)) .lines().collect(Collectors.joining(System.getProperty("line.separator"))); return data; } catch (Exception e) { return null; } } protected String readFileText(String template) { Buffer templateBuffer = vertx.fileSystem().readFileBlocking(template); return templateBuffer.toString(); } protected void saveFile(String folder, String fileName, String text) { Path path = Paths.get(folder); try { if (!Files.exists(path)) { Files.createDirectories(path); } File targetFile = Paths.get(folder, fileName).toFile(); LOGGER.info("Saving file " + targetFile.getAbsolutePath()); Files.copy(new ByteArrayInputStream(text.getBytes()), targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { e.printStackTrace(); } } protected void writeFileText(String filePath, String data) throws IOException { Files.writeString(Paths.get(filePath), data); } protected JsonObject getProperties(JsonObject definitions, String classname) { JsonObject root = definitions.getJsonObject(classname); JsonObject props = root.getJsonObject("properties"); JsonArray oneOf = root.getJsonArray("oneOf"); if (props != null) { return props; } else { return oneOf.getJsonObject(1).getJsonObject("properties"); } } protected String getPropertyToMapString(JsonObject definitions, String classname) { JsonObject root = definitions.getJsonObject(classname); JsonArray oneOf = root.getJsonArray("oneOf"); JsonArray required = root.getJsonArray("required"); if (oneOf != null && required != null) { return required.getString(0); } return null; } protected String camelize(String name, String separator) { return Arrays.stream(name.split(separator)).map(s -> capitalize(s)).collect(Collectors.joining()); } protected String capitalize(String str) { return str.length() == 0 ? str : str.length() == 1 ? str.toUpperCase() : str.substring(0, 1).toUpperCase() + str.substring(1); } protected String deCapitalize(String str) { return str.length() == 0 ? str : str.length() == 1 ? str.toLowerCase() : str.substring(0, 1).toLowerCase() + str.substring(1); } protected String getMetaModel(String name) { try { InputStream inputStream = CamelCatalog.class.getResourceAsStream("/org/apache/camel/catalog/models/" + name + ".json"); String data = new BufferedReader(new InputStreamReader(inputStream)) .lines().collect(Collectors.joining(System.getProperty("line.separator"))); return data; } catch (Exception e) { return null; } } protected String getMetaDataFormat(String name) { try { InputStream inputStream = RouteBuilder.class.getResourceAsStream("/org/apache/camel/model/dataformat/" + name + ".json"); String data = new BufferedReader(new InputStreamReader(inputStream)) .lines().collect(Collectors.joining(System.getProperty("line.separator"))); return data; } catch (Exception e) { return null; } } protected String getMetaLanguage(String name) { try { InputStream inputStream = RouteBuilder.class.getResourceAsStream("/org/apache/camel/model/language/" + name + ".json"); String data = new BufferedReader(new InputStreamReader(inputStream)) .lines().collect(Collectors.joining(System.getProperty("line.separator"))); return data; } catch (Exception e) { return null; } } protected boolean isAttributeRef(JsonObject attribute) { return attribute.containsKey("$ref"); } protected String getAttributeClass(JsonObject attribute) { return classSimple(attribute.getString("$ref")); } protected String getAttributeArrayClass(String stepName, JsonObject attribute) { if (attribute.containsKey("items")) { JsonObject items = attribute.getJsonObject("items"); if (items.containsKey("$ref")) { return classSimple(items.getString("$ref")); } else if (items.containsKey("properties")) { JsonObject properties = items.getJsonObject("properties"); return classSimple(properties.getJsonObject(stepName).getString("$ref")); } else { return items.getString("type"); } } return "string"; } protected String classSimple(String classFullName) { String[] def = classFullName.split("\\."); return def[def.length - 1]; } protected List<String> getClasses(JsonObject definitions, String filter) { List<String> result = new ArrayList<>(); definitions.getMap().forEach((s, o) -> { if (s.startsWith(filter) && !s.equals("org.apache.camel.dsl.yaml.deserializers.RouteFromDefinitionDeserializer")) { result.add(s); } }); return result; } protected Map<String, String> getProcessorStepNameMapForObject(String key, JsonObject jsonObject) { Map<String, String> result = new LinkedHashMap<>(); jsonObject.fieldNames().forEach(k -> { Object object = jsonObject.getValue(k); if (object instanceof JsonObject) { JsonObject value = jsonObject.getJsonObject(k); result.putAll(getProcessorStepNameMapForObject(k, value)); } else if (object instanceof JsonArray) { JsonArray value = jsonObject.getJsonArray(k); result.putAll(getProcessorStepNameMapForArray(value)); } else if (object instanceof String && k.equals("$ref") && !object.toString().contains(".deserializers.")) { String ref = jsonObject.getString(k); String className = classSimple(ref); result.put(className, key); } }); return result; } protected Map<String, String> getProcessorStepNameMapForArray(JsonArray jsonArray) { Map<String, String> result = new LinkedHashMap<>(); jsonArray.forEach(object -> { if (object instanceof JsonObject) { result.putAll(getProcessorStepNameMapForObject(null, (JsonObject) object)); } else if (object instanceof JsonArray) { result.putAll(getProcessorStepNameMapForArray((JsonArray) object)); } }); return result; } protected Map<String, String> getProcessorStepNameMap() { String camelYamlDSL = getCamelYamlDSL(); JsonObject definitions = new JsonObject(camelYamlDSL); return new LinkedHashMap<>(getProcessorStepNameMapForObject(null, definitions)); } protected Map<String, String> getProcessorDefinitionStepNameMap() { Map<String, String> result = new LinkedHashMap<>(); String camelYamlDSL = getCamelYamlDSL(); JsonObject definitions = new JsonObject(camelYamlDSL); JsonObject properties = definitions .getJsonObject("items") .getJsonObject("definitions") .getJsonObject("org.apache.camel.model.ProcessorDefinition") .getJsonObject("properties"); properties.getMap().forEach((key, o) -> { String ref = ((Map)o).get("$ref").toString(); String className = classSimple(ref); result.put(className, key); }); return result; } protected JsonObject getDefinition(JsonObject definitions, String className) { return definitions.getJsonObject(className.replace("#/items/definitions/", "")); } protected boolean isAttributeRefArray(JsonObject attribute) { return attribute.containsKey("type") && attribute.getString("type").equals("array"); } }
893
0
Create_ds/camel-karavan/karavan-generator/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-generator/src/main/java/org/apache/camel/karavan/generator/CamelMetadataGenerator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.camel.karavan.generator; import io.vertx.core.json.JsonObject; import org.apache.camel.util.SensitiveUtils; import java.util.*; import java.util.stream.Collectors; public final class CamelMetadataGenerator extends AbstractGenerator { final static String modelHeader = "karavan-generator/src/main/resources/CamelMetadata.header.ts"; final static String targetModel = "karavan-core/src/core/model/CamelMetadata.ts"; public static void main(String[] args) throws Exception { CamelMetadataGenerator.generate(); System.exit(0); } public static void generate() throws Exception { CamelMetadataGenerator g = new CamelMetadataGenerator(); g.createCamelDefinitions(); } private void createCamelDefinitions() throws Exception { StringBuilder camelModel = new StringBuilder(); camelModel.append(readFileText(modelHeader)); String camelYamlDSL = getCamelYamlDSL(); JsonObject definitions = new JsonObject(camelYamlDSL).getJsonObject("items").getJsonObject("definitions"); // Generate DataFormats JsonObject dataformats = getProperties(definitions, "org.apache.camel.model.dataformat.DataFormatsDefinition"); camelModel.append("\nexport const DataFormats: [string, string, string][] = [\n"); dataformats.getMap().forEach((name, val) -> { String json = getMetaDataFormat(name); JsonObject model = new JsonObject(json).getJsonObject("model"); String title = model.getString("title"); String description = model.getString("description"); camelModel.append(String.format(" ['%s','%s',\"%s\"],\n", name, title, description)); }); camelModel.append("]\n\n"); // Prepare stepNames map Map<String, String> stepNames = getProcessorStepNameMap(); Map<String, JsonObject> classProps = new LinkedHashMap<>(); // Generate DataFormatMetadata definitions.getMap().forEach((s, o) -> { if (s.startsWith("org.apache.camel.model.dataformat")) { String name = classSimple(s); JsonObject obj = getDefinition(definitions, s); JsonObject props = obj.containsKey("oneOf") ? obj.getJsonArray("oneOf").getJsonObject(1).getJsonObject("properties") : obj.getJsonObject("properties"); classProps.put(name, props); } }); camelModel.append(getMetadataCode("CamelDataFormatMetadata", classProps, stepNames, "dataformat")); // Generate Languages JsonObject expression = getProperties(definitions, "org.apache.camel.model.language.ExpressionDefinition"); camelModel.append("export const Languages: [string, string, string][] = [\n"); expression.getMap().forEach((name, val) -> { String json = getMetaModel(name); JsonObject model = new JsonObject(json).getJsonObject("model"); String title = model.getString("title"); String description = model.getString("description"); camelModel.append(String.format(" ['%s','%s',\"%s\"],\n", name, title, description)); }); camelModel.append("]\n\n"); // Generate LanguageMetadata classProps.clear(); definitions.getMap().forEach((s, o) -> { if (s.startsWith("org.apache.camel.model.language")) { String name = classSimple(s); JsonObject obj = getDefinition(definitions, s); JsonObject props = obj.containsKey("oneOf") ? obj.getJsonArray("oneOf").getJsonObject(1).getJsonObject("properties") : obj.getJsonObject("properties"); classProps.put(name, props); } }); camelModel.append(getMetadataCode("CamelLanguageMetadata", classProps, stepNames, "language")); // Generate DSL Metadata Map<String, Object> defsMap = new LinkedHashMap<>(); defsMap.putAll(definitions.getJsonObject("org.apache.camel.model.ProcessorDefinition").getJsonObject("properties").getMap()); defsMap.putAll(new JsonObject(camelYamlDSL).getJsonObject("items").getJsonObject("properties").getMap()); classProps.clear(); defsMap.forEach((s, o) -> { String ref = ((Map<?, ?>) o).get("$ref").toString(); String name = classSimple(ref); JsonObject obj = getDefinition(definitions, ref); JsonObject props = obj.containsKey("oneOf") ? obj.getJsonArray("oneOf").getJsonObject(1).getJsonObject("properties") : obj.getJsonObject("properties"); classProps.put(name, props); }); // add additional classes getClasses(definitions, "org.apache.camel.model").forEach(s -> { String className = classSimple(s); if (!stepNames.containsKey(className)) { String stepName = deCapitalize(className.replace("Definition", "")); stepNames.put(className, stepName); } }); definitions.getMap().forEach((s, o) -> { if (s.startsWith("org.apache.camel.model.") && s.endsWith("Definition")) { String name = classSimple(s); String stepName = getStepNameForClass(name); JsonObject obj = getDefinition(definitions, s); // JsonObject props = obj.containsKey("oneOf") ? obj.getJsonArray("oneOf").getJsonObject(1).getJsonObject("properties") : obj.getJsonObject("properties"); Map<String, JsonObject> properties = getClassProperties(stepName, obj); classProps.put(name, JsonObject.mapFrom(properties)); } }); camelModel.append(getMetadataCode("CamelModelMetadata", classProps, stepNames, "model")); // add Sensitive keys List<String> sk = new ArrayList(SensitiveUtils.getSensitiveKeys()); camelModel.append("export const SensitiveKeys: string[] = [\n"); for (int i = 0; i < sk.size(); i++) { camelModel.append(" \"").append(sk.get(i)).append("\"").append(i < sk.size() - 1 ? "," : "").append("\n"); } camelModel.append("]"); writeFileText(targetModel, camelModel.toString()); } private String getMetadataCode(String className, Map<String, JsonObject> classProps, Map<String, String> stepNames, String folder) { StringBuilder code = new StringBuilder(); code.append(String.format("export const %s: ElementMeta[] = [\n", className)); classProps.entrySet().stream().filter(entry -> { if (entry.getValue() == null) { // System.out.println(entry.getKey()); return false; } else { return true; } }).forEach(entry -> { String name = entry.getKey(); JsonObject properties = entry.getValue(); String stepName = getStepNameForClass(name); String json = folder.equals("model") ? getMetaModel(stepName) : (folder.equals("language") ? getMetaLanguage(stepName) : getMetaDataFormat(stepName)); if (json != null) { JsonObject model = new JsonObject(json).getJsonObject("model"); JsonObject props = new JsonObject(json).getJsonObject("properties"); List propsLowerCase = props.getMap().keySet().stream().map(s -> s.toLowerCase()).collect(Collectors.toList()); Comparator<String> comparator = Comparator.comparing(e -> { if (propsLowerCase.contains(e.toLowerCase())) return propsLowerCase.indexOf(e.toLowerCase()); else return propsLowerCase.size() + 1; }); String title = model.getString("title"); String description = model.getString("description"); String label = model.getString("label"); code.append(String.format(" new ElementMeta('%s', '%s', '%s', \"%s\", '%s', [\n", stepName, name, title, description, label)); properties.getMap().keySet().stream().sorted(comparator).forEach((pname) -> { Object v = properties.getMap().get(pname); JsonObject p = props.getJsonObject(pname); if ("inheritErrorHandler".equals(pname) && p == null) { } else { PropertyMeta pm = getAttributeType(pname, new JsonObject((Map) v)); String displayName = p != null && p.containsKey("displayName") ? p.getString("displayName") : pname; String desc = p != null && p.containsKey("description") ? p.getString("description") : pname; String en = p != null && p.containsKey("enum") ? p.getString("enum").replace("[", "").replace("]", "") : ""; Boolean required = p != null && p.containsKey("required") ? p.getBoolean("required") : false; Boolean secret = p != null && p.containsKey("secret") ? p.getBoolean("secret") : false; String defaultValue = p != null && p.containsKey("defaultValue") ? p.getString("defaultValue") : ""; defaultValue = defaultValue.length() == 1 && defaultValue.toCharArray()[0] == '\\' ? "\\\\" : defaultValue; String labels = p != null && p.containsKey("label") ? p.getString("label") : ""; String javaType = getJavaType(p); if (name.equals("ProcessDefinition") && pname.equals("ref")) javaType = "org.apache.camel.Processor"; // exception for processor code.append(String.format( " new PropertyMeta('%s', '%s', \"%s\", '%s', '%s', '%s', %b, %b, %b, %b, '%s', '%s'),\n", pname, displayName, desc, pm.type, en, defaultValue, required, secret, pm.isArray, (pm.isArray ? pm.type : pm.isObject), labels, javaType)); } }); code.append(" ]),\n"); } }); code.append("]\n\n"); return code.toString(); } private String getJavaType(JsonObject p) { if (p != null && p.containsKey("type") && p.getString("type").equals("object") && (p.getString("javaType").equals("org.apache.camel.AggregationStrategy") || p.getString("javaType").equals("org.apache.camel.Processor")) ) { String javaName = p.getString("javaType"); try { Class clazz = Class.forName(javaName); if (clazz.isInterface() && clazz.getPackageName().equals("org.apache.camel")) return javaName; } catch (ClassNotFoundException e) { return ""; } } return ""; } private PropertyMeta getAttributeType(String pname, JsonObject attribute) { if (attribute.containsKey("$ref")) { String classFullName = attribute.getString("$ref"); String className = classSimple(classFullName); if (className.equals("SagaActionUriDefinition")) return new PropertyMeta("string", false, false); // exception for SagaActionUriDefinition if (className.equals("ToDefinition")) return new PropertyMeta("string", false, false); // exception for ToDefinition (in REST Methods) if (className.equals("ToDynamicDefinition")) return new PropertyMeta("string", false, false); // exception for ToDynamicDefinition (in REST Methods) return new PropertyMeta(className, false, true); } else if (attribute.containsKey("type") && attribute.getString("type").equals("array")) { JsonObject items = attribute.getJsonObject("items"); if (items.containsKey("properties") && items.getJsonObject("properties").containsKey(pname)) { String t = items.getJsonObject("properties").getJsonObject(pname).getString("$ref"); if (t.equals("#/items/definitions/org.apache.camel.model.ProcessorDefinition")) { return new PropertyMeta("CamelElement", true, true); } else { String className = classSimple(t); return new PropertyMeta(className, true, true); } } else if (items.containsKey("$ref")) { String t = items.getString("$ref"); if (t.equals("#/items/definitions/org.apache.camel.model.ProcessorDefinition")) { return new PropertyMeta("CamelElement", true, true); } else { String className = classSimple(t); return new PropertyMeta(className, true, true); } } else { return new PropertyMeta(items.getString("type"), true, false); } } else if (attribute.containsKey("type") && attribute.getString("type").equals("object")) { return new PropertyMeta(attribute.getString("type"), false, false); } else { return new PropertyMeta(attribute.getString("type"), false, false); } } class PropertyMeta { public String type; public Boolean isArray; public Boolean isObject; public PropertyMeta(String type, Boolean isArray, Boolean isObject) { this.type = type; this.isArray = isArray; this.isObject = isObject; } @Override public String toString() { return "PropertyMeta{" + "type='" + type + '\'' + ", isArray=" + isArray + ", isObject=" + isObject + '}'; } } }
894
0
Create_ds/camel-karavan/karavan-generator/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-generator/src/main/java/org/apache/camel/karavan/generator/CamelDefinitionYamlStepGenerator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.camel.karavan.generator; import io.vertx.core.json.JsonObject; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import static java.util.stream.Collectors.toList; public final class CamelDefinitionYamlStepGenerator extends AbstractGenerator { final static String modelHeader = "karavan-generator/src/main/resources/CamelDefinitionYamlStep.header.ts"; final static String modelFooter = "karavan-generator/src/main/resources/CamelDefinitionYamlStep.footer.ts"; final static String modelTemplate = "karavan-generator/src/main/resources/CamelDefinitionYamlStep.ts"; final static String targetModel = "karavan-core/src/core/api/CamelDefinitionYamlStep.ts"; public static void main(String[] args) throws Exception { CamelDefinitionYamlStepGenerator.generate(); System.exit(0); } public static void generate() throws Exception { CamelDefinitionYamlStepGenerator g = new CamelDefinitionYamlStepGenerator(); g.createCamelDefinitions(); } private void createCamelDefinitions() throws Exception { StringBuilder camelModel = new StringBuilder(); camelModel.append(readFileText(modelHeader)); String camelYamlDSL = getCamelYamlDSL(); JsonObject definitions = new JsonObject(camelYamlDSL).getJsonObject("items").getJsonObject("definitions"); List<String> modelList = getClasses(definitions, "org.apache.camel"); modelList.forEach(classFullName -> { String className = classSimple(classFullName); camelModel.append(" ").append(className).append(",\n"); }); camelModel.append("} from '../model/CamelDefinition';\n"); camelModel.append("import {CamelUtil} from './CamelUtil';\n"); camelModel.append("import {CamelMetadataApi} from '../model/CamelMetadata';\n"); camelModel.append("import {ComponentApi} from './ComponentApi';\n\n"); camelModel.append("export class CamelDefinitionYamlStep { \n\n"); // generate create functions for Definitions modelList.forEach(classFullName -> { String model = generateModelApi(classFullName, definitions.getJsonObject(classFullName)); camelModel.append(model).append(System.lineSeparator()); }); // generate readStep function Map<String, String> stepNames = getProcessorDefinitionStepNameMap(); StringBuilder cs = new StringBuilder( " static readStep = (body: any, clone: boolean = false): CamelElement => {\n" + " const name = Object.getOwnPropertyNames(body)[0];\n" + " const newBody = CamelUtil.camelizeBody(name, body[name], clone);\n" + " switch (name) { \n" ); stepNames.forEach((className, stepName) -> { String code = String.format(" case '%1$s': return CamelDefinitionYamlStep.read%2$s(newBody);\n", stepName, className); cs.append(code); }); cs.append( " default: return new CamelElement('');\n" + " }\n" + " }\n"); camelModel.append(cs); camelModel.append(readFileText(modelFooter)); camelModel.append("}\n"); writeFileText(targetModel, camelModel.toString()); } private String generateModelApi(String classFullName, JsonObject obj) { String className = classSimple(classFullName); String stepName = getStepNameForClass(className); String s1 = getStringToRequired(obj, className); AtomicReference<String> s3 = new AtomicReference<>(""); Map<String, JsonObject> properties = getClassProperties(stepName, obj); Map<String, String> attrs = new HashMap<>(); properties.keySet().stream().sorted(getComparator(stepName)).forEach(aName -> { if (aName.equals("uri")) { s3.set("\n def = ComponentApi.parseElementUri(def);"); } JsonObject aValue = properties.get(aName); boolean attributeIsArray = isAttributeRefArray(aValue); String attributeArrayClass = getAttributeArrayClass(aName, aValue); if (attributeIsArray && aName.equals("steps") && ! className.equals("ChoiceDefinition") && ! className.equals("SwitchDefinition") && ! className.equals("KameletDefinition")) { attrs.put(aName, " def.steps = CamelDefinitionYamlStep.readSteps(element?.steps);\n"); } else if (attributeIsArray && !aName.equals("steps") && !attributeArrayClass.equals("string")) { String format = Arrays.asList("intercept", "interceptFrom", "interceptSendToEndpoint", "onCompletion", "onException").contains(aName) ? " def.%1$s = element && element?.%1$s ? element?.%1$s.map((x:any) => CamelDefinitionYamlStep.read%2$s(x.%1$s)) :[]; \n" : " def.%1$s = element && element?.%1$s ? element?.%1$s.map((x:any) => CamelDefinitionYamlStep.read%2$s(x)) :[]; \n"; String code = String.format(format, aName, attributeArrayClass); attrs.put(aName, code); } else if (isAttributeRef(aValue) && getAttributeClass(aValue).equals("ExpressionDefinition")) { // Expressions implicits String code = String.format( " if (element?.%1$s !== undefined) { \n" + " def.%1$s = CamelDefinitionYamlStep.read%2$s(element.%1$s); \n" + " } else {\n" + " const languageName: string | undefined = Object.keys(element).filter(key => CamelMetadataApi.hasLanguage(key))[0] || undefined;\n" + " if (languageName){\n" + " const exp:any = {};\n" + " exp[languageName] = element[languageName]\n" + " def.%1$s = CamelDefinitionYamlStep.readExpressionDefinition(exp);\n" + " delete (def as any)[languageName];\n" + " }\n" + " }\n" , aName, getAttributeClass(aValue)); attrs.put(aName, code); } else if (isAttributeRef(aValue) && !getAttributeClass(aValue).equals("SagaActionUriDefinition") // SagaActionUriDefinition is exception && !getAttributeClass(aValue).equals("ToDefinition") // exception for ToDefinition (in REST Methods) && !getAttributeClass(aValue).equals("ToDynamicDefinition") // exception for ToDynamicDefinition (in REST Methods) ) { String code = String.format( " if (element?.%1$s !== undefined) { \n" + " if (Array.isArray(element.%1$s)) { \n" + " def.%1$s = CamelDefinitionYamlStep.read%2$s(element.%1$s[0]); \n" + " } else { \n" + " def.%1$s = CamelDefinitionYamlStep.read%2$s(element.%1$s); \n" + " } \n" + " } \n" , aName, getAttributeClass(aValue)); attrs.put(aName, code); } else { } }); return String.format(readFileText(modelTemplate), className, s1, s3, attrs.values().stream().collect(Collectors.joining(""))); } private String getStringToRequired(JsonObject obj, String className) { if (className.equals("FromDefinition")) { return "if (element && typeof element === 'string') element = { uri: element};"; } else if (obj.containsKey("oneOf") && obj.containsKey("required")) { List<String> list = obj.getJsonArray("required").getList(); list = list.stream().filter(o -> !o.equals("steps")).collect(toList()); return "if (element && typeof element === 'string') element = {" + list.get(0) + ": element};"; } else { return ""; } } }
895
0
Create_ds/camel-karavan/karavan-generator/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-generator/src/main/java/org/apache/camel/karavan/generator/CamelComponentsGenerator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.camel.karavan.generator; import io.vertx.core.json.JsonObject; import org.apache.camel.builder.RouteBuilder; import java.io.*; import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; public final class CamelComponentsGenerator extends AbstractGenerator { public static void main(String[] args) throws Exception { CamelComponentsGenerator.generate(); System.exit(0); } public static void generate(String... paths) throws Exception { CamelComponentsGenerator g = new CamelComponentsGenerator(); for (String path : paths) { g.createCreateComponents(path + "/components", true); } } private void createCreateComponents(String path, boolean singleFile) { clearDirectory(Paths.get(path).toFile()); List<String> components = getComponents(); StringBuilder list = new StringBuilder(); StringBuilder sources = new StringBuilder("[\n"); for (int i = 0; i < components.size(); i++) { String name = components.get(i); String json = getComponent(name); JsonObject obj = new JsonObject(json); obj.remove("componentProperties"); if (!obj.getJsonObject("component").getBoolean("deprecated") && !obj.getJsonObject("component").getString("name").equals("kamelet")) { if (singleFile) { sources.append(obj).append( i != components.size() - 1 ? "\n,\n" : "\n"); } else { saveFile(path, name + ".json", obj.toString()); } list.append(name).append("\n"); } } saveFile(path, "components.properties", list.toString()); if (singleFile) { sources.append("]"); saveFile(path, "components.json", sources.toString()); } } public List<String> getComponents() { try { InputStream inputStream = RouteBuilder.class.getResourceAsStream("/org/apache/camel/catalog/components.properties"); List<String> data = new BufferedReader(new InputStreamReader(inputStream)) .lines().collect(Collectors.toList()); return data; } catch (Exception e) { return null; } } public String getComponent(String name) { try { InputStream inputStream = RouteBuilder.class.getResourceAsStream("/org/apache/camel/catalog/components/" + name + ".json"); String data = new BufferedReader(new InputStreamReader(inputStream)) .lines().collect(Collectors.joining(System.getProperty("line.separator"))); return data; } catch (Exception e) { return null; } } void clearDirectory(File directoryToBeDeleted) { File[] allContents = directoryToBeDeleted.listFiles(); if (allContents != null) { for (File file : allContents) { if (!file.getName().endsWith("gitignore")) file.delete(); } } } }
896
0
Create_ds/camel-karavan/karavan-generator/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-generator/src/main/java/org/apache/camel/karavan/generator/KaravanGenerator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.camel.karavan.generator; public final class KaravanGenerator { public static void main(String[] args) throws Exception { String[] paths = new String[] { "karavan-designer/public", "karavan-web/karavan-app/src/main/resources", "karavan-vscode" }; if (args.length > 0) { paths = new String[] {args[0]}; } CamelDefinitionGenerator.generate(); CamelDefinitionApiGenerator.generate(); CamelDefinitionYamlStepGenerator.generate(); CamelMetadataGenerator.generate(); KameletGenerator.generate(paths); CamelComponentsGenerator.generate(paths); System.exit(0); } }
897
0
Create_ds/camel-karavan/karavan-web/karavan-installer/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-installer/src/main/java/org/apache/camel/karavan/installer/ResourceUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.camel.karavan.installer; import io.fabric8.kubernetes.client.utils.Serialization; import org.apache.camel.karavan.installer.resources.*; import java.util.*; public class ResourceUtils { public static String generateResources(KaravanCommand config) { return String.join("", generateResourcesMap(config).values()); } public static Map<String, String> generateResourcesMap(KaravanCommand config) { Map<String, String> result = new HashMap<>(); result.put("sa-karavan", toYAML(KaravanServiceAccount.getServiceAccount(config))); result.put("role-karavan", toYAML(KaravanRole.getRole(config))); result.put("rb-karavan", toYAML(KaravanRole.getRoleBinding(config))); result.put("rb-karavan-view", toYAML(KaravanRole.getRoleBindingView(config))); result.put("deployment", toYAML(KaravanDeployment.getDeployment(config))); result.put("service", toYAML(KaravanService.getService(config))); if (config.isOpenShift()) { result.put("route", toYAML(KaravanService.getRoute(config))); } return result; } public static String toYAML(Object resource) { try { return Serialization.yamlMapper().writeValueAsString(resource); } catch (Exception e) { System.out.println(e.getMessage()); return null; } } public static Map<String, String> getLabels(String name, String version, Map<String, String> labels) { Map<String, String> result = new HashMap<>(Map.of( "app", name, "app.kubernetes.io/name", name, "app.kubernetes.io/version", version, "app.kubernetes.io/part-of", Constants.NAME )); result.putAll(labels); return result; } }
898
0
Create_ds/camel-karavan/karavan-web/karavan-installer/src/main/java/org/apache/camel/karavan
Create_ds/camel-karavan/karavan-web/karavan-installer/src/main/java/org/apache/camel/karavan/installer/KaravanCommand.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.camel.karavan.installer; import picocli.CommandLine; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.concurrent.Callable; @CommandLine.Command(name = "install", mixinStandardHelpOptions = true, description = "Karavan Installer") public class KaravanCommand implements Callable<Integer> { @CommandLine.Option(names = {"-v", "--version"}, required = true, description = "Karavan version", defaultValue = "4.1.1") private String version; @CommandLine.Option(names = {"-n", "--namespace"}, description = "Namespace", defaultValue = Constants.DEFAULT_NAMESPACE) private String namespace; @CommandLine.Option(names = {"-e", "--environment"}, description = "Environment", defaultValue = Constants.DEFAULT_ENVIRONMENT) private String environment; @CommandLine.Option(names = {"--auth"}, description = "Authentication: public, basic, oidc", defaultValue = Constants.DEFAULT_AUTH) private String auth; @CommandLine.Option(names = {"--node-port"}, description = "Node port", defaultValue = "0") private int nodePort; @CommandLine.Option(names = {"--image"}, description = "Karavan Image", defaultValue = Constants.KARAVAN_IMAGE) private String baseImage; @CommandLine.Option(names = {"--devmode-image"}, description = "Karavan DevMode Image", defaultValue = Constants.DEFAULT_DEVMODE_IMAGE) private String devmodeImage; @CommandLine.Option(names = {"--file"}, description = "YAML file name", defaultValue = "karavan.yaml") private String file; @CommandLine.Option(names = {"--yaml"}, description = "Create YAML file. Do not apply") private boolean yaml; @CommandLine.Option(names = {"--openshift"}, description = "Create files for OpenShift") private boolean isOpenShift; @CommandLine.Option(names = {"--master-password"}, description = "Master password", defaultValue = "karavan") private String masterPassword; @CommandLine.Option(names = {"--oidc-secret"}, description = "OIDC secret") private String oidcSecret; @CommandLine.Option(names = {"--oidc-server-url"}, description = "OIDC server URL") private String oidcServerUrl; @CommandLine.Option(names = {"--oidc-frontend-url"}, description = "OIDC frontend URL") private String oidcFrontendUrl; @CommandLine.Option(names = {"--git-repository"}, description = "Git repository", defaultValue = Constants.DEFAULT_GIT_REPOSITORY) private String gitRepository; @CommandLine.Option(names = {"--git-username"}, description = "Git username", defaultValue = Constants.DEFAULT_GIT_USERNAME) private String gitUsername; @CommandLine.Option(names = {"--git-password"}, description = "Git password", defaultValue = Constants.DEFAULT_GIT_PASSWORD) private String gitPassword; @CommandLine.Option(names = {"--git-branch"}, description = "Git branch", defaultValue = Constants.DEFAULT_GIT_BRANCH) private String gitBranch; @CommandLine.Option(names = {"--image-registry"}, description = "Image registry") private String imageRegistry; @CommandLine.Option(names = {"--image-group"}, description = "Image group", defaultValue = "karavan") private String imageGroup; @CommandLine.Option(names = {"--image-registry-username"}, description = "Image registry username") private String imageRegistryUsername; @CommandLine.Option(names = {"--image-registry-password"}, description = "Image registry password") private String imageRegistryPassword; @CommandLine.Option(names = {"--infinispan-image"}, description = "Infinispan Image", defaultValue = Constants.INFINISPAN_IMAGE) private String infinispanImage; @CommandLine.Option(names = {"--infinispan-username"}, description = "Infinispan Username", defaultValue = Constants.INFINISPAN_USERNAME) private String infinispanUsername; @CommandLine.Option(names = {"--infinispan-password"}, description = "Infinispan Password", defaultValue = Constants.INFINISPAN_PASSWORD) private String infinispanPassword; @CommandLine.Option(names = {"--nexus-proxy"}, description = "Deploy nexus proxy") private boolean nexusProxy; @CommandLine.Option(names = {"--install-gitea"}, description = "Install Gitea (for demo purposes)", defaultValue = "false") private boolean installGitea; @CommandLine.Option(names = {"--install-infinispan"}, description = "Install Infinispan", defaultValue = "true") private boolean installInfinispan; @CommandLine.Option(names = {"-h", "--help"}, usageHelp = true, description = "Display help") private boolean helpRequested; private Map<String, String> labels = new HashMap<>(); public static void main(String... args) { CommandLine commandLine = new CommandLine(new KaravanCommand()); commandLine.parseArgs(args); if (commandLine.isUsageHelpRequested()) { commandLine.usage(System.out); System.exit(0); } int exitCode = commandLine.execute(args); System.exit(exitCode); } @Override public Integer call() throws Exception { if (yaml) { System.out.println("⭕ Preparing Karavan resources YAML"); Files.writeString(Path.of(file), ResourceUtils.generateResources(this)); System.out.println("\uD83D\uDC4D Prepared Karavan resources YAML " + file); } else { CommandUtils.installKaravan(this); } return 0; } public boolean gitConfigured() { return installGitea || (gitRepository != null && !Constants.DEFAULT_GIT_PASSWORD.equals(gitPassword) && gitUsername !=null && gitBranch !=null ); } public boolean oidcConfigured() { return oidcSecret != null && oidcServerUrl != null && oidcFrontendUrl != null; } public boolean isInstallGitea() { return installGitea; } public boolean isInstallInfinispan() { return installInfinispan; } public boolean isAuthOidc() { return Objects.equals(this.auth, "oidc"); } public boolean isAuthBasic() { return Objects.equals(this.auth, "basic"); } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } public String getEnvironment() { return environment; } public void setEnvironment(String environment) { this.environment = environment; } public String getAuth() { return auth; } public void setAuth(String auth) { this.auth = auth; } public int getNodePort() { return nodePort; } public void setNodePort(int nodePort) { this.nodePort = nodePort; } public String getBaseImage() { return baseImage; } public void setBaseImage(String baseImage) { this.baseImage = baseImage; } public String getDevmodeImage() { return devmodeImage; } public void setDevmodeImage(String devmodeImage) { this.devmodeImage = devmodeImage; } public String getFile() { return file; } public void setFile(String file) { this.file = file; } public boolean isYaml() { return yaml; } public void setYaml(boolean yaml) { this.yaml = yaml; } public boolean isOpenShift() { return isOpenShift; } public void setOpenShift(boolean openShift) { isOpenShift = openShift; } public String getMasterPassword() { return masterPassword; } public void setMasterPassword(String masterPassword) { this.masterPassword = masterPassword; } public String getOidcSecret() { return oidcSecret; } public void setOidcSecret(String oidcSecret) { this.oidcSecret = oidcSecret; } public String getOidcServerUrl() { return oidcServerUrl; } public void setOidcServerUrl(String oidcServerUrl) { this.oidcServerUrl = oidcServerUrl; } public String getOidcFrontendUrl() { return oidcFrontendUrl; } public void setOidcFrontendUrl(String oidcFrontendUrl) { this.oidcFrontendUrl = oidcFrontendUrl; } public String getGitRepository() { return gitRepository; } public void setGitRepository(String gitRepository) { this.gitRepository = gitRepository; } public String getGitUsername() { return gitUsername; } public void setGitUsername(String gitUsername) { this.gitUsername = gitUsername; } public String getGitPassword() { return gitPassword; } public void setGitPassword(String gitPassword) { this.gitPassword = gitPassword; } public String getGitBranch() { return gitBranch; } public void setGitBranch(String gitBranch) { this.gitBranch = gitBranch; } public String getImageRegistry() { return imageRegistry; } public void setImageRegistry(String imageRegistry) { this.imageRegistry = imageRegistry; } public String getImageGroup() { return imageGroup; } public void setImageGroup(String imageGroup) { this.imageGroup = imageGroup; } public String getImageRegistryUsername() { return imageRegistryUsername; } public void setImageRegistryUsername(String imageRegistryUsername) { this.imageRegistryUsername = imageRegistryUsername; } public String getImageRegistryPassword() { return imageRegistryPassword; } public void setImageRegistryPassword(String imageRegistryPassword) { this.imageRegistryPassword = imageRegistryPassword; } public String getInfinispanImage() { return infinispanImage; } public void setInfinispanImage(String infinispanImage) { this.infinispanImage = infinispanImage; } public String getInfinispanUsername() { return infinispanUsername; } public void setInfinispanUsername(String infinispanUsername) { this.infinispanUsername = infinispanUsername; } public String getInfinispanPassword() { return infinispanPassword; } public void setInfinispanPassword(String infinispanPassword) { this.infinispanPassword = infinispanPassword; } public boolean isNexusProxy() { return nexusProxy; } public void setNexusProxy(boolean nexusProxy) { this.nexusProxy = nexusProxy; } public boolean isHelpRequested() { return helpRequested; } public void setHelpRequested(boolean helpRequested) { this.helpRequested = helpRequested; } public Map<String, String> getLabels() { return labels; } public void setLabels(Map<String, String> labels) { this.labels = labels; } }
899