AWS IoT FleetWise exemples d'utilisation du SDK pour Java 2.x - AWS SDK for Java 2.x

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

AWS IoT FleetWise exemples d'utilisation du SDK pour Java 2.x

Les exemples de code suivants vous montrent comment effectuer des actions et implémenter des scénarios courants à l'aide du AWS SDK for Java 2.x with AWS IoT FleetWise.

Les principes de base sont des exemples de code qui vous montrent comment effectuer les opérations essentielles au sein d’un service.

Les actions sont des extraits de code de programmes plus larges et doivent être exécutées dans leur contexte. Alors que les actions vous indiquent comment appeler des fonctions de service individuelles, vous pouvez les voir en contexte dans leurs scénarios associés.

Chaque exemple inclut un lien vers le code source complet, où vous trouverez des instructions sur la façon de configurer et d'exécuter le code en contexte.

Mise en route

Les exemples de code suivants montrent comment démarrer avec AWS IoT FleetWise.

SDK pour Java 2.x
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

public class HelloFleetwise { public static void main(String[] args) { ListSignalCatalogs(); } public static void ListSignalCatalogs() { try (IoTFleetWiseClient fleetWiseClient = IoTFleetWiseClient.builder() .region(Region.US_EAST_1) .credentialsProvider(DefaultCredentialsProvider.create()) .build()) { ListSignalCatalogsRequest request = ListSignalCatalogsRequest.builder() .maxResults(10) // Optional: limit per page .build(); ListSignalCatalogsIterable paginator = fleetWiseClient.listSignalCatalogsPaginator(request); boolean found = false; for (ListSignalCatalogsResponse response : paginator) { for (SignalCatalogSummary summary : response.summaries()) { found = true; System.out.println("Catalog Name: " + summary.name()); System.out.println("ARN: " + summary.arn()); System.out.println("Created: " + summary.creationTime()); System.out.println("Last Modified: " + summary.lastModificationTime()); System.out.println("---------------"); } } if (!found) { System.out.println("No AWS Fleetwise Signal Catalogs were found."); } } catch (IoTFleetWiseException e) { System.err.println("Error listing signal catalogs: " + e.awsErrorDetails().errorMessage()); throw new RuntimeException(e); } } }

Principes de base

L’exemple de code suivant illustre comment :

  • Créez un ensemble de signaux standardisés.

  • Créez une flotte représentant un groupe de véhicules.

  • Créez un modèle de manifeste.

  • Créez un manifeste du décodeur.

  • Vérifiez l'état du manifeste du modèle.

  • Vérifiez l'état du décodeur.

  • Créez un objet IoT.

  • Créez un véhicule.

  • Afficher les détails du véhicule.

