Skip to content
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 3 commits into from
Sep 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
Copy link
Contributor

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?

Copy link
Member Author

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.


// 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);
}
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,7 @@

package com.azure.digitaltwins.core;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
Expand All @@ -15,6 +12,13 @@
import java.util.stream.Stream;

public class FileHelper {

/**
* Loads all json file contents in a path.
* @param path Path to the target directory.
* @return List of all file names and their content in map format.
* @throws IOException If an I/O error is thrown when accessing the starting file.
*/
public static Map<String, String> loadAllFilesInPath(Path path) throws IOException {
Map<String, String> fileContents = new HashMap<>();

Expand All @@ -36,12 +40,12 @@ public static Map<String, String> loadAllFilesInPath(Path path) throws IOExcepti
return fileContents;
}

public static String cleanupJsonString(String jsonString) {
private static String cleanupJsonString(String jsonString) {
// Remove newline characters, empty spaces and unwanted unicode characters
return jsonString.replaceAll("([\\r\\n\\s+\\uFEFF-\\uFFFF])", "");
}

public static String getFileNameFromPath(Path path) {
private static String getFileNameFromPath(Path path) {
String fileName = path.getFileName().toString();
if (fileName.indexOf(".") > 0) {
fileName = fileName.substring(0, fileName.lastIndexOf("."));
Expand Down

This file was deleted.