From 8205b7bad69cc1c26c1ac27821ea605db51ab28f Mon Sep 17 00:00:00 2001 From: Ganesh Viswanathan Date: Wed, 10 Nov 2021 13:54:49 -0800 Subject: [PATCH 1/3] Updated java samples for latest working IoT Central SDK version 1.0.0-beta.2 with support for managed identity and containing other improvements --- java/.gitignore | 4 +- java/.vscode/settings.json | 3 + java/README.MD | 29 +- java/SampleOutput.txt | 110 ++++++++ java/build.gradle | 24 -- java/pom.xml | 76 +++++ java/src/main/IotCentralMgmtApiSample.java | 266 ++++++++++++++++++ .../src/main/IotCentralMgmtApiSampleBase.java | 42 +++ java/src/main/Main.java | 41 +++ .../main/java/sample/IoTCentralExample.java | 105 ------- 10 files changed, 559 insertions(+), 141 deletions(-) create mode 100644 java/.vscode/settings.json create mode 100644 java/SampleOutput.txt delete mode 100644 java/build.gradle create mode 100644 java/pom.xml create mode 100644 java/src/main/IotCentralMgmtApiSample.java create mode 100644 java/src/main/IotCentralMgmtApiSampleBase.java create mode 100644 java/src/main/Main.java delete mode 100644 java/src/main/java/sample/IoTCentralExample.java diff --git a/java/.gitignore b/java/.gitignore index 83ffa89..e8d17a6 100644 --- a/java/.gitignore +++ b/java/.gitignore @@ -1,6 +1,6 @@ .classpath -.gradle/ .project .settings/ bin/ -build/ \ No newline at end of file +build/ +target/ \ No newline at end of file diff --git a/java/.vscode/settings.json b/java/.vscode/settings.json new file mode 100644 index 0000000..e0f15db --- /dev/null +++ b/java/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "java.configuration.updateBuildConfiguration": "automatic" +} \ No newline at end of file diff --git a/java/README.MD b/java/README.MD index 072fb70..62e147b 100644 --- a/java/README.MD +++ b/java/README.MD @@ -1,24 +1,33 @@ -# Azure IoT Central ARM Java SDK samples +# Azure IoT Central Java SDK Samples for Management APIs +Sample code for using Azure IoT Central Management Plane APIs. Sample code for using [com.microsoft.azure.iotcentral.v2018_09_01:azure-mgmt-iotcentral](https://search.maven.org/artifact/com.microsoft.azure.iotcentral.v2018_09_01/azure-mgmt-iotcentral/1.0.0/jar) SDK provided by [Microsoft Azure](https://github.com/Azure). This sample code will check if the resource name is available, create or update an app, retrieve app information, update app, list all the apps that belongs to the specific resource group, and finally delete the app if uncommented. ## Get started ### Prerequisites - [Java JDK or JRE](https://www.oracle.com/technetwork/java/javase/downloads/index.html) -- [Gradle](https://gradle.org/install/) -- A resource group called **myResourceGroup** in your Azure subscription +- [Maven](http://maven.apache.org/install.html) +- A service principal and a resource group to work with. Follow [these instructions](https://docs.microsoft.com/en-us/azure/active-directory/develop/howto-create-service-principal-portal). -### Installation -To begin, simply clone this repository onto your local machine and build it using Gradle. +### SDK version -``` -gradle build -``` +The support SDK version is [1.0.0-beta.2](https://github.com/Azure/azure-sdk-for-java/tree/azure-resourcemanager-iotcentral_1.0.0-beta.2/sdk/iotcentral/azure-resourcemanager-iotcentral). + +See more samples on using IoT Central APIs [here](https://github.com/Azure/azure-sdk-for-java/blob/azure-resourcemanager-iotcentral_1.0.0-beta.2/sdk/iotcentral/azure-resourcemanager-iotcentral/SAMPLE.md). ### Usage -Make sure you head over to the src\main\java\sample\IoTCentralExample.java to change the configuration to the one that is shown on your [Microsoft Azure Portal](https://portal.azure.com). +To begin, clone this repository, update the authentication settings in IotCentralMgmtApiSampleBase.java, the app configurations in Main.java, and compile/execute the project. ``` -gradle run +cd src +mvn clean compile exec:java ``` + +See SampleOutput.txt in the basedir for output from the project execution. + +Continue developing using the samples shown [here](https://github.com/Azure/azure-sdk-for-java/blob/azure-resourcemanager-iotcentral_1.0.0-beta.2/sdk/iotcentral/azure-resourcemanager-iotcentral/SAMPLE.md). + +### Additional References: +Overview: Use the Azure SDK for Java | Microsoft Docs +Getting started: Get started with the Azure SDK for Java | Microsoft Docs diff --git a/java/SampleOutput.txt b/java/SampleOutput.txt new file mode 100644 index 0000000..d93d6b1 --- /dev/null +++ b/java/SampleOutput.txt @@ -0,0 +1,110 @@ +[INFO] Scanning for projects... +[INFO] +[INFO] --< com.microsoft.azure.iotcentral:azure-iot-central-java-sdk-samples >-- +[INFO] Building azure-iot-central-java-sdk-samples 2.0-SNAPSHOT +[INFO] --------------------------------[ jar ]--------------------------------- +[INFO] +[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ azure-iot-central-java-sdk-samples --- +[INFO] Deleting C:\code\final\azure-iot-central-arm-sdk-samples\java\target +[INFO] +[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ azure-iot-central-java-sdk-samples --- +[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! +[INFO] skip non existing resourceDirectory C:\code\final\azure-iot-central-arm-sdk-samples\java\src\main\resources +[INFO] +[INFO] --- maven-compiler-plugin:3.7.0:compile (default-compile) @ azure-iot-central-java-sdk-samples --- +[INFO] Changes detected - recompiling the module! +[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent! +[INFO] Compiling 3 source files to C:\code\final\azure-iot-central-arm-sdk-samples\java\target\classes +[INFO] +[INFO] --- exec-maven-plugin:1.6.0:java (default-cli) @ azure-iot-central-java-sdk-samples --- +------------------ +Operations List: +------------------ + +Microsoft.IoTCentral/IoTApps/read +Microsoft.IoTCentral/IoTApps/write +Microsoft.IoTCentral/IoTApps/delete +Microsoft.IoTCentral/checkNameAvailability/action +Microsoft.IoTCentral/checkSubdomainAvailability/action +Microsoft.IoTCentral/operations/read +Microsoft.IoTCentral/appTemplates/action +Microsoft.IoTCentral/register/action +Microsoft.IoTCentral/IoTApps/providers/Microsoft.Insights/metricDefinitions/read +Microsoft.IoTCentral/IoTApps/providers/Microsoft.Insights/diagnosticSettings/read +Microsoft.IoTCentral/IoTApps/providers/Microsoft.Insights/diagnosticSettings/write + +------------------ +IOT Central App Templates: +------------------ + +iotc-condition +iotc-consumption +iotc-distribution +iotc-inventory +iotc-logistics +iotc-meter +iotc-mfc +iotc-patient +iotc-pnp-preview +iotc-power +iotc-quality +iotc-store +iotc-video-analytics-om +iotc-waste + +------------------ +Apps in Resource Group: +------------------ + +Name:gaviswanapp21636580090, Location: eastus +Name:gtest1, Location: westus +Name:gaviswanapp21636578314, Location: eastus + +------------------ +Create/Update App: +------------------ + +randomizedName: gaviswanapp21636580731 +App created successfully. +------------------ +Get App: +------------------ + +Name:gaviswanapp21636580731, Location: eastus, com.azure.resourcemanager.iotcentral.implementation.AppImpl@2df8aa39 + +------------------ +Update App: +------------------ + +App updated successfully. + +------------------ +Delete App: +------------------ + +App deleted! + +------------------ +Validating Exceptions: +------------------ + +randomizedName: gaviswanapp21636580772 +Validated error with use of geo location. +------------------ +Validating Exceptions: +------------------ + +randomizedName: gaviswanapp21636580772 +Validated error with invalid sku 'S1'. +------------------ +Validating Exceptions: +------------------ + +randomizedName: gaviswanapp21636580775 +Validated error with F1 sku. +[INFO] ------------------------------------------------------------------------ +[INFO] BUILD SUCCESS +[INFO] ------------------------------------------------------------------------ +[INFO] Total time: 53.902 s +[INFO] Finished at: 2021-11-10T13:46:18-08:00 +[INFO] ------------------------------------------------------------------------ diff --git a/java/build.gradle b/java/build.gradle deleted file mode 100644 index 9816b83..0000000 --- a/java/build.gradle +++ /dev/null @@ -1,24 +0,0 @@ -apply plugin: 'java' - -repositories { - mavenCentral() -} - -sourceCompatibility = 1.8 -targetCompatibility = 1.8 - -dependencies { - implementation "com.microsoft.azure.iotcentral.v2018_09_01:azure-mgmt-iotcentral:1.0.4" - implementation "com.microsoft.azure:azure:1.30.0" - implementation "org.apache.logging.log4j:log4j-slf4j-impl:2.13.0" - implementation "org.apache.logging.log4j:log4j-core:2.13.0" -} - -jar { - archiveBaseName = 'iotcentral' - archiveVersion = '1.0.0' -} - -apply plugin: 'application' - -mainClassName = 'sample.IoTCentralExample' \ No newline at end of file diff --git a/java/pom.xml b/java/pom.xml new file mode 100644 index 0000000..b8a0b39 --- /dev/null +++ b/java/pom.xml @@ -0,0 +1,76 @@ + + + 4.0.0 + + com.microsoft.azure.iotcentral + azure-iot-central-java-sdk-samples + 2.0-SNAPSHOT + + ${basedir}/src/main + ${basedir}/src/main/scripts + ${basedir}/src/test + ${basedir}/target/classes + ${basedir}/target/test-classes + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + 1.8 + 1.8 + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + + java + + + + + Main + false + + + + + + + + com.azure + azure-core-http-netty + 1.11.1 + + + + com.azure.resourcemanager + azure-resourcemanager + 2.9.0 + + + + com.azure + azure-core + 1.21.0 + + + + com.azure + azure-identity + 1.4.0 + + + + com.azure.resourcemanager + azure-resourcemanager-iotcentral + 1.0.0-beta.2 + + + diff --git a/java/src/main/IotCentralMgmtApiSample.java b/java/src/main/IotCentralMgmtApiSample.java new file mode 100644 index 0000000..6029396 --- /dev/null +++ b/java/src/main/IotCentralMgmtApiSample.java @@ -0,0 +1,266 @@ +import java.io.IOException; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.util.Context; +import com.azure.resourcemanager.iotcentral.IotCentralManager; +import com.azure.resourcemanager.iotcentral.models.App; +import com.azure.resourcemanager.iotcentral.models.AppSku; +import com.azure.resourcemanager.iotcentral.models.AppSkuInfo; +import com.azure.resourcemanager.iotcentral.models.AppTemplate; +import com.azure.resourcemanager.iotcentral.models.Operation; +import com.azure.resourcemanager.iotcentral.models.SystemAssignedServiceIdentity; +import com.azure.resourcemanager.iotcentral.models.SystemAssignedServiceIdentityType; + +public class IotCentralMgmtApiSample extends IotCentralMgmtApiSampleBase { + private static String defaultLocation = "eastus"; + + public IotCentralMgmtApiSample() throws IOException { + super(); + } + + /** + * Lists the available operations in IoT Central Management Plan. + **/ + public static void operationsList(IotCentralManager manager) { + PagedIterable < Operation > operations = manager.operations().list(Context.NONE); + + printHeader("Operations List:"); + for (Operation operation: operations) { + System.out.println(operation.name()); + } + System.out.println(); + } + + /** + * Lists the app templates in IoT Central. + **/ + public static void appsListTemplates(IotCentralManager manager) { + PagedIterable < AppTemplate > templates = manager.apps().listTemplates(Context.NONE); + + printHeader("IOT Central App Templates:"); + // System.out.printf("Name: %s.%n", Arrays.toString(templates.stream().map(AppTemplate::name).toArray()), ","); + for (AppTemplate template: templates) { + System.out.println(template.manifestId()); + } + System.out.println(); + } + + /** + * Lists the apps in a given resource group in IoT Central. + **/ + public static void appsListByResourceGroup(IotCentralManager manager, String resourceGroupName) { + PagedIterable < App > apps = manager.apps().listByResourceGroup(resourceGroupName, Context.NONE); + + printHeader("Apps in Resource Group:"); + for (App app: apps) { + System.out.println("Name:" + app.name() + ", Location: " + app.regionName()); + } + System.out.println(); + } + + /** + * Creates a new IoT Central application using the IoT Central Management Plane APIs + * and system assigned managed identity. + **/ + public static String appsCreateOrUpdate( + IotCentralManager manager, + String resourceGroupName, + String appName) throws InterruptedException { + + printHeader("Create/Update App:"); + + String randomizedAppName = getRandomizedName(appName); + manager + .apps() + .define(randomizedAppName) + .withRegion(defaultLocation) + .withExistingResourceGroup(resourceGroupName) + .withSku(new AppSkuInfo().withName(AppSku.ST2)) + // Validating System Assigned Managed Identity for app creation. + .withIdentity( + new SystemAssignedServiceIdentity() + .withType(SystemAssignedServiceIdentityType.SYSTEM_ASSIGNED)) + .withDisplayName(randomizedAppName + "-Display") + .withSubdomain(randomizedAppName) + .withTemplate("iotc-distribution") + .create(); + + Thread.sleep(10000); + System.out.println("App created successfully."); + + return randomizedAppName; + } + + /** + * Retrieves information about an IoT Central application. + **/ + public static void appsGet( + IotCentralManager manager, + String resourceGroupName, + String appName) { + + printHeader("Get App:"); + + com.azure.resourcemanager.iotcentral.models.App app = + manager.apps().getByResourceGroupWithResponse(resourceGroupName, appName, Context.NONE).getValue(); + + System.out.println("Name:" + app.name() + ", Location: " + app.regionName() + ", " + app.toString() + "\n"); + } + + /** + * Updates application details. + **/ + public static void appsUpdate( + IotCentralManager manager, + String resourceGroupName, + String appName) throws InterruptedException { + + printHeader("Update App:"); + + App resource = + manager.apps().getByResourceGroupWithResponse(resourceGroupName, appName, Context.NONE).getValue(); + resource + .update() + .withIdentity( + new SystemAssignedServiceIdentity().withType(SystemAssignedServiceIdentityType.SYSTEM_ASSIGNED)) + .withDisplayName(appName + "- new display name") + .apply(); + + Thread.sleep(10000); + System.out.println("App updated successfully.\n"); + } + + /** + * Deletes the IoT Central application. + **/ + public static void appsDelete( + IotCentralManager manager, + String resourceGroupName, + String appName) throws InterruptedException { + + printHeader("Delete App:"); + + manager.apps().delete(resourceGroupName, appName, Context.NONE); + + Thread.sleep(10000); + System.out.println("App deleted!\n"); + } + + /** + * Validates error when using geography instead of region for location when creating + * a new IoT Central application. This change was introduced in 2021-06-01 APIs. + **/ + public static void appsCreateOrUpdateWithInvalidGeoLocation( + IotCentralManager manager, + String resourceGroupName, + String appName) { + + printHeader("Validating Exceptions:"); + + String invalidGeoLocationForIotcApp = "unitedstates"; + + try { + manager + .apps() + .define(getRandomizedName(appName)) + .withRegion(invalidGeoLocationForIotcApp) + .withExistingResourceGroup(resourceGroupName) + .withSku(new AppSkuInfo().withName(AppSku.ST2)) + .withIdentity( + new SystemAssignedServiceIdentity() + .withType(SystemAssignedServiceIdentityType.SYSTEM_ASSIGNED)) + .withDisplayName(appName + "-Display") + .withSubdomain(appName) + .withTemplate("iotc-distribution") + .create(); + } catch (ManagementException mex) { + if (mex.getValue().getMessage().contains("No registered resource provider found for location 'unitedstates'")) { + System.out.println("Validated error with use of geo location."); + } else { + System.err.println("ERROR: Expected exception thrown for use of geo location!"); + } + } + } + + /** + * Validates error when using an invalid SKU. This change (lack of support for S1 sku) was introduced in 2021-06-01 APIs. + **/ + public static void appsCreateOrUpdateWithInvalidSku( + com.azure.resourcemanager.iotcentral.IotCentralManager manager, + String resourceGroupName, + String appName, + String skuName) { + + printHeader("Validating Exceptions:"); + + AppSku invalidSkuForIotcApp = AppSku.fromString(skuName); + try { + manager + .apps() + .define(getRandomizedName(appName)) + .withRegion(defaultLocation) + .withExistingResourceGroup(resourceGroupName) + .withSku(new AppSkuInfo().withName(invalidSkuForIotcApp)) + .withIdentity( + new SystemAssignedServiceIdentity() + .withType(SystemAssignedServiceIdentityType.SYSTEM_ASSIGNED)) + .withDisplayName(appName + "-Display") + .withSubdomain(appName) + .withTemplate("iotc-distribution") + .create(); + } catch (ManagementException mex) { + if (mex.getValue().getMessage().contains("The sku S1 is invalid, allowed skus are ST0, ST1, ST2")) { + System.out.println(String.format("Validated error with invalid sku '%s'.", skuName)); + } else { + System.err.println("ERROR: Expected exception thrown for invalid sku!"); + } + } + } + + /** + * Validates error when using invalid inputs when creating IoT Central application. + **/ + public static void appsCreateOrUpdateThrowsWithSubscriptionLessAppAndF1Sku( + IotCentralManager manager, + String resourceGroupName, + String appName) { + + printHeader("Validating Exceptions:"); + + AppSku invalidSkuForIotcApp = com.azure.resourcemanager.iotcentral.models.AppSku.fromString("F1"); + try { + manager + .apps() + .define(getRandomizedName(appName)) + .withRegion(defaultLocation) + .withExistingResourceGroup(resourceGroupName) + .withSku(new AppSkuInfo().withName(invalidSkuForIotcApp)) + .withIdentity( + new SystemAssignedServiceIdentity() + .withType(com.azure.resourcemanager.iotcentral.models.SystemAssignedServiceIdentityType.SYSTEM_ASSIGNED)) + .withDisplayName(appName + "-Display") + .withSubdomain(appName) + .withTemplate("iotc-distribution") + .create(); + } catch (ManagementException mex) { + if (mex.getValue().getMessage().contains("Cannot create a subscription less application with SKU F1")) { + System.out.println("Validated error with F1 sku."); + } else { + System.err.println("ERROR: Expected correct exception for F1 sku!"); + } + } + } + + private static void printHeader(String headerName) { + System.out.println("------------------"); + System.out.println(headerName); + System.out.println("------------------"); + System.out.println(); + } + + private static String getRandomizedName(String name) { + String randomizedName = name + System.currentTimeMillis() / 1000L; + System.out.println("randomizedName: " + randomizedName); + return randomizedName; + } +} \ No newline at end of file diff --git a/java/src/main/IotCentralMgmtApiSampleBase.java b/java/src/main/IotCentralMgmtApiSampleBase.java new file mode 100644 index 0000000..5a28053 --- /dev/null +++ b/java/src/main/IotCentralMgmtApiSampleBase.java @@ -0,0 +1,42 @@ +import com.azure.core.credential.TokenCredential; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.profile.AzureProfile; +import com.azure.identity.ClientSecretCredentialBuilder; +import com.azure.resourcemanager.iotcentral.IotCentralManager; + +public class IotCentralMgmtApiSampleBase { + protected static final String AZURE_CLIENT_ID = "Azure Client ID"; + protected static final String AZURE_CLIENT_SECRET = "Azure Client Secret"; + protected static final String AZURE_TENANT_ID = "Azure Tenant ID"; + protected static final String AZURE_SUBSCRIPTION_ID = "Azure Subscription"; + + protected static IotCentralManager iotCentralManager; + + static { + authenticateToAzure(); + } + + protected static IotCentralManager CreateIoTCentralManager() { + AzureProfile profile = new AzureProfile(AZURE_TENANT_ID, AZURE_SUBSCRIPTION_ID, AzureEnvironment.AZURE); + TokenCredential credential = createToken(); + IotCentralManager manager = IotCentralManager.authenticate(credential, profile); + + return manager; + } + + protected static TokenCredential createToken() { + return new ClientSecretCredentialBuilder() + .clientSecret(AZURE_CLIENT_SECRET) + .tenantId(AZURE_TENANT_ID) + .clientId(AZURE_CLIENT_ID) + .build(); + } + + private static void authenticateToAzure() { + // Authentication for general IOTC service + AzureProfile profile = new AzureProfile(AZURE_TENANT_ID, AZURE_SUBSCRIPTION_ID, AzureEnvironment.AZURE); + TokenCredential credential = createToken(); + iotCentralManager = IotCentralManager.authenticate(credential, profile); + } + +} diff --git a/java/src/main/Main.java b/java/src/main/Main.java new file mode 100644 index 0000000..6f63004 --- /dev/null +++ b/java/src/main/Main.java @@ -0,0 +1,41 @@ +import com.azure.resourcemanager.iotcentral.IotCentralManager; + +public class Main { + // NOTE: Replace with your own resource group name. + // Make sure the service principal has "Contributor" permissions on the resource group. + private static final String RESOURCE_GROUP = "gTest1_26Oct2021"; + + // NOTE: Replace with your own IoT Central App Name. + private static final String APP_NAME = "gaviswanapp1"; + + public static void main(String[] args) throws Exception { + runIotcSamples(); + } + + private static void runIotcSamples() throws Exception { + // Create the IoT Central Manager to operate the management plane APIs. + IotCentralManager manager = IotCentralMgmtApiSample.CreateIoTCentralManager(); + + // Test listing operations. + IotCentralMgmtApiSample.operationsList(manager); + + // Test listing templates and apps inside resource group. + IotCentralMgmtApiSample.appsListTemplates(manager); + IotCentralMgmtApiSample.appsListByResourceGroup(manager, RESOURCE_GROUP); + + // Test App Creation. + String createdAppName = IotCentralMgmtApiSample.appsCreateOrUpdate(manager, RESOURCE_GROUP, APP_NAME); + + // Get app details and update it. + IotCentralMgmtApiSample.appsGet(manager, RESOURCE_GROUP, createdAppName); + IotCentralMgmtApiSample.appsUpdate(manager, RESOURCE_GROUP, createdAppName); + + // Delete the application. + IotCentralMgmtApiSample.appsDelete(manager, RESOURCE_GROUP, createdAppName); + + // Validate expected exceptions. + IotCentralMgmtApiSample.appsCreateOrUpdateWithInvalidGeoLocation(manager, RESOURCE_GROUP, APP_NAME); + IotCentralMgmtApiSample.appsCreateOrUpdateWithInvalidSku(manager, RESOURCE_GROUP, APP_NAME, "S1"); + IotCentralMgmtApiSample.appsCreateOrUpdateThrowsWithSubscriptionLessAppAndF1Sku(manager, RESOURCE_GROUP, APP_NAME); + } +} \ No newline at end of file diff --git a/java/src/main/java/sample/IoTCentralExample.java b/java/src/main/java/sample/IoTCentralExample.java deleted file mode 100644 index 05875a1..0000000 --- a/java/src/main/java/sample/IoTCentralExample.java +++ /dev/null @@ -1,105 +0,0 @@ -package sample; - -import rx.Observable; -import com.microsoft.rest.RestClient; -import com.microsoft.azure.PagedList; -import com.microsoft.azure.AzureEnvironment; -import com.microsoft.azure.AzureResponseBuilder; -import com.microsoft.azure.serializer.AzureJacksonAdapter; -import com.microsoft.azure.credentials.UserTokenCredentials; -import com.microsoft.azure.credentials.AzureTokenCredentials; -import com.microsoft.azure.management.iotcentral.v2018_09_01.App; -import com.microsoft.azure.management.iotcentral.v2018_09_01.AppPatch; -import com.microsoft.azure.management.iotcentral.v2018_09_01.AppSku; -import com.microsoft.azure.management.iotcentral.v2018_09_01.AppSkuInfo; -import com.microsoft.azure.management.iotcentral.v2018_09_01.Operation; -import com.microsoft.azure.management.iotcentral.v2018_09_01.OperationInputs; -import com.microsoft.azure.management.iotcentral.v2018_09_01.AppAvailabilityInfo; -import com.microsoft.azure.management.iotcentral.v2018_09_01.implementation.AppInner; -import com.microsoft.azure.management.iotcentral.v2018_09_01.implementation.AppsInner; -import com.microsoft.azure.management.iotcentral.v2018_09_01.implementation.AppTemplateInner; -import com.microsoft.azure.management.iotcentral.v2018_09_01.implementation.OperationInner; -import com.microsoft.azure.management.iotcentral.v2018_09_01.implementation.OperationsInner; -import com.microsoft.azure.management.iotcentral.v2018_09_01.implementation.IoTCentralManager; -import com.microsoft.azure.management.iotcentral.v2018_09_01.implementation.IotCentralClientImpl; - -public class IoTCentralExample { - public static void main(String[] args) { - String clientID = ""; // get it from service principal in Azure AD - String domain = ""; // tenant id - // please make sure this user has the following permission: - // Either Owner or Contributor to the sub id for IAM - // Owner of the the Service Principal (application) - // please make sure your Service Principal has the following setting: - // API Permissions: Given ReadWrite.All access for Microsoft IoT Central - // API Permissions: Given access for Windows Azure Service Management API - // Note: You would also need to grant admin consent for Default Directory through Enterprise applications tab (requires admin access) - // Manifest: allowPublicClient should set to true so that we can access the API publicly - String username = ""; - String password = ""; // for newly created user, make sure to try and login first so that you can change the password to your own instead of generated one - String subscriptionId = ""; - AzureTokenCredentials azureTokenCredentials = new UserTokenCredentials( - clientID, domain, username, password, AzureEnvironment.AZURE); - RestClient restClient = new RestClient.Builder() - .withBaseUrl(azureTokenCredentials.environment(), AzureEnvironment.Endpoint.RESOURCE_MANAGER) - .withCredentials(azureTokenCredentials) - .withSerializerAdapter(new AzureJacksonAdapter()) - .withResponseBuilderFactory(new AzureResponseBuilder.Factory()) - .build(); - IoTCentralManager iotcentralManager = IoTCentralManager.authenticate(restClient, subscriptionId); - - String resourceName = "my-app-name"; - String resourceGroupName = "myResourceGroup"; - OperationInputs operationInputs = new OperationInputs().withName(resourceName); - Observable checkNameResult = iotcentralManager.apps().checkNameAvailabilityAsync(operationInputs); - checkNameResult.subscribe(word->System.out.println("name is available: " + word.nameAvailable())); // check if the resource name is available - - AppInner app = new AppInner(); - app.withDisplayName(resourceName); - app.withSubdomain(resourceName); - app.withLocation("unitedstates"); - AppSku appSku = new AppSku().fromString("ST2"); - AppSkuInfo appSkuInfo = new AppSkuInfo().withName(appSku); - app.withSku(appSkuInfo); - - IotCentralClientImpl iotCentralClientImpl = new IotCentralClientImpl(restClient); - iotCentralClientImpl.withSubscriptionId(subscriptionId); - AppsInner appsInner = new AppsInner(restClient.retrofit(), iotCentralClientImpl); - - // create app - AppInner createdApp = appsInner.createOrUpdate(resourceGroupName, resourceName, app); - System.out.println("Newly created app id is " + createdApp.applicationId()); - - // get app - AppInner getResult = appsInner.getByResourceGroup(resourceGroupName, resourceName); - System.out.println("its sku is " + getResult.sku().name()); - - AppPatch appPatch = new AppPatch(); - appPatch.withDisplayName(resourceName + "-new-name"); - - // update app - appsInner.update(resourceGroupName, resourceName, appPatch); - - // list all the apps under the resource group - PagedList apps = appsInner.listByResourceGroup(resourceGroupName); - for(AppInner eachApp : apps) { - System.out.println(eachApp.displayName()); - } - - // list all the operations for iotc - OperationsInner operationsInner = new OperationsInner(restClient.retrofit(), iotCentralClientImpl); - PagedList operations = operationsInner.list(); - for(OperationInner eachOperation : operations) { - System.out.println(eachOperation.name()); - } - - // list all the app templates in iotc - PagedList appTemplates = appsInner.listTemplates(); - for(AppTemplateInner eachAppTemplate : appTemplates) { - System.out.println(eachAppTemplate.name()); - } - - // delete app - // appsInner.delete(resourceGroupName, resourceName); - } -} From 4f18505e74299c2089bd375170c39dbebe19f16a Mon Sep 17 00:00:00 2001 From: Ganesh Viswanathan Date: Wed, 10 Nov 2021 15:38:09 -0800 Subject: [PATCH 2/3] Minor: Updated link in readme.md Minor: Updated link in readme.md --- java/README.MD | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java/README.MD b/java/README.MD index 62e147b..5e3d391 100644 --- a/java/README.MD +++ b/java/README.MD @@ -8,7 +8,7 @@ Sample code for using [com.microsoft.azure.iotcentral.v2018_09_01:azure-mgmt-iot ### Prerequisites - [Java JDK or JRE](https://www.oracle.com/technetwork/java/javase/downloads/index.html) - [Maven](http://maven.apache.org/install.html) -- A service principal and a resource group to work with. Follow [these instructions](https://docs.microsoft.com/en-us/azure/active-directory/develop/howto-create-service-principal-portal). +- A service principal and a resource group to work with. Follow [these instructions](https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal). ### SDK version From 42e55877617883cfb5bd084a4a0766fd1f344177 Mon Sep 17 00:00:00 2001 From: Ganesh Viswanathan Date: Wed, 10 Nov 2021 15:43:18 -0800 Subject: [PATCH 3/3] Minor: Updated readme.md Minor: Updated readme.md --- java/README.MD | 1 - 1 file changed, 1 deletion(-) diff --git a/java/README.MD b/java/README.MD index 5e3d391..e02e576 100644 --- a/java/README.MD +++ b/java/README.MD @@ -1,7 +1,6 @@ # Azure IoT Central Java SDK Samples for Management APIs Sample code for using Azure IoT Central Management Plane APIs. -Sample code for using [com.microsoft.azure.iotcentral.v2018_09_01:azure-mgmt-iotcentral](https://search.maven.org/artifact/com.microsoft.azure.iotcentral.v2018_09_01/azure-mgmt-iotcentral/1.0.0/jar) SDK provided by [Microsoft Azure](https://github.com/Azure). This sample code will check if the resource name is available, create or update an app, retrieve app information, update app, list all the apps that belongs to the specific resource group, and finally delete the app if uncommented. ## Get started