  • Supprimez les AWS IoT FleetWise actifs.

SDK pour Java 2.x
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

Exécutez un scénario interactif illustrant AWS IoT SiteWise les fonctionnalités.

public class FleetwiseScenario { public static final String DASHES = new String(new char[80]).replace("\0", "-"); static FleetwiseActions actions = new FleetwiseActions(); private static final Logger logger = LoggerFactory.getLogger(FleetwiseScenario.class); static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { final String usage = """ Usage: <signalCatalogName> <manifestName> <fleetId> <vecName> <decName> Where: signalCatalogName - The name of the Signal Catalog to create (eg, catalog30). manifestName - The name of the Vehicle Model (Model Manifest) to create (eg, manifest30). fleetId - The ID of the Fleet to create (eg, fleet30). vecName - The name of the Vehicle to create (eg, vehicle30). decName - The name of the Decoder Manifest to create (eg, decManifest30). """; if (args.length != 5) { logger.info(usage); return; } String signalCatalogName = args[0]; String manifestName = args[1]; String fleetId = args[2]; String vecName = args[3]; String decName = args[4]; logger.info( """ AWS IoT FleetWise is a managed service that simplifies the process of collecting, organizing, and transmitting vehicle data to the cloud in near real-time. Designed for automakers and fleet operators, it allows you to define vehicle models, specify the exact data you want to collect (such as engine temperature, speed, or battery status), and send this data to AWS for analysis. By using intelligent data collection techniques, IoT FleetWise reduces the volume of data transmitted by filtering and transforming it at the edge, helping to minimize bandwidth usage and costs. At its core, AWS IoT FleetWise helps organizations build scalable systems for vehicle data management and analytics, supporting a wide variety of vehicles and sensor configurations. You can define signal catalogs and decoder manifests that describe how raw CAN bus signals are translated into readable data, making the platform highly flexible and extensible. This allows manufacturers to optimize vehicle performance, improve safety, and reduce maintenance costs by gaining real-time visibility into fleet operations. """); waitForInputToContinue(scanner); logger.info(DASHES); try { runScenario(signalCatalogName, manifestName, fleetId, vecName, decName); } catch (RuntimeException e) { logger.info(e.getMessage()); } } private static void runScenario(String signalCatalogName, String manifestName, String fleetId, String vecName, String decName) { logger.info(DASHES); logger.info("1. Creates a collection of standardized signals that can be reused to create vehicle models"); String signalCatalogArn; try { signalCatalogArn = actions.createSignalCatalogAsync(signalCatalogName).join(); logger.info("The collection ARN is " + signalCatalogArn); } catch (CompletionException ce) { Throwable cause = ce.getCause(); if (cause instanceof ValidationException) { logger.error("The request failed due to a validation issue: {}", cause.getMessage()); } else { logger.error("An unexpected error occurred.", cause); } return; } waitForInputToContinue(scanner); logger.info(DASHES); logger.info(DASHES); logger.info("2. Create a fleet that represents a group of vehicles"); logger.info( """ Creating an IoT FleetWise fleet allows you to efficiently collect, organize, and transfer vehicle data to the cloud, enabling real-time insights into vehicle performance and health. It helps reduce data costs by allowing you to filter and prioritize only the most relevant vehicle signals, supporting advanced analytics and predictive maintenance use cases. """); waitForInputToContinue(scanner); String fleetid; try { fleetid = actions.createFleetAsync(signalCatalogArn, fleetId).join(); logger.info("The fleet Id is " + fleetid); } catch (CompletionException ce) { Throwable cause = ce.getCause(); if (cause instanceof ResourceNotFoundException) { logger.error("The resource was not found: {}", cause.getMessage()); } else { logger.error("An unexpected error occurred.", cause); } return; } waitForInputToContinue(scanner); logger.info(DASHES); logger.info(DASHES); logger.info("3. Create a model manifest"); logger.info( """ An AWS IoT FleetWise manifest defines the structure and relationships of vehicle data. The model manifest specifies which signals to collect and how they relate to vehicle systems, while the decoder manifest defines how to decode raw vehicle data into meaningful signals. """); waitForInputToContinue(scanner); String manifestArn; try { List<Node> nodes = actions.listSignalCatalogNodeAsync(signalCatalogName).join(); manifestArn = actions.createModelManifestAsync(manifestName, signalCatalogArn, nodes).join(); logger.info("The manifest ARN is {}", manifestArn); } catch (CompletionException ce) { Throwable cause = ce.getCause(); logger.error("An unexpected error occurred.", cause); return; } waitForInputToContinue(scanner); logger.info(DASHES); logger.info(DASHES); logger.info("4. Create a decoder manifest"); logger.info( """ A decoder manifest in AWS IoT FleetWise defines how raw vehicle data (such as CAN signals) should be interpreted and decoded into meaningful signals. It acts as a translation layer that maps vehicle-specific protocols to standardized data formats using decoding rules. This is crucial for extracting usable data from different vehicle models, even when their data formats vary. """); waitForInputToContinue(scanner); String decArn; try { decArn = actions.createDecoderManifestAsync(decName, manifestArn).join(); logger.info("The decoder manifest ARN is {}", decArn); } catch (CompletionException ce) { Throwable cause = ce.getCause(); logger.error("An unexpected error occurred.", cause); return; } waitForInputToContinue(scanner); logger.info(DASHES); logger.info("5. Check the status of the model manifest"); logger.info( """ The model manifest must be in an ACTIVE state before it can be used to create or update a vehicle. """); waitForInputToContinue(scanner); try { actions.updateModelManifestAsync(manifestName); actions.waitForModelManifestActiveAsync(manifestName).join(); } catch (CompletionException ce) { Throwable cause = ce.getCause(); logger.error("An unexpected error occurred while waiting for the model manifest status.", cause); return; } waitForInputToContinue(scanner); logger.info(DASHES); logger.info("6. Check the status of the decoder"); logger.info( """ The decoder manifest must be in an ACTIVE state before it can be used to create or update a vehicle. """); waitForInputToContinue(scanner); try { actions.updateDecoderManifestAsync(decName); actions.waitForDecoderManifestActiveAsync(decName).join(); } catch (CompletionException ce) { Throwable cause = ce.getCause(); logger.error("An unexpected error occurred while waiting for the decoder manifest status.", cause); return; } waitForInputToContinue(scanner); logger.info(DASHES); logger.info(DASHES); logger.info("7. Create an IoT Thing"); logger.info( """ AWS IoT FleetWise expects an existing AWS IoT Thing with the same name as the vehicle name you are passing to createVehicle method. Before calling createVehicle(), you must create an AWS IoT Thing with the same name using the AWS IoT Core service. """); waitForInputToContinue(scanner); try { actions.createThingIfNotExistsAsync(vecName).join(); } catch (CompletionException ce) { Throwable cause = ce.getCause(); if (cause instanceof ResourceAlreadyExistsException) { logger.error("The resource exists: {}", cause.getMessage()); } else { logger.error("An unexpected error occurred.", cause); return; } } waitForInputToContinue(scanner); logger.info(DASHES); logger.info(DASHES); logger.info("8. Create a vehicle"); logger.info( """ Creating a vehicle in AWS IoT FleetWise allows you to digitally represent and manage a physical vehicle within the AWS ecosystem. This enables efficient ingestion, transformation, and transmission of vehicle telemetry data to the cloud for analysis. """); waitForInputToContinue(scanner); try { actions.createVehicleAsync(vecName, manifestArn, decArn).join(); } catch (CompletionException ce) { Throwable cause = ce.getCause(); if (cause instanceof ResourceNotFoundException) { logger.error("The required resource was not found: {}", cause.getMessage()); } else { logger.error("An unexpected error occurred while creating vehicle.", cause); } } waitForInputToContinue(scanner); logger.info(DASHES); logger.info(DASHES); logger.info("9. Display vehicle details"); waitForInputToContinue(scanner); try { actions.getVehicleDetailsAsync(vecName).join(); } catch (CompletionException ce) { Throwable cause = ce.getCause(); if (cause instanceof ResourceNotFoundException) { logger.error("The resource was not found: {}", cause.getMessage()); } else { logger.error("An unexpected error occurred.", cause); } return; } waitForInputToContinue(scanner); logger.info(DASHES); logger.info(DASHES); logger.info("10. Delete the AWS IoT Fleetwise Assets"); logger.info("Would you like to delete the IoT Fleetwise Assets? (y/n)"); String delAns = scanner.nextLine().trim(); if (delAns.equalsIgnoreCase("y")) { try { actions.deleteVehicleAsync(vecName).join(); actions.deleteDecoderManifestAsync(decName).join(); actions.deleteModelManifestAsync(manifestName).join(); actions.deleteFleetAsync(fleetid).join(); actions.deleteSignalCatalogAsync(signalCatalogName).join(); } catch (CompletionException ce) { Throwable cause = ce.getCause(); if (cause instanceof ResourceNotFoundException) { // Handle the case where the resource is not found. logger.error("The resource was not found: {}", cause.getMessage()); } else if (cause instanceof RuntimeException) { // Handle other runtime exceptions. logger.error("An unexpected error occurred: {}", cause.getMessage()); } else { // Catch any other unexpected exceptions. logger.error("An unknown error occurred.", cause); } return; } logger.info(DASHES); logger.info( """ Thank you for checking out the AWS IoT Fleetwise Service Use demo. We hope you learned something new, or got some inspiration for your own apps today. For more AWS code examples, have a look at: https://docs.aws.amazon.com/code-library/latest/ug/what-is-code-library.html """); logger.info(DASHES); } else { logger.info("The AWS resources will not be deleted."); } } private static void waitForInputToContinue(Scanner scanner) { while (true) { logger.info(""); logger.info("Enter 'c' followed by <ENTER> to continue:"); String input = scanner.nextLine(); if (input.trim().equalsIgnoreCase("c")) { logger.info("Continuing with the program..."); logger.info(""); break; } else { logger.info("Invalid input. Please try again."); } } } }

Une classe wrapper pour les méthodes du AWS IoT FleetWise SDK.

public class FleetwiseActions { private static final Logger logger = LoggerFactory.getLogger(FleetwiseActions.class); private static IoTFleetWiseAsyncClient ioTFleetWiseAsyncClient; private static IoTFleetWiseAsyncClient getAsyncClient() { if (ioTFleetWiseAsyncClient == null) { SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder() .maxConcurrency(100) .connectionTimeout(Duration.ofSeconds(60)) .readTimeout(Duration.ofSeconds(60)) .writeTimeout(Duration.ofSeconds(60)) .build(); ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder() .apiCallTimeout(Duration.ofMinutes(2)) .apiCallAttemptTimeout(Duration.ofSeconds(90)) .retryStrategy(RetryMode.STANDARD) .build(); ioTFleetWiseAsyncClient = IoTFleetWiseAsyncClient.builder() .httpClient(httpClient) .overrideConfiguration(overrideConfig) .build(); } return ioTFleetWiseAsyncClient; } /** * Creates a signal catalog. * * @param signalCatalogName the name of the signal catalog to be created * @return a {@link CompletableFuture} that completes with the Amazon Resource Name (ARN) of the created signal catalog */ public CompletableFuture<String> createSignalCatalogAsync(String signalCatalogName) { return deleteSignalCatalogIfExistsAsync(signalCatalogName) .thenCompose(ignored -> delayAsync(2000)) // Wait for 2 seconds .thenCompose(ignored -> { List<Node> nodes = List.of( Node.builder().branch( Branch.builder() .fullyQualifiedName("Vehicle") .description("Root branch") .build() ).build(), Node.builder().branch( Branch.builder() .fullyQualifiedName("Vehicle.Powertrain") .description("Powertrain branch") .build() ).build(), Node.builder().sensor( Sensor.builder() .fullyQualifiedName("Vehicle.Powertrain.EngineRPM") .description("Engine RPM") .dataType(NodeDataType.DOUBLE) .unit("rpm") .build() ).build(), Node.builder().sensor( Sensor.builder() .fullyQualifiedName("Vehicle.Powertrain.VehicleSpeed") .description("Vehicle Speed") .dataType(NodeDataType.DOUBLE) .unit("km/h") .build() ).build() ); CreateSignalCatalogRequest request = CreateSignalCatalogRequest.builder() .name(signalCatalogName) .nodes(nodes) .build(); CompletableFuture<String> result = new CompletableFuture<>(); getAsyncClient().createSignalCatalog(request) .whenComplete((response, exception) -> { if (exception != null) { Throwable cause = exception.getCause() != null ? exception.getCause() : exception; if (cause instanceof ValidationException) { result.completeExceptionally(cause); } else { result.completeExceptionally(new RuntimeException("Error creating the catalog", cause)); } } else { result.complete(response.arn()); } }); return result; }); } /** * Delays the execution of the current thread asynchronously for the specified duration. * * @param millis the duration of the delay in milliseconds * @return a {@link CompletableFuture} that completes after the specified delay */ private static CompletableFuture<Void> delayAsync(long millis) { return CompletableFuture.runAsync(() -> { try { Thread.sleep(millis); } catch (InterruptedException e) { throw new CompletionException("Sleep interrupted", e); } }); } /** * Deletes the specified signal catalog. * * @param signalCatalogName the name of the signal catalog to delete * @return a {@link CompletableFuture} representing the asynchronous operation. */ public static CompletableFuture<Void> deleteSignalCatalogIfExistsAsync(String signalCatalogName) { DeleteSignalCatalogRequest request = DeleteSignalCatalogRequest.builder() .name(signalCatalogName) .build(); return getAsyncClient().deleteSignalCatalog(request) .handle((response, exception) -> { if (exception != null) { Throwable cause = exception.getCause() != null ? exception.getCause() : exception; if (cause instanceof ResourceNotFoundException) { throw new CompletionException(new RuntimeException("Signal Catalog not found: " + signalCatalogName)); } throw new RuntimeException("Failed to delete signal catalog: " + signalCatalogName, cause); } return null; }); } /** * Creates a new decoder manifest. * * @param name the name of the decoder manifest * @param modelManifestArn the ARN of the model manifest * @return a {@link CompletableFuture} that completes with the ARN of the created decoder manifest */ public CompletableFuture<String> createDecoderManifestAsync(String name, String modelManifestArn) { String interfaceId = "can0"; NetworkInterface networkInterface = NetworkInterface.builder() .interfaceId(interfaceId) .type(NetworkInterfaceType.CAN_INTERFACE) .canInterface(CanInterface.builder() .name("canInterface0") .protocolName("CAN") .protocolVersion("1.0") .build()) .build(); // Vehicle.Powertrain.EngineRPM decoder. SignalDecoder engineRpmDecoder = SignalDecoder.builder() .fullyQualifiedName("Vehicle.Powertrain.EngineRPM") .interfaceId(interfaceId) .type(SignalDecoderType.CAN_SIGNAL) .canSignal(CanSignal.builder() .messageId(100) .isBigEndian(false) .isSigned(false) .startBit(0) .length(16) .factor(1.0) .offset(0.0) .build()) .build(); // Vehicle.Powertrain.VehicleSpeed decoder. SignalDecoder vehicleSpeedDecoder = SignalDecoder.builder() .fullyQualifiedName("Vehicle.Powertrain.VehicleSpeed") .interfaceId(interfaceId) .type(SignalDecoderType.CAN_SIGNAL) .canSignal(CanSignal.builder() .messageId(101) .isBigEndian(false) .isSigned(false) .startBit(16) .length(16) .factor(1.0) .offset(0.0) .build()) .build(); CreateDecoderManifestRequest request = CreateDecoderManifestRequest.builder() .name(name) .modelManifestArn(modelManifestArn) .networkInterfaces(List.of(networkInterface)) .signalDecoders(List.of(engineRpmDecoder, vehicleSpeedDecoder)) .build(); CompletableFuture<String> result = new CompletableFuture<>(); getAsyncClient().createDecoderManifest(request) .whenComplete((response, exception) -> { if (exception != null) { Throwable cause = exception.getCause() != null ? exception.getCause() : exception; if (cause instanceof DecoderManifestValidationException) { result.completeExceptionally(new CompletionException("The request contains signal decoders with validation errors: " + cause.getMessage(), cause)); } else { result.completeExceptionally(new CompletionException("Failed to create decoder manifest: " + exception.getMessage(), exception)); } } else { result.complete(response.arn()); // Complete successfully with the ARN } }); return result; } /** * Deletes a decoder manifest. * * @param name the name of the decoder manifest to delete * @return a {@link CompletableFuture} that completes when the decoder manifest has been deleted */ public CompletableFuture<Void> deleteDecoderManifestAsync(String name) { return getAsyncClient().deleteDecoderManifest(DeleteDecoderManifestRequest.builder().name(name).build()) .handle((response, exception) -> { if (exception != null) { Throwable cause = exception.getCause() != null ? exception.getCause() : exception; if (cause instanceof ResourceNotFoundException) { throw (ResourceNotFoundException) cause; } throw new RuntimeException("Failed to delete the decoder manifest: " + cause); } return null; }); } /** * Deletes a vehicle with the specified name. * * @param vecName the name of the vehicle to be deleted * @return a {@link CompletableFuture} that completes when the vehicle has been deleted */ public CompletableFuture<Void> deleteVehicleAsync(String vecName) { DeleteVehicleRequest request = DeleteVehicleRequest.builder() .vehicleName(vecName) .build(); return getAsyncClient().deleteVehicle(request) .handle((response, exception) -> { if (exception != null) { Throwable cause = exception.getCause() != null ? exception.getCause() : exception; if (cause instanceof ResourceNotFoundException) { throw (ResourceNotFoundException) cause; } throw new RuntimeException("Failed to delete the vehicle: " + cause); } return null; }); } /** * Updates the model manifest. * * @param name the name of the model manifest to update */ public void updateModelManifestAsync(String name) { UpdateModelManifestRequest request = UpdateModelManifestRequest.builder() .name(name) .status(ManifestStatus.ACTIVE) .build(); getAsyncClient().updateModelManifest(request) .whenComplete((response, exception) -> { if (exception != null) { throw new CompletionException("Failed to update model manifest: " + exception.getMessage(), exception); } }) .thenApply(response -> null); } /** * Updates the decoder manifest with the given name. * * @param name the name of the decoder manifest to update * @return a {@link CompletableFuture} that completes when the update operation is finished */ public CompletableFuture<Void> updateDecoderManifestAsync(String name) { UpdateDecoderManifestRequest request = UpdateDecoderManifestRequest.builder() .name(name) .status(ManifestStatus.ACTIVE) .build(); return getAsyncClient().updateDecoderManifest(request) .whenComplete((response, exception) -> { if (exception != null) { throw new CompletionException("Failed to update decoder manifest: " + exception.getMessage(), exception); } }) .thenApply(response -> null); } /** * Creates a new vehicle in the system. * * @param vecName the name of the vehicle to be created * @param manifestArn the Amazon Resource Name (ARN) of the model manifest for the vehicle * @param decArn the Amazon Resource Name (ARN) of the decoder manifest for the vehicle * @return a {@link CompletableFuture} that completes when the vehicle has been created, or throws a */ public CompletableFuture<Void> createVehicleAsync(String vecName, String manifestArn, String decArn) { CreateVehicleRequest request = CreateVehicleRequest.builder() .vehicleName(vecName) .modelManifestArn(manifestArn) .decoderManifestArn(decArn) .build(); CompletableFuture<Void> result = new CompletableFuture<>(); getAsyncClient().createVehicle(request) .whenComplete((response, exception) -> { if (exception != null) { Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception; if (cause instanceof ResourceNotFoundException) { result.completeExceptionally(cause); } else { result.completeExceptionally(new RuntimeException("Failed to create vehicle: " + cause.getMessage(), cause)); } } else { logger.info("Vehicle '{}' created successfully.", vecName); result.complete(null); // mark future as complete } }); return result; } /** * Waits for the decoder manifest to become active. * * @param decoderName the name of the decoder to wait for * @return a {@link CompletableFuture} that completes when the decoder manifest becomes active, or exceptionally if an error occurs or the manifest becomes invalid */ public CompletableFuture<Void> waitForDecoderManifestActiveAsync(String decoderName) { CompletableFuture<Void> result = new CompletableFuture<>(); ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); AtomicInteger secondsElapsed = new AtomicInteger(0); AtomicReference<ManifestStatus> lastStatus = new AtomicReference<>(ManifestStatus.DRAFT); logger.info(" Elapsed: 0s | Decoder Status: DRAFT"); final Runnable pollTask = new Runnable() { @Override public void run() { int elapsed = secondsElapsed.incrementAndGet(); // Check status every 5 seconds if (elapsed % 5 == 0) { GetDecoderManifestRequest request = GetDecoderManifestRequest.builder() .name(decoderName) .build(); getAsyncClient().getDecoderManifest(request) .whenComplete((response, exception) -> { if (exception != null) { Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception; scheduler.shutdown(); if (cause instanceof ResourceNotFoundException) { result.completeExceptionally(new RuntimeException("Decoder manifest not found: " + cause.getMessage(), cause)); } else { result.completeExceptionally(new RuntimeException("Error while polling decoder manifest status: " + exception.getMessage(), exception)); } return; } ManifestStatus status = response.status(); lastStatus.set(status); if (status == ManifestStatus.ACTIVE) { logger.info("\r Elapsed: {}s | Decoder Status: ACTIVE", elapsed); scheduler.shutdown(); result.complete(null); } else if (status == ManifestStatus.INVALID) { logger.info("\r Elapsed: {}s | Decoder Status: INVALID", elapsed); scheduler.shutdown(); result.completeExceptionally(new RuntimeException("Decoder manifest became INVALID. Cannot proceed.")); } else { logger.info("\r⏱ Elapsed: {}s | Decoder Status: {}", elapsed, status); } }); } else { logger.info("\r Elapsed: {}s | Decoder Status: {}", elapsed, lastStatus.get()); } } }; // Start the task with an initial delay of 1 second, and repeat every second scheduler.scheduleAtFixedRate(pollTask, 1, 1, TimeUnit.SECONDS); return result; } /** * Waits for the specified model manifest to become active. * * @param manifestName the name of the model manifest to wait for */ public CompletableFuture<Void> waitForModelManifestActiveAsync(String manifestName) { CompletableFuture<Void> result = new CompletableFuture<>(); ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); AtomicInteger secondsElapsed = new AtomicInteger(0); AtomicReference<ManifestStatus> lastStatus = new AtomicReference<>(ManifestStatus.DRAFT); logger.info("Elapsed: 0s | Status: DRAFT"); final Runnable pollTask = new Runnable() { @Override public void run() { int elapsed = secondsElapsed.incrementAndGet(); // Only check status every 5 seconds if (elapsed % 5 == 0) { GetModelManifestRequest request = GetModelManifestRequest.builder() .name(manifestName) .build(); getAsyncClient().getModelManifest(request) .whenComplete((response, exception) -> { if (exception != null) { Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception; scheduler.shutdown(); if (cause instanceof ResourceNotFoundException) { result.completeExceptionally(new RuntimeException("Model manifest not found: " + cause.getMessage(), cause)); } else { result.completeExceptionally(new RuntimeException("Error while polling model manifest status: " + exception.getMessage(), exception)); } return; } ManifestStatus status = response.status(); lastStatus.set(status); if (status == ManifestStatus.ACTIVE) { logger.info("\rElapsed: {}s | Status: ACTIVE", elapsed); scheduler.shutdown(); result.complete(null); } else if (status == ManifestStatus.INVALID) { logger.info("\rElapsed: {}s | Status: INVALID", elapsed); scheduler.shutdown(); result.completeExceptionally(new RuntimeException("Model manifest became INVALID. Cannot proceed.")); } else { logger.info("\rElapsed: {}s | Status: {}", elapsed, status); } }); } else { logger.info("\rElapsed: {}s | Status: {}", elapsed, lastStatus.get()); } } }; // Start the task with an initial delay of 1 second, and repeat every second scheduler.scheduleAtFixedRate(pollTask, 1, 1, TimeUnit.SECONDS); return result; } /** * Fetches the details of a vehicle. * * @param vehicleName the name of the vehicle to fetch details for * @return a {@link CompletableFuture} that completes when the vehicle details have been fetched */ public CompletableFuture<Void> getVehicleDetailsAsync(String vehicleName) { GetVehicleRequest request = GetVehicleRequest.builder() .vehicleName(vehicleName) .build(); CompletableFuture<Void> result = new CompletableFuture<>(); getAsyncClient().getVehicle(request) .whenComplete((response, exception) -> { if (exception != null) { Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception; if (cause instanceof ResourceNotFoundException) { result.completeExceptionally(cause); // don't rewrap } else { result.completeExceptionally(new RuntimeException("Failed to fetch vehicle details: " + cause.getMessage(), cause)); } } else { Map<String, Object> details = new HashMap<>(); details.put("vehicleName", response.vehicleName()); details.put("arn", response.arn()); details.put("modelManifestArn", response.modelManifestArn()); details.put("decoderManifestArn", response.decoderManifestArn()); details.put("attributes", response.attributes()); details.put("creationTime", response.creationTime().toString()); details.put("lastModificationTime", response.lastModificationTime().toString()); logger.info("Vehicle Details:"); details.forEach((key, value) -> logger.info("• {} : {}", key, value)); result.complete(null); // mark as successful } }); return result; } /** * Creates an IoT Thing if it does not already exist. * * @param thingName the name of the IoT Thing to create * @return a {@link CompletableFuture} that completes when the IoT Thing has been created or if it already exists */ public CompletableFuture<Void> createThingIfNotExistsAsync(String thingName) { IotAsyncClient iotClient = IotAsyncClient.builder() .region(Region.US_EAST_1) .build(); CreateThingRequest request = CreateThingRequest.builder() .thingName(thingName) .build(); return iotClient.createThing(request) .whenComplete((response, exception) -> { if (exception != null) { if (exception instanceof ResourceAlreadyExistsException) { logger.info(" IoT Thing already exists: " + thingName); } else { throw new CompletionException("Failed to create IoT Thing: " + thingName, exception); } } else { logger.info("IoT Thing created: " + response.thingName()); } }) .thenApply(response -> null); } /** * Deletes a model manifest. * * @param name the name of the model manifest to delete * @return a {@link CompletableFuture} that completes when the model manifest has been deleted */ public CompletableFuture<Void> deleteModelManifestAsync(String name) { DeleteModelManifestRequest request = DeleteModelManifestRequest.builder() .name(name) .build(); return getAsyncClient().deleteModelManifest(request) .handle((response, exception) -> { if (exception != null) { Throwable cause = exception.getCause() != null ? exception.getCause() : exception; if (cause instanceof ResourceNotFoundException) { throw (ResourceNotFoundException) cause; } throw new RuntimeException("Failed to delete the model manifest: " + cause); } logger.info("{} was successfully deleted", name); return null; }); } /** * Deletes a signal catalog. * * @param name the name of the signal catalog to delete * @return a {@link CompletableFuture} that completes when the signal catalog is deleted */ public CompletableFuture<Void> deleteSignalCatalogAsync(String name) { DeleteSignalCatalogRequest request = DeleteSignalCatalogRequest.builder() .name(name) .build(); return getAsyncClient().deleteSignalCatalog(request) .handle((response, exception) -> { if (exception != null) { Throwable cause = exception.getCause() != null ? exception.getCause() : exception; if (cause instanceof ResourceNotFoundException) { throw (ResourceNotFoundException) cause; } throw new RuntimeException("Failed to delete the signal catalog: " + cause); } logger.info("{} was successfully deleted", name); return null; }); } /** * Asynchronously retrieves a list of all nodes in the specified signal catalog. * * @param signalCatalogName the name of the signal catalog to retrieve nodes for * @return a {@link CompletableFuture} that, when completed, contains a {@link List} of {@link Node} objects * representing all the nodes in the specified signal catalog */ public CompletableFuture<List<Node>> listSignalCatalogNodeAsync(String signalCatalogName) { ListSignalCatalogNodesRequest request = ListSignalCatalogNodesRequest.builder() .name(signalCatalogName) .build(); List<Node> allNodes = new ArrayList<>(); return getAsyncClient().listSignalCatalogNodesPaginator(request) .subscribe(response -> allNodes.addAll(response.nodes())) .thenApply(v -> allNodes); } /** * Creates a model manifest. * * @param name the name of the model manifest to create * @param signalCatalogArn the Amazon Resource Name (ARN) of the signal catalog * @param nodes a list of nodes to include in the model manifest * @return a {@link CompletableFuture} that completes with the ARN of the created model manifest */ public CompletableFuture<String> createModelManifestAsync(String name, String signalCatalogArn, List<Node> nodes) { // Extract the fully qualified names (FQNs) from each Node in the provided list. List<String> fqnList = nodes.stream() .map(node -> { if (node.sensor() != null) { return node.sensor().fullyQualifiedName(); } else if (node.branch() != null) { return node.branch().fullyQualifiedName(); } else if (node.attribute() != null) { return node.attribute().fullyQualifiedName(); } else { throw new RuntimeException("Unsupported node type"); } }) .toList(); CreateModelManifestRequest request = CreateModelManifestRequest.builder() .name(name) .signalCatalogArn(signalCatalogArn) .nodes(fqnList) .build(); CompletableFuture<String> result = new CompletableFuture<>(); getAsyncClient().createModelManifest(request) .whenComplete((response, exception) -> { if (exception != null) { Throwable cause = exception.getCause() != null ? exception.getCause() : exception; if (cause instanceof InvalidSignalsException) { result.completeExceptionally(new CompletionException("The request contains signals that aren't valid: " + cause.getMessage(), cause)); } else { result.completeExceptionally(new CompletionException("Failed to create model manifest: " + exception.getMessage(), exception)); } } else { result.complete(response.arn()); // Complete successfully with the ARN } }); return result; } /** * Deletes a fleet based on the provided fleet ID. * * @param fleetId the ID of the fleet to be deleted */ public CompletableFuture<Void> deleteFleetAsync(String fleetId) { DeleteFleetRequest request = DeleteFleetRequest.builder() .fleetId(fleetId) .build(); return getAsyncClient().deleteFleet(request) .handle((response, exception) -> { if (exception != null) { Throwable cause = exception.getCause() != null ? exception.getCause() : exception; if (cause instanceof ResourceNotFoundException) { throw (ResourceNotFoundException) cause; } throw new RuntimeException("Failed to delete the fleet: " + cause); } logger.info("{} was successfully deleted", fleetId); return null; }); } /** * Creates a new fleet. * * @param catARN the Amazon Resource Name (ARN) of the signal catalog to associate with the fleet * @param fleetId the unique identifier for the fleet * @return a {@link CompletableFuture} that completes with the ID of the created fleet */ public CompletableFuture<String> createFleetAsync(String catARN, String fleetId) { CreateFleetRequest fleetRequest = CreateFleetRequest.builder() .fleetId(fleetId) .signalCatalogArn(catARN) .description("Built using the AWS For Java V2") .build(); CompletableFuture<String> result = new CompletableFuture<>(); getAsyncClient().createFleet(fleetRequest) .whenComplete((response, exception) -> { if (exception != null) { Throwable cause = exception.getCause() != null ? exception.getCause() : exception; if (cause instanceof ResourceNotFoundException) { result.completeExceptionally(cause); } else { result.completeExceptionally(new RuntimeException("An unexpected error occurred", cause)); } } else { result.complete(response.id()); } }); return result; } }

Actions

L'exemple de code suivant montre comment utilisercreateDecoderManifest.

SDK pour Java 2.x
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

/** * Creates a new decoder manifest. * * @param name the name of the decoder manifest * @param modelManifestArn the ARN of the model manifest * @return a {@link CompletableFuture} that completes with the ARN of the created decoder manifest */ public CompletableFuture<String> createDecoderManifestAsync(String name, String modelManifestArn) { String interfaceId = "can0"; NetworkInterface networkInterface = NetworkInterface.builder() .interfaceId(interfaceId) .type(NetworkInterfaceType.CAN_INTERFACE) .canInterface(CanInterface.builder() .name("canInterface0") .protocolName("CAN") .protocolVersion("1.0") .build()) .build(); // Vehicle.Powertrain.EngineRPM decoder. SignalDecoder engineRpmDecoder = SignalDecoder.builder() .fullyQualifiedName("Vehicle.Powertrain.EngineRPM") .interfaceId(interfaceId) .type(SignalDecoderType.CAN_SIGNAL) .canSignal(CanSignal.builder() .messageId(100) .isBigEndian(false) .isSigned(false) .startBit(0) .length(16) .factor(1.0) .offset(0.0) .build()) .build(); // Vehicle.Powertrain.VehicleSpeed decoder. SignalDecoder vehicleSpeedDecoder = SignalDecoder.builder() .fullyQualifiedName("Vehicle.Powertrain.VehicleSpeed") .interfaceId(interfaceId) .type(SignalDecoderType.CAN_SIGNAL) .canSignal(CanSignal.builder() .messageId(101) .isBigEndian(false) .isSigned(false) .startBit(16) .length(16) .factor(1.0) .offset(0.0) .build()) .build(); CreateDecoderManifestRequest request = CreateDecoderManifestRequest.builder() .name(name) .modelManifestArn(modelManifestArn) .networkInterfaces(List.of(networkInterface)) .signalDecoders(List.of(engineRpmDecoder, vehicleSpeedDecoder)) .build(); CompletableFuture<String> result = new CompletableFuture<>(); getAsyncClient().createDecoderManifest(request) .whenComplete((response, exception) -> { if (exception != null) { Throwable cause = exception.getCause() != null ? exception.getCause() : exception; if (cause instanceof DecoderManifestValidationException) { result.completeExceptionally(new CompletionException("The request contains signal decoders with validation errors: " + cause.getMessage(), cause)); } else { result.completeExceptionally(new CompletionException("Failed to create decoder manifest: " + exception.getMessage(), exception)); } } else { result.complete(response.arn()); // Complete successfully with the ARN } }); return result; }
  • Pour plus de détails sur l'API, reportez-vous createDecoderManifestà la section Référence des AWS SDK for Java 2.x API.

L'exemple de code suivant montre comment utilisercreateFleet.

SDK pour Java 2.x
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

/** * Creates a new fleet. * * @param catARN the Amazon Resource Name (ARN) of the signal catalog to associate with the fleet * @param fleetId the unique identifier for the fleet * @return a {@link CompletableFuture} that completes with the ID of the created fleet */ public CompletableFuture<String> createFleetAsync(String catARN, String fleetId) { CreateFleetRequest fleetRequest = CreateFleetRequest.builder() .fleetId(fleetId) .signalCatalogArn(catARN) .description("Built using the AWS For Java V2") .build(); CompletableFuture<String> result = new CompletableFuture<>(); getAsyncClient().createFleet(fleetRequest) .whenComplete((response, exception) -> { if (exception != null) { Throwable cause = exception.getCause() != null ? exception.getCause() : exception; if (cause instanceof ResourceNotFoundException) { result.completeExceptionally(cause); } else { result.completeExceptionally(new RuntimeException("An unexpected error occurred", cause)); } } else { result.complete(response.id()); } }); return result; }
  • Pour plus de détails sur l'API, consultez CreateFleet dans la référence des AWS SDK for Java 2.x API.

L'exemple de code suivant montre comment utilisercreateModelManifest.

SDK pour Java 2.x
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

/** * Creates a model manifest. * * @param name the name of the model manifest to create * @param signalCatalogArn the Amazon Resource Name (ARN) of the signal catalog * @param nodes a list of nodes to include in the model manifest * @return a {@link CompletableFuture} that completes with the ARN of the created model manifest */ public CompletableFuture<String> createModelManifestAsync(String name, String signalCatalogArn, List<Node> nodes) { // Extract the fully qualified names (FQNs) from each Node in the provided list. List<String> fqnList = nodes.stream() .map(node -> { if (node.sensor() != null) { return node.sensor().fullyQualifiedName(); } else if (node.branch() != null) { return node.branch().fullyQualifiedName(); } else if (node.attribute() != null) { return node.attribute().fullyQualifiedName(); } else { throw new RuntimeException("Unsupported node type"); } }) .toList(); CreateModelManifestRequest request = CreateModelManifestRequest.builder() .name(name) .signalCatalogArn(signalCatalogArn) .nodes(fqnList) .build(); CompletableFuture<String> result = new CompletableFuture<>(); getAsyncClient().createModelManifest(request) .whenComplete((response, exception) -> { if (exception != null) { Throwable cause = exception.getCause() != null ? exception.getCause() : exception; if (cause instanceof InvalidSignalsException) { result.completeExceptionally(new CompletionException("The request contains signals that aren't valid: " + cause.getMessage(), cause)); } else { result.completeExceptionally(new CompletionException("Failed to create model manifest: " + exception.getMessage(), exception)); } } else { result.complete(response.arn()); // Complete successfully with the ARN } }); return result; }
  • Pour plus de détails sur l'API, reportez-vous createModelManifestà la section Référence des AWS SDK for Java 2.x API.

L'exemple de code suivant montre comment utilisercreateSignalCatalog.

SDK pour Java 2.x
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

/** * Creates a signal catalog. * * @param signalCatalogName the name of the signal catalog to be created * @return a {@link CompletableFuture} that completes with the Amazon Resource Name (ARN) of the created signal catalog */ public CompletableFuture<String> createSignalCatalogAsync(String signalCatalogName) { return deleteSignalCatalogIfExistsAsync(signalCatalogName) .thenCompose(ignored -> delayAsync(2000)) // Wait for 2 seconds .thenCompose(ignored -> { List<Node> nodes = List.of( Node.builder().branch( Branch.builder() .fullyQualifiedName("Vehicle") .description("Root branch") .build() ).build(), Node.builder().branch( Branch.builder() .fullyQualifiedName("Vehicle.Powertrain") .description("Powertrain branch") .build() ).build(), Node.builder().sensor( Sensor.builder() .fullyQualifiedName("Vehicle.Powertrain.EngineRPM") .description("Engine RPM") .dataType(NodeDataType.DOUBLE) .unit("rpm") .build() ).build(), Node.builder().sensor( Sensor.builder() .fullyQualifiedName("Vehicle.Powertrain.VehicleSpeed") .description("Vehicle Speed") .dataType(NodeDataType.DOUBLE) .unit("km/h") .build() ).build() ); CreateSignalCatalogRequest request = CreateSignalCatalogRequest.builder() .name(signalCatalogName) .nodes(nodes) .build(); CompletableFuture<String> result = new CompletableFuture<>(); getAsyncClient().createSignalCatalog(request) .whenComplete((response, exception) -> { if (exception != null) { Throwable cause = exception.getCause() != null ? exception.getCause() : exception; if (cause instanceof ValidationException) { result.completeExceptionally(cause); } else { result.completeExceptionally(new RuntimeException("Error creating the catalog", cause)); } } else { result.complete(response.arn()); } }); return result; }); }
  • Pour plus de détails sur l'API, reportez-vous createSignalCatalogà la section Référence des AWS SDK for Java 2.x API.

L'exemple de code suivant montre comment utilisercreateVehicle.

SDK pour Java 2.x
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

/** * Creates a new vehicle in the system. * * @param vecName the name of the vehicle to be created * @param manifestArn the Amazon Resource Name (ARN) of the model manifest for the vehicle * @param decArn the Amazon Resource Name (ARN) of the decoder manifest for the vehicle * @return a {@link CompletableFuture} that completes when the vehicle has been created, or throws a */ public CompletableFuture<Void> createVehicleAsync(String vecName, String manifestArn, String decArn) { CreateVehicleRequest request = CreateVehicleRequest.builder() .vehicleName(vecName) .modelManifestArn(manifestArn) .decoderManifestArn(decArn) .build(); CompletableFuture<Void> result = new CompletableFuture<>(); getAsyncClient().createVehicle(request) .whenComplete((response, exception) -> { if (exception != null) { Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception; if (cause instanceof ResourceNotFoundException) { result.completeExceptionally(cause); } else { result.completeExceptionally(new RuntimeException("Failed to create vehicle: " + cause.getMessage(), cause)); } } else { logger.info("Vehicle '{}' created successfully.", vecName); result.complete(null); // mark future as complete } }); return result; }
  • Pour plus de détails sur l'API, voir CreateVehicle dans la référence des AWS SDK for Java 2.x API.

L'exemple de code suivant montre comment utiliserdeleteDecoderManifest.

SDK pour Java 2.x
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

/** * Deletes a decoder manifest. * * @param name the name of the decoder manifest to delete * @return a {@link CompletableFuture} that completes when the decoder manifest has been deleted */ public CompletableFuture<Void> deleteDecoderManifestAsync(String name) { return getAsyncClient().deleteDecoderManifest(DeleteDecoderManifestRequest.builder().name(name).build()) .handle((response, exception) -> { if (exception != null) { Throwable cause = exception.getCause() != null ? exception.getCause() : exception; if (cause instanceof ResourceNotFoundException) { throw (ResourceNotFoundException) cause; } throw new RuntimeException("Failed to delete the decoder manifest: " + cause); } return null; }); }
  • Pour plus de détails sur l'API, reportez-vous deleteDecoderManifestà la section Référence des AWS SDK for Java 2.x API.

L'exemple de code suivant montre comment utiliserdeleteFleet.

SDK pour Java 2.x
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

/** * Deletes a fleet based on the provided fleet ID. * * @param fleetId the ID of the fleet to be deleted */ public CompletableFuture<Void> deleteFleetAsync(String fleetId) { DeleteFleetRequest request = DeleteFleetRequest.builder() .fleetId(fleetId) .build(); return getAsyncClient().deleteFleet(request) .handle((response, exception) -> { if (exception != null) { Throwable cause = exception.getCause() != null ? exception.getCause() : exception; if (cause instanceof ResourceNotFoundException) { throw (ResourceNotFoundException) cause; } throw new RuntimeException("Failed to delete the fleet: " + cause); } logger.info("{} was successfully deleted", fleetId); return null; }); }

L'exemple de code suivant montre comment utiliserdeleteModelManifest.

SDK pour Java 2.x
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

/** * Deletes a model manifest. * * @param name the name of the model manifest to delete * @return a {@link CompletableFuture} that completes when the model manifest has been deleted */ public CompletableFuture<Void> deleteModelManifestAsync(String name) { DeleteModelManifestRequest request = DeleteModelManifestRequest.builder() .name(name) .build(); return getAsyncClient().deleteModelManifest(request) .handle((response, exception) -> { if (exception != null) { Throwable cause = exception.getCause() != null ? exception.getCause() : exception; if (cause instanceof ResourceNotFoundException) { throw (ResourceNotFoundException) cause; } throw new RuntimeException("Failed to delete the model manifest: " + cause); } logger.info("{} was successfully deleted", name); return null; }); }
  • Pour plus de détails sur l'API, reportez-vous deleteModelManifestà la section Référence des AWS SDK for Java 2.x API.

L'exemple de code suivant montre comment utiliserdeleteSignalCatalog.

SDK pour Java 2.x
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

/** * Deletes a signal catalog. * * @param name the name of the signal catalog to delete * @return a {@link CompletableFuture} that completes when the signal catalog is deleted */ public CompletableFuture<Void> deleteSignalCatalogAsync(String name) { DeleteSignalCatalogRequest request = DeleteSignalCatalogRequest.builder() .name(name) .build(); return getAsyncClient().deleteSignalCatalog(request) .handle((response, exception) -> { if (exception != null) { Throwable cause = exception.getCause() != null ? exception.getCause() : exception; if (cause instanceof ResourceNotFoundException) { throw (ResourceNotFoundException) cause; } throw new RuntimeException("Failed to delete the signal catalog: " + cause); } logger.info("{} was successfully deleted", name); return null; }); }
  • Pour plus de détails sur l'API, reportez-vous deleteSignalCatalogà la section Référence des AWS SDK for Java 2.x API.

L'exemple de code suivant montre comment utiliserdeleteVehicle.

SDK pour Java 2.x
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

/** * Deletes a vehicle with the specified name. * * @param vecName the name of the vehicle to be deleted * @return a {@link CompletableFuture} that completes when the vehicle has been deleted */ public CompletableFuture<Void> deleteVehicleAsync(String vecName) { DeleteVehicleRequest request = DeleteVehicleRequest.builder() .vehicleName(vecName) .build(); return getAsyncClient().deleteVehicle(request) .handle((response, exception) -> { if (exception != null) { Throwable cause = exception.getCause() != null ? exception.getCause() : exception; if (cause instanceof ResourceNotFoundException) { throw (ResourceNotFoundException) cause; } throw new RuntimeException("Failed to delete the vehicle: " + cause); } return null; }); }
  • Pour plus de détails sur l'API, voir DeleteVehicle dans la référence des AWS SDK for Java 2.x API.

L'exemple de code suivant montre comment utilisergetDecoderManifest.

SDK pour Java 2.x
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

/** * Waits for the decoder manifest to become active. * * @param decoderName the name of the decoder to wait for * @return a {@link CompletableFuture} that completes when the decoder manifest becomes active, or exceptionally if an error occurs or the manifest becomes invalid */ public CompletableFuture<Void> waitForDecoderManifestActiveAsync(String decoderName) { CompletableFuture<Void> result = new CompletableFuture<>(); ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); AtomicInteger secondsElapsed = new AtomicInteger(0); AtomicReference<ManifestStatus> lastStatus = new AtomicReference<>(ManifestStatus.DRAFT); logger.info(" Elapsed: 0s | Decoder Status: DRAFT"); final Runnable pollTask = new Runnable() { @Override public void run() { int elapsed = secondsElapsed.incrementAndGet(); // Check status every 5 seconds if (elapsed % 5 == 0) { GetDecoderManifestRequest request = GetDecoderManifestRequest.builder() .name(decoderName) .build(); getAsyncClient().getDecoderManifest(request) .whenComplete((response, exception) -> { if (exception != null) { Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception; scheduler.shutdown(); if (cause instanceof ResourceNotFoundException) { result.completeExceptionally(new RuntimeException("Decoder manifest not found: " + cause.getMessage(), cause)); } else { result.completeExceptionally(new RuntimeException("Error while polling decoder manifest status: " + exception.getMessage(), exception)); } return; } ManifestStatus status = response.status(); lastStatus.set(status); if (status == ManifestStatus.ACTIVE) { logger.info("\r Elapsed: {}s | Decoder Status: ACTIVE", elapsed); scheduler.shutdown(); result.complete(null); } else if (status == ManifestStatus.INVALID) { logger.info("\r Elapsed: {}s | Decoder Status: INVALID", elapsed); scheduler.shutdown(); result.completeExceptionally(new RuntimeException("Decoder manifest became INVALID. Cannot proceed.")); } else { logger.info("\r⏱ Elapsed: {}s | Decoder Status: {}", elapsed, status); } }); } else { logger.info("\r Elapsed: {}s | Decoder Status: {}", elapsed, lastStatus.get()); } } }; // Start the task with an initial delay of 1 second, and repeat every second scheduler.scheduleAtFixedRate(pollTask, 1, 1, TimeUnit.SECONDS); return result; }
  • Pour plus de détails sur l'API, reportez-vous getDecoderManifestà la section Référence des AWS SDK for Java 2.x API.

L'exemple de code suivant montre comment utilisergetModelManifest.

SDK pour Java 2.x
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

/** * Waits for the specified model manifest to become active. * * @param manifestName the name of the model manifest to wait for */ public CompletableFuture<Void> waitForModelManifestActiveAsync(String manifestName) { CompletableFuture<Void> result = new CompletableFuture<>(); ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); AtomicInteger secondsElapsed = new AtomicInteger(0); AtomicReference<ManifestStatus> lastStatus = new AtomicReference<>(ManifestStatus.DRAFT); logger.info("Elapsed: 0s | Status: DRAFT"); final Runnable pollTask = new Runnable() { @Override public void run() { int elapsed = secondsElapsed.incrementAndGet(); // Only check status every 5 seconds if (elapsed % 5 == 0) { GetModelManifestRequest request = GetModelManifestRequest.builder() .name(manifestName) .build(); getAsyncClient().getModelManifest(request) .whenComplete((response, exception) -> { if (exception != null) { Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception; scheduler.shutdown(); if (cause instanceof ResourceNotFoundException) { result.completeExceptionally(new RuntimeException("Model manifest not found: " + cause.getMessage(), cause)); } else { result.completeExceptionally(new RuntimeException("Error while polling model manifest status: " + exception.getMessage(), exception)); } return; } ManifestStatus status = response.status(); lastStatus.set(status); if (status == ManifestStatus.ACTIVE) { logger.info("\rElapsed: {}s | Status: ACTIVE", elapsed); scheduler.shutdown(); result.complete(null); } else if (status == ManifestStatus.INVALID) { logger.info("\rElapsed: {}s | Status: INVALID", elapsed); scheduler.shutdown(); result.completeExceptionally(new RuntimeException("Model manifest became INVALID. Cannot proceed.")); } else { logger.info("\rElapsed: {}s | Status: {}", elapsed, status); } }); } else { logger.info("\rElapsed: {}s | Status: {}", elapsed, lastStatus.get()); } } }; // Start the task with an initial delay of 1 second, and repeat every second scheduler.scheduleAtFixedRate(pollTask, 1, 1, TimeUnit.SECONDS); return result; }
  • Pour plus de détails sur l'API, reportez-vous getModelManifestà la section Référence des AWS SDK for Java 2.x API.

L'exemple de code suivant montre comment utilisergetVehicle.

SDK pour Java 2.x
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

/** * Fetches the details of a vehicle. * * @param vehicleName the name of the vehicle to fetch details for * @return a {@link CompletableFuture} that completes when the vehicle details have been fetched */ public CompletableFuture<Void> getVehicleDetailsAsync(String vehicleName) { GetVehicleRequest request = GetVehicleRequest.builder() .vehicleName(vehicleName) .build(); CompletableFuture<Void> result = new CompletableFuture<>(); getAsyncClient().getVehicle(request) .whenComplete((response, exception) -> { if (exception != null) { Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception; if (cause instanceof ResourceNotFoundException) { result.completeExceptionally(cause); // don't rewrap } else { result.completeExceptionally(new RuntimeException("Failed to fetch vehicle details: " + cause.getMessage(), cause)); } } else { Map<String, Object> details = new HashMap<>(); details.put("vehicleName", response.vehicleName()); details.put("arn", response.arn()); details.put("modelManifestArn", response.modelManifestArn()); details.put("decoderManifestArn", response.decoderManifestArn()); details.put("attributes", response.attributes()); details.put("creationTime", response.creationTime().toString()); details.put("lastModificationTime", response.lastModificationTime().toString()); logger.info("Vehicle Details:"); details.forEach((key, value) -> logger.info("• {} : {}", key, value)); result.complete(null); // mark as successful } }); return result; }
  • Pour plus de détails sur l'API, consultez GetVehicle dans AWS SDK for Java 2.x API Reference.

L'exemple de code suivant montre comment utiliserlistSignalCatalogNodes.

SDK pour Java 2.x
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

/** * Asynchronously retrieves a list of all nodes in the specified signal catalog. * * @param signalCatalogName the name of the signal catalog to retrieve nodes for * @return a {@link CompletableFuture} that, when completed, contains a {@link List} of {@link Node} objects * representing all the nodes in the specified signal catalog */ public CompletableFuture<List<Node>> listSignalCatalogNodeAsync(String signalCatalogName) { ListSignalCatalogNodesRequest request = ListSignalCatalogNodesRequest.builder() .name(signalCatalogName) .build(); List<Node> allNodes = new ArrayList<>(); return getAsyncClient().listSignalCatalogNodesPaginator(request) .subscribe(response -> allNodes.addAll(response.nodes())) .thenApply(v -> allNodes); }
  • Pour plus de détails sur l'API, consultez la section listSignalCatalogNodes dans le AWS SDK for Java 2.x manuel de référence des API.

L'exemple de code suivant montre comment utiliserupdateDecoderManifest.

SDK pour Java 2.x
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

/** * Updates the decoder manifest with the given name. * * @param name the name of the decoder manifest to update * @return a {@link CompletableFuture} that completes when the update operation is finished */ public CompletableFuture<Void> updateDecoderManifestAsync(String name) { UpdateDecoderManifestRequest request = UpdateDecoderManifestRequest.builder() .name(name) .status(ManifestStatus.ACTIVE) .build(); return getAsyncClient().updateDecoderManifest(request) .whenComplete((response, exception) -> { if (exception != null) { throw new CompletionException("Failed to update decoder manifest: " + exception.getMessage(), exception); } }) .thenApply(response -> null); }
  • Pour plus de détails sur l'API, reportez-vous updateDecoderManifestà la section Référence des AWS SDK for Java 2.x API.

L'exemple de code suivant montre comment utiliserupdateModelManifest.

SDK pour Java 2.x
Note

Il y en a plus à ce sujet GitHub. Trouvez l’exemple complet et découvrez comment le configurer et l’exécuter dans le référentiel d’exemples de code AWS.

/** * Updates the model manifest. * * @param name the name of the model manifest to update */ public void updateModelManifestAsync(String name) { UpdateModelManifestRequest request = UpdateModelManifestRequest.builder() .name(name) .status(ManifestStatus.ACTIVE) .build(); getAsyncClient().updateModelManifest(request) .whenComplete((response, exception) -> { if (exception != null) { throw new CompletionException("Failed to update model manifest: " + exception.getMessage(), exception); } }) .thenApply(response -> null); }
  • Pour plus de détails sur l'API, reportez-vous updateModelManifestà la section Référence des AWS SDK for Java 2.x API.