-
Notifications
You must be signed in to change notification settings - Fork 2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add digital twin lifecycle sample #14744
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
195 changes: 195 additions & 0 deletions
195
...s-core/src/samples/java/com/azure/digitaltwins/core/DigitalTwinsLifecycleAsyncSample.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,195 @@ | ||
// Copyright (c) Microsoft Corporation. All rights reserved. | ||
// Licensed under the MIT License. | ||
|
||
package com.azure.digitaltwins.core; | ||
|
||
import com.azure.core.http.policy.HttpLogDetailLevel; | ||
import com.azure.core.http.policy.HttpLogOptions; | ||
import com.azure.digitaltwins.core.implementation.models.ErrorResponseException; | ||
import com.azure.digitaltwins.core.implementation.serialization.BasicRelationship; | ||
import com.azure.identity.ClientSecretCredentialBuilder; | ||
import org.apache.http.HttpStatus; | ||
|
||
import java.io.IOException; | ||
import java.net.URISyntaxException; | ||
import java.net.URL; | ||
import java.nio.file.Path; | ||
import java.nio.file.Paths; | ||
import java.util.Map; | ||
import java.util.concurrent.Semaphore; | ||
import java.util.concurrent.TimeUnit; | ||
|
||
/** | ||
* This sample creates all the models in \DTDL\Models folder in the ADT service instance and creates the corresponding twins in \DTDL\DigitalTwins folder. | ||
* The Diagram for the Hospital model looks like this: | ||
* | ||
* +------------+ | ||
* | Building +-----isEquippedWith-----+ | ||
* +------------+ | | ||
* | v | ||
* has +-----+ | ||
* | | HVAC| | ||
* v +-----+ | ||
* +------------+ | | ||
* | Floor +<--controlsTemperature--+ | ||
* +------------+ | ||
* | | ||
* contains | ||
* | | ||
* v | ||
* +------------+ +-----------------+ | ||
* | Room |-with component->| WifiAccessPoint | | ||
* +------------+ +-----------------+ | ||
* | ||
*/ | ||
public class DigitalTwinsLifecycleAsyncSample { | ||
private static final String tenantId = System.getenv("TENANT_ID"); | ||
private static final String clientId = System.getenv("CLIENT_ID"); | ||
private static final String clientSecret = System.getenv("CLIENT_SECRET"); | ||
private static final String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT"); | ||
|
||
private static final int MaxWaitTimeAsyncOperationsInSeconds = 10; | ||
|
||
private static final URL DtdlDirectoryUrl = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL"); | ||
private static final Path DtDlDirectoryPath; | ||
private static final Path TwinsPath; | ||
private static final Path ModelsPath; | ||
private static final Path RelationshipsPath; | ||
|
||
private static final DigitalTwinsAsyncClient client; | ||
|
||
static { | ||
try { | ||
assert DtdlDirectoryUrl != null; | ||
DtDlDirectoryPath = Paths.get(DtdlDirectoryUrl.toURI()); | ||
} catch (URISyntaxException e) { | ||
throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e); | ||
} | ||
TwinsPath = Paths.get(DtDlDirectoryPath.toString(), "DigitalTwins"); | ||
ModelsPath = Paths.get(DtDlDirectoryPath.toString(), "Models"); | ||
RelationshipsPath = Paths.get(DtDlDirectoryPath.toString(), "Relationships"); | ||
|
||
client = new DigitalTwinsClientBuilder() | ||
.tokenCredential( | ||
new ClientSecretCredentialBuilder() | ||
.tenantId(tenantId) | ||
.clientId(clientId) | ||
.clientSecret(clientSecret) | ||
.build() | ||
) | ||
.endpoint(endpoint) | ||
.httpLogOptions( | ||
new HttpLogOptions() | ||
.setLogLevel(HttpLogDetailLevel.NONE)) | ||
.buildAsyncClient(); | ||
} | ||
|
||
public static void main(String[] args) throws IOException, InterruptedException { | ||
// Ensure existing twins with the same name are deleted first | ||
deleteTwins(); | ||
|
||
// Create twin counterparts for all the models | ||
createTwins(); | ||
} | ||
|
||
/** | ||
* Delete a twin, and any relationships it might have. | ||
* @throws IOException If an I/O error is thrown when accessing the starting file. | ||
* @throws InterruptedException If the current thread is interrupted while waiting to acquire permits on a semaphore. | ||
*/ | ||
public static void deleteTwins() throws IOException, InterruptedException { | ||
System.out.println("DELETE DIGITAL TWINS"); | ||
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath); | ||
final Semaphore deleteTwinsSemaphore = new Semaphore(0); | ||
final Semaphore deleteRelationshipsSemaphore = new Semaphore(0); | ||
|
||
// Call APIs to clean up any pre-existing resources that might be referenced by this sample. If digital twin does not exist, ignore. | ||
twins | ||
.forEach((twinId, twinContent) -> { | ||
// Call APIs to delete all relationships. | ||
client.listRelationships(twinId, BasicRelationship.class) | ||
.doOnComplete(deleteRelationshipsSemaphore::release) | ||
.doOnError(throwable -> { | ||
if (throwable instanceof ErrorResponseException && ((ErrorResponseException) throwable).getResponse().getStatusCode() == HttpStatus.SC_NOT_FOUND) { | ||
deleteRelationshipsSemaphore.release(); | ||
} else { | ||
System.err.println("List relationships error: " + throwable); | ||
} | ||
}) | ||
.subscribe( | ||
relationship -> client.deleteRelationship(twinId, relationship.getId()) | ||
.subscribe( | ||
aVoid -> System.out.println("Found and deleted relationship: " + relationship.getId()), | ||
throwable -> System.err.println("Delete relationship error: " + throwable) | ||
)); | ||
|
||
// Call APIs to delete any incoming relationships. | ||
client.listIncomingRelationships(twinId) | ||
.doOnComplete(deleteRelationshipsSemaphore::release) | ||
.doOnError(throwable -> { | ||
if (throwable instanceof ErrorResponseException && ((ErrorResponseException) throwable).getResponse().getStatusCode() == HttpStatus.SC_NOT_FOUND) { | ||
deleteRelationshipsSemaphore.release(); | ||
} else { | ||
System.err.println("List incoming relationships error: " + throwable); | ||
} | ||
}) | ||
.subscribe( | ||
incomingRelationship -> client.deleteRelationship(incomingRelationship.getSourceId(), incomingRelationship.getRelationshipId()) | ||
.subscribe( | ||
aVoid -> System.out.println("Found and deleted incoming relationship: " + incomingRelationship.getRelationshipId()), | ||
throwable -> System.err.println("Delete incoming relationship error: " + throwable) | ||
)); | ||
|
||
try { | ||
// Verify that the list relationships and list incoming relationships async operations have completed. | ||
if (deleteRelationshipsSemaphore.tryAcquire(2, MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS)) { | ||
// Now the digital twin should be safe to delete | ||
|
||
// Call APIs to delete the twins. | ||
client.deleteDigitalTwin(twinId) | ||
.doOnSuccess(aVoid -> { | ||
System.out.println("Deleted digital twin: " + twinId); | ||
deleteTwinsSemaphore.release(); | ||
}) | ||
.doOnError(throwable -> { | ||
if (throwable instanceof ErrorResponseException && ((ErrorResponseException) throwable).getResponse().getStatusCode() == HttpStatus.SC_NOT_FOUND) { | ||
deleteTwinsSemaphore.release(); | ||
} else { | ||
System.err.println("Could not delete digital twin " + twinId + " due to " + throwable); | ||
} | ||
}) | ||
.subscribe(); | ||
} | ||
} catch (InterruptedException e) { | ||
throw new RuntimeException("Could not cleanup the pre-existing resources: ", e); | ||
} | ||
}); | ||
|
||
// Verify that a semaphore has been released for each delete async operation, signifying that the async call has completed successfully.. | ||
boolean created = deleteTwinsSemaphore.tryAcquire(twins.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS); | ||
System.out.println("Twins deleted: " + created); | ||
} | ||
|
||
/** | ||
* Creates all twins specified in the DTDL->DigitalTwins directory. | ||
* @throws IOException If an I/O error is thrown when accessing the starting file. | ||
* @throws InterruptedException If the current thread is interrupted while waiting to acquire permits on a semaphore. | ||
*/ | ||
public static void createTwins() throws IOException, InterruptedException { | ||
System.out.println("CREATE DIGITAL TWINS"); | ||
Map<String, String> twins = FileHelper.loadAllFilesInPath(TwinsPath); | ||
final Semaphore createTwinsSemaphore = new Semaphore(0); | ||
|
||
// Call APIs to create the twins. For each async operation, once the operation is completed successfully, a semaphore is released. | ||
twins | ||
.forEach((twinId, twinContent) -> client.createDigitalTwinWithResponse(twinId, twinContent) | ||
.subscribe( | ||
response -> System.out.println("Created digital twin: " + twinId + "\n\t Body: " + response.getValue()), | ||
throwable -> System.err.println("Could not create digital twin " + twinId + " due to " + throwable), | ||
createTwinsSemaphore::release)); | ||
|
||
// Verify that a semaphore has been released for each async operation, signifying that the async call has completed successfully. | ||
boolean created = createTwinsSemaphore.tryAcquire(twins.size(), MaxWaitTimeAsyncOperationsInSeconds, TimeUnit.SECONDS); | ||
System.out.println("Twins created: " + created); | ||
} | ||
} |
111 changes: 0 additions & 111 deletions
111
...ltwins-core/src/samples/java/com/azure/digitaltwins/core/DigitalTwinsLifecycleSample.java
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
7 changes: 0 additions & 7 deletions
7
sdk/digitaltwins/azure-digitaltwins-core/src/samples/resources/BuildingTwin.json
This file was deleted.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
To understand why do we need semaphore here? Do we have some limitations for parallel operations?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
No, not really. The semaphore is to ensure that we do not exit before the async operation has completed. We start all async operations and then release the semaphore only once the async call has completed.
That way, the subsequent operations are executed after the previous call has completed -> similar to doing a await on a Task.