diff --git a/azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/AvailabilitySet.java b/azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/AvailabilitySet.java index 462cce394cd7f..96505f5c5d1b8 100644 --- a/azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/AvailabilitySet.java +++ b/azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/AvailabilitySet.java @@ -13,6 +13,7 @@ import com.microsoft.azure.management.resources.fluentcore.model.Refreshable; import com.microsoft.azure.management.resources.fluentcore.model.Updatable; import com.microsoft.azure.management.resources.fluentcore.model.Wrapper; + import java.util.List; /** diff --git a/azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/implementation/AvailabilitySetsImpl.java b/azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/implementation/AvailabilitySetsImpl.java index 180f5f663df7d..3dc3ba7d7027b 100644 --- a/azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/implementation/AvailabilitySetsImpl.java +++ b/azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/implementation/AvailabilitySetsImpl.java @@ -36,7 +36,7 @@ class AvailabilitySetsImpl } @Override - public PagedList list() throws CloudException, IOException { + public PagedList list() throws RestException, IOException { return new GroupPagedList(this.myManager.resourceManager().resourceGroups().list()) { @Override public List listNextGroup(String resourceGroupName) throws RestException, IOException { diff --git a/azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/implementation/ChildListFlattener.java b/azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/implementation/ChildListFlattener.java index ea965b14feeb8..b095483da8409 100644 --- a/azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/implementation/ChildListFlattener.java +++ b/azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/implementation/ChildListFlattener.java @@ -17,10 +17,9 @@ * @param the type of child paged list item */ final class ChildListFlattener { - protected final String switchToCousin = "switchToCousin"; - protected Iterator parentItr; - protected PagedList currentChildList; - protected PagedList cousinList; + private final String switchToCousin = "switchToCousin"; + private Iterator parentItr; + private PagedList currentChildList; private final ChildListLoader childListLoader; /** @@ -67,52 +66,22 @@ public PagedList flatten() throws CloudException, IOException { if (this.currentChildList == null) { return emptyPagedList(); } - // setCousin sets the next child paged list (i.e. the current child list's immediate cousin). - // we need to know in advance whether there is going to be a next child paged list (cousin). - // This is because the 'next link' of the current child paged list's last page will be null. - // when the PagedList sees next link as null it assumes there is no more pages hence it won't - // call nextPage and iteration stops, if cousin presents then 'childListPage' method replace - // this null with a marker indicating there is more pages. - setCousin(); return new PagedList(childListPage(currentChildList.currentPage())) { @Override public Page nextPage(String nextPageLink) throws RestException, IOException { if (nextPageLink.equalsIgnoreCase(switchToCousin)) { // Reached end of current child paged list, make next child list(cousin) as current // paged list and return it's first page. - currentChildList = cousinList; - setCousin(); + currentChildList = nextChildList(); return childListPage(currentChildList.currentPage()); } else { currentChildList.loadNextPage(); - if (currentChildList.currentPage().getNextPageLink() == null) { - // This is the last page of the current child paged list set it's cousin - // so that next call to nextPage can start using it. - setCousin(); - } return childListPage(currentChildList.currentPage()); } } }; } - /** - * @return true if the current child paged list has a cousin - */ - private boolean hasCousin() { - return this.cousinList != null; - } - - /** - * Locate and sets the cousin list (the next child paged list). - * - * @throws CloudException exceptions thrown from the cloud - * @throws IOException exceptions thrown from serialization/deserialization - */ - private void setCousin() throws CloudException, IOException { - cousinList = nextChildList(); - } - /** * Returns the next child paged list containing at least one item. *

@@ -152,7 +121,7 @@ public String getNextPageLink() { return page.getNextPageLink(); } - if (hasCousin()) { + if (parentItr.hasNext()) { // The current child paged list has no more pages so switch to it's cousin list return switchToCousin; } diff --git a/azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/implementation/VirtualMachineImagesImpl.java b/azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/implementation/VirtualMachineImagesImpl.java index 48ee881798604..e23dcf587991e 100644 --- a/azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/implementation/VirtualMachineImagesImpl.java +++ b/azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/implementation/VirtualMachineImagesImpl.java @@ -2,13 +2,14 @@ import com.microsoft.azure.CloudException; import com.microsoft.azure.PagedList; +import com.microsoft.azure.management.compute.VirtualMachineImage; +import com.microsoft.azure.management.compute.VirtualMachineImages; import com.microsoft.azure.management.compute.VirtualMachineOffer; import com.microsoft.azure.management.compute.VirtualMachinePublisher; import com.microsoft.azure.management.compute.VirtualMachinePublishers; -import com.microsoft.azure.management.compute.VirtualMachineImage; -import com.microsoft.azure.management.compute.VirtualMachineImages; import com.microsoft.azure.management.compute.VirtualMachineSku; import com.microsoft.azure.management.resources.fluentcore.arm.Region; + import java.io.IOException; /** diff --git a/azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/implementation/VirtualMachineImagesInSkuImpl.java b/azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/implementation/VirtualMachineImagesInSkuImpl.java index 0883fb32b253c..28d2ecfbb5e83 100644 --- a/azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/implementation/VirtualMachineImagesInSkuImpl.java +++ b/azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/implementation/VirtualMachineImagesInSkuImpl.java @@ -1,6 +1,5 @@ package com.microsoft.azure.management.compute.implementation; -import com.microsoft.azure.CloudException; import com.microsoft.azure.Page; import com.microsoft.azure.PagedList; import com.microsoft.azure.management.compute.VirtualMachineImage; @@ -25,7 +24,7 @@ class VirtualMachineImagesInSkuImpl implements VirtualMachineImagesInSku { this.innerCollection = innerCollection; } - public PagedList list() throws CloudException, IOException { + public PagedList list() throws RestException, IOException { final List images = new ArrayList<>(); for (VirtualMachineImageResourceInner inner : innerCollection.list( diff --git a/azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/implementation/VirtualMachineSkusImpl.java b/azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/implementation/VirtualMachineSkusImpl.java index b672af42fb564..ec8e4e05310f7 100644 --- a/azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/implementation/VirtualMachineSkusImpl.java +++ b/azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/implementation/VirtualMachineSkusImpl.java @@ -5,12 +5,12 @@ */ package com.microsoft.azure.management.compute.implementation; -import com.microsoft.azure.CloudException; import com.microsoft.azure.PagedList; import com.microsoft.azure.management.compute.VirtualMachineOffer; import com.microsoft.azure.management.compute.VirtualMachineSkus; import com.microsoft.azure.management.compute.VirtualMachineSku; import com.microsoft.azure.management.resources.fluentcore.arm.collection.implementation.ReadableWrappersImpl; +import com.microsoft.rest.RestException; import java.io.IOException; @@ -30,7 +30,7 @@ class VirtualMachineSkusImpl } @Override - public PagedList list() throws CloudException, IOException { + public PagedList list() throws RestException, IOException { return wrapList(innerCollection.listSkus( offer.region().toString(), offer.publisher().name(), diff --git a/azure-mgmt-datalake-analytics/src/test/java/com/microsoft/azure/management/datalake/analytics/DataLakeAnalyticsManagementTestBase.java b/azure-mgmt-datalake-analytics/src/test/java/com/microsoft/azure/management/datalake/analytics/DataLakeAnalyticsManagementTestBase.java index a97e0f63e2816..3b6246c1b18cc 100644 --- a/azure-mgmt-datalake-analytics/src/test/java/com/microsoft/azure/management/datalake/analytics/DataLakeAnalyticsManagementTestBase.java +++ b/azure-mgmt-datalake-analytics/src/test/java/com/microsoft/azure/management/datalake/analytics/DataLakeAnalyticsManagementTestBase.java @@ -49,8 +49,8 @@ public static void createClients() { authEnv = new AzureEnvironment( "https://login.windows-ppe.net/", "https://management.core.windows.net/", - true, - "https://api-dogfood.resources.windows-int.net"); + "https://api-dogfood.resources.windows-int.net", + "https://graph.windows.net"); break; case "test": armUri = "https://api-dogfood.resources.windows-int.net"; @@ -59,8 +59,8 @@ public static void createClients() { authEnv = new AzureEnvironment( "https://login.windows-ppe.net/", "https://management.core.windows.net/", - true, - "https://api-dogfood.resources.windows-int.net"); + "https://api-dogfood.resources.windows-int.net", + "https://graph.windows.net"); break; default: // default to production armUri = "https://management.azure.com"; @@ -74,7 +74,6 @@ public static void createClients() { System.getenv("arm.domain"), System.getenv("arm.username"), System.getenv("arm.password"), - null, authEnv); RestClient restClient = new RestClient.Builder() diff --git a/azure-mgmt-datalake-store-uploader/src/test/java/com/microsoft/azure/management/datalake/store/uploader/DataLakeUploaderTestBase.java b/azure-mgmt-datalake-store-uploader/src/test/java/com/microsoft/azure/management/datalake/store/uploader/DataLakeUploaderTestBase.java index 38447a18f2597..24954721e8667 100644 --- a/azure-mgmt-datalake-store-uploader/src/test/java/com/microsoft/azure/management/datalake/store/uploader/DataLakeUploaderTestBase.java +++ b/azure-mgmt-datalake-store-uploader/src/test/java/com/microsoft/azure/management/datalake/store/uploader/DataLakeUploaderTestBase.java @@ -28,7 +28,6 @@ public static void createClients() { System.getenv("arm.domain"), System.getenv("arm.username"), System.getenv("arm.password"), - null, AzureEnvironment.AZURE); RestClient restClient = new RestClient.Builder() diff --git a/azure-mgmt-datalake-store/src/test/java/com/microsoft/azure/management/datalake/store/DataLakeStoreManagementTestBase.java b/azure-mgmt-datalake-store/src/test/java/com/microsoft/azure/management/datalake/store/DataLakeStoreManagementTestBase.java index ae8c934c769c1..0fca86a3de9b0 100644 --- a/azure-mgmt-datalake-store/src/test/java/com/microsoft/azure/management/datalake/store/DataLakeStoreManagementTestBase.java +++ b/azure-mgmt-datalake-store/src/test/java/com/microsoft/azure/management/datalake/store/DataLakeStoreManagementTestBase.java @@ -19,7 +19,6 @@ public static void createClients() { System.getenv("arm.domain"), System.getenv("arm.username"), System.getenv("arm.password"), - null, AzureEnvironment.AZURE); RestClient restClient = new RestClient.Builder() diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/ActiveDirectoryGroup.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/ActiveDirectoryGroup.java new file mode 100644 index 0000000000000..c7ec7af4cd3ff --- /dev/null +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/ActiveDirectoryGroup.java @@ -0,0 +1,114 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + */ + +package com.microsoft.azure.management.graphrbac; + +import com.microsoft.azure.management.graphrbac.implementation.ADGroupInner; +import com.microsoft.azure.management.resources.fluentcore.model.Creatable; +import com.microsoft.azure.management.resources.fluentcore.model.Wrapper; + +/** + * An immutable client-side representation of an Azure AD group. + */ +public interface ActiveDirectoryGroup extends + Wrapper { + /** + * @return object Id. + */ + String objectId(); + + /** + * @return object type. + */ + String objectType(); + + /** + * @return group display name. + */ + String displayName(); + + /** + * @return security enabled field. + */ + Boolean securityEnabled(); + + /** + * @return mail field. + */ + String mail(); + + /************************************************************** + * Fluent interfaces to provision a Group + **************************************************************/ + + /** + * Container interface for all the definitions that need to be implemented. + */ + interface Definition extends + DefinitionStages.Blank, + DefinitionStages.WithDisplayName, + DefinitionStages.WithMailNickname, + DefinitionStages.WithCreate { + } + + /** + * Grouping of all the group definition stages. + */ + interface DefinitionStages { + /** + * The first stage of the group definition. + */ + interface Blank extends WithDisplayName { + } + + /** + * The stage of group definition allowing display name to be specified. + */ + interface WithDisplayName { + /** + * Specifies the display name of the group. + * + * @param displayName the human readable display name + * @return the next stage of group definition + */ + WithMailNickname withDisplayName(String displayName); + } + + /** + * The stage of group definition allowing mail nickname to be specified. + */ + interface WithMailNickname { + /** + * Specifies the mail nickname of the group. + * + * @param mailNickname the mail nickname for the group + * @return the next stage of group definition + */ + WithCreate withMailNickname(String mailNickname); + } + + /** + * An AD group definition with sufficient inputs to create a new + * group in the cloud, but exposing additional optional inputs to + * specify. + */ + interface WithCreate extends + Creatable { + } + } + + /** + * Grouping of all the group update stages. + */ + interface UpdateStages { + } + + /** + * The template for a group update operation, containing all the settings that can be modified. + */ + interface Update { + } +} diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/GraphError.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/GraphError.java new file mode 100644 index 0000000000000..033bb358f3d53 --- /dev/null +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/GraphError.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.graphrbac; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.rest.serializer.JsonFlatten; + +/** + * Active Directory error information. + */ +@JsonFlatten +public class GraphError { + /** + * Error code. + */ + @JsonProperty(value = "odata\\.error.code") + private String code; + + /** + * Error message value. + */ + @JsonProperty(value = "odata\\.error.message.value") + private String message; + + /** + * Get the code value. + * + * @return the code value + */ + public String code() { + return this.code; + } + + /** + * Set the code value. + * + * @param code the code value to set + * @return the GraphError object itself. + */ + public GraphError withCode(String code) { + this.code = code; + return this; + } + + /** + * Get the message value. + * + * @return the message value + */ + public String message() { + return this.message; + } + + /** + * Set the message value. + * + * @param message the message value to set + * @return the GraphError object itself. + */ + public GraphError withMessage(String message) { + this.message = message; + return this; + } + +} diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/GraphErrorException.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/GraphErrorException.java new file mode 100644 index 0000000000000..e6b4aeeeecb85 --- /dev/null +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/GraphErrorException.java @@ -0,0 +1,87 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.graphrbac; + +import com.microsoft.rest.RestException; +import retrofit2.Response; + +/** + * Exception thrown for an invalid response with GraphError information. + */ +public class GraphErrorException extends RestException { + /** + * Information about the associated HTTP response. + */ + private Response response; + /** + * The actual response body. + */ + private GraphError body; + /** + * Initializes a new instance of the GraphErrorException class. + */ + public GraphErrorException() { } + /** + * Initializes a new instance of the GraphErrorException class. + * + * @param message The exception message. + */ + public GraphErrorException(final String message) { + super(message); + } + /** + * Initializes a new instance of the GraphErrorException class. + * + * @param message the exception message + * @param cause exception that caused this exception to occur + */ + public GraphErrorException(final String message, final Throwable cause) { + super(message, cause); + } + /** + * Initializes a new instance of the GraphErrorException class. + * + * @param cause exception that caused this exception to occur + */ + public GraphErrorException(final Throwable cause) { + super(cause); + } + /** + * Gets information about the associated HTTP response. + * + * @return the HTTP response + */ + public Response getResponse() { + return response; + } + /** + * Gets the HTTP response body. + * + * @return the response body + */ + public GraphError getBody() { + return body; + } + /** + * Sets the HTTP response. + * + * @param response the HTTP response + */ + public void setResponse(Response response) { + this.response = response; + } + /** + * Sets the HTTP response body. + * + * @param body the response body + */ + public void setBody(GraphError body) { + this.body = body; + } +} diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/Groups.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/Groups.java new file mode 100644 index 0000000000000..c8844b3e9d0b1 --- /dev/null +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/Groups.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + */ + +package com.microsoft.azure.management.graphrbac; + +import com.microsoft.azure.CloudException; +import com.microsoft.azure.management.resources.fluentcore.collection.SupportsCreating; +import com.microsoft.azure.management.resources.fluentcore.collection.SupportsDeleting; +import com.microsoft.azure.management.resources.fluentcore.collection.SupportsListing; + +import java.io.IOException; +import java.util.List; + +/** + * Entry point to AD group management API. + */ +public interface Groups extends + SupportsCreating, + SupportsListing, + SupportsDeleting { + /** + * Gets the information about a group. + * + * @param objectId the unique object id + * @return an immutable representation of the resource + * @throws CloudException exceptions thrown from the cloud + * @throws IOException exceptions thrown from serialization/deserialization + */ + ActiveDirectoryGroup getByObjectId(String objectId) throws CloudException, IOException; + + /** + * Gets the information about a group. + * + * @param displayNamePrefix the partial prefix of the display name to search + * @return an immutable representation of the resource + * @throws CloudException exceptions thrown from the cloud + * @throws IOException exceptions thrown from serialization/deserialization + */ + List searchByDisplayName(String displayNamePrefix) throws CloudException, IOException; +} diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/KeyCredentialsUpdateParameters.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/KeyCredentialsUpdateParameters.java new file mode 100644 index 0000000000000..9fd5ff8b29f5d --- /dev/null +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/KeyCredentialsUpdateParameters.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.graphrbac; + +import java.util.List; +import com.microsoft.azure.management.graphrbac.implementation.KeyCredentialInner; + +/** + * Request parameters for KeyCredentials update operation. + */ +public class KeyCredentialsUpdateParameters { + /** + * KeyCredential list. + */ + private List value; + + /** + * Get the value value. + * + * @return the value value + */ + public List value() { + return this.value; + } + + /** + * Set the value value. + * + * @param value the value value to set + * @return the KeyCredentialsUpdateParameters object itself. + */ + public KeyCredentialsUpdateParameters withValue(List value) { + this.value = value; + return this; + } + +} diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/PasswordCredentialsUpdateParameters.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/PasswordCredentialsUpdateParameters.java new file mode 100644 index 0000000000000..adc5d0ccec51f --- /dev/null +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/PasswordCredentialsUpdateParameters.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.graphrbac; + +import java.util.List; +import com.microsoft.azure.management.graphrbac.implementation.PasswordCredentialInner; + +/** + * Request paramters for PasswordCredentials update operation. + */ +public class PasswordCredentialsUpdateParameters { + /** + * PasswordCredential list. + */ + private List value; + + /** + * Get the value value. + * + * @return the value value + */ + public List value() { + return this.value; + } + + /** + * Set the value value. + * + * @param value the value value to set + * @return the PasswordCredentialsUpdateParameters object itself. + */ + public PasswordCredentialsUpdateParameters withValue(List value) { + this.value = value; + return this; + } + +} diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/ServicePrincipal.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/ServicePrincipal.java index 08fb88f510a88..5d0a609ee0a0d 100644 --- a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/ServicePrincipal.java +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/ServicePrincipal.java @@ -13,11 +13,10 @@ import java.util.List; /** - * An immutable client-side representation of an Azure tenant. + * An immutable client-side representation of an Azure AD service principal. */ public interface ServicePrincipal extends Wrapper { - /** * @return object Id. */ @@ -56,22 +55,31 @@ interface Definition extends } /** - * Grouping of all the storage account definition stages. + * Grouping of all the service principal definition stages. */ interface DefinitionStages { /** - * The first stage of the storage account definition. + * The first stage of the service principal definition. */ interface Blank extends WithCreate { } + /** + * The stage of service principal definition allowing specifying if the service principal account is enabled. + */ interface WithAccountEnabled { + /** + * Specifies whether the service principal account is enabled upon creation. + * + * @param enabled if set to true, the service principal account is enabled. + * @return the next stage in service principal definition + */ WithCreate withAccountEnabled(boolean enabled); } /** - * A storage account definition with sufficient inputs to create a new - * storage account in the cloud, but exposing additional optional inputs to + * A service principal definition with sufficient inputs to create a new + * service principal in the cloud, but exposing additional optional inputs to * specify. */ interface WithCreate extends @@ -81,13 +89,13 @@ interface WithCreate extends } /** - * Grouping of all the storage account update stages. + * Grouping of all the service principal update stages. */ interface UpdateStages { } /** - * The template for a storage account update operation, containing all the settings that can be modified. + * The template for a service principal update operation, containing all the settings that can be modified. */ interface Update { } diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/ServicePrincipals.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/ServicePrincipals.java index 3084db1c6e79e..f9c2a80eecd3b 100644 --- a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/ServicePrincipals.java +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/ServicePrincipals.java @@ -6,17 +6,66 @@ package com.microsoft.azure.management.graphrbac; -import com.microsoft.azure.management.resources.fluentcore.arm.collection.SupportsGettingByName; import com.microsoft.azure.management.resources.fluentcore.collection.SupportsCreating; import com.microsoft.azure.management.resources.fluentcore.collection.SupportsDeleting; import com.microsoft.azure.management.resources.fluentcore.collection.SupportsListing; +import com.microsoft.rest.ServiceCall; +import com.microsoft.rest.ServiceCallback; +import rx.Observable; + +import java.io.IOException; /** - * Entry point to tenant management API. + * Entry point to service principal management API. */ public interface ServicePrincipals extends SupportsCreating, SupportsListing, - SupportsGettingByName, SupportsDeleting { + /** + * Gets the information about a service principal. + * + * @param objectId the unique object id + * @return an immutable representation of the resource + * @throws GraphErrorException exceptions thrown from the graph API + * @throws IOException exceptions thrown from serialization/deserialization + */ + ServicePrincipal getByObjectId(String objectId) throws GraphErrorException, IOException; + + /** + * Gets the information about a service principal. + * + * @param appId the application id (or the client id) + * @return an immutable representation of the resource + * @throws GraphErrorException exceptions thrown from the graph API + * @throws IOException exceptions thrown from serialization/deserialization + */ + ServicePrincipal getByAppId(String appId) throws GraphErrorException, IOException; + + /** + * Gets the information about a service principal. + * + * @param spn the service principal name + * @return an immutable representation of the resource + * @throws GraphErrorException exceptions thrown from the graph API + * @throws IOException exceptions thrown from serialization/deserialization + */ + ServicePrincipal getByServicePrincipalName(String spn) throws GraphErrorException, IOException; + + /** + * Gets the information about a service principal. + * + * @param spn the service principal name + * @param callback the call back to handle response + * @return the Future based service call + */ + ServiceCall getByServicePrincipalNameAsync(String spn, final ServiceCallback callback); + + /** + * Gets the information about a service principal. + * + * @param spn the service principal name + * @return the Observable to the request + */ + Observable getByServicePrincipalNameAsync(String spn); } diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/User.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/User.java index e277dec590c80..45c0b50bf3f89 100644 --- a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/User.java +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/User.java @@ -11,7 +11,7 @@ import com.microsoft.azure.management.resources.fluentcore.model.Wrapper; /** - * An immutable client-side representation of an Azure tenant. + * An immutable client-side representation of an Azure AD user. */ public interface User extends Wrapper { @@ -52,7 +52,7 @@ public interface User extends String mailNickname(); /************************************************************** - * Fluent interfaces to provision a StorageAccount + * Fluent interfaces to provision a User **************************************************************/ /** @@ -67,35 +67,79 @@ interface Definition extends } /** - * Grouping of all the storage account definition stages. + * Grouping of all the user definition stages. */ interface DefinitionStages { /** - * The first stage of the storage account definition. + * The first stage of the user definition. */ interface Blank extends WithDisplayName { } + /** + * The stage of a user definition allowing display name to be set. + */ interface WithDisplayName { + /** + * Specifies the display name of the user. + * + * @param displayName the human-readable display name + * @return the next stage of a user definition + */ WithPassword withDisplayName(String displayName); } + /** + * The stage of a user definition allowing password to be set. + */ interface WithPassword { + /** + * Specifies the password for the user. + * + * @param password the password + * @return the next stage for a user definition + */ WithMailNickname withPassword(String password); + + /** + * Specifies the temporary password for the user. + * + * @param password the temporary password + * @param forceChangePasswordNextLogin if set to true, the user will have to change the password next time + * @return the next stage for a user definition + */ WithMailNickname withPassword(String password, boolean forceChangePasswordNextLogin); } + /** + * The stage of a user definition allowing mail nickname to be specified. + */ interface WithMailNickname { + /** + * Specifies the mail nickname for the user. + * + * @param mailNickname the mail nickname + * @return the next stage for a user definition + */ WithCreate withMailNickname(String mailNickname); } + /** + * The stage of a user definition allowing specifying if the account is enabled. + */ interface WithAccountEnabled { + /** + * Specifies if the user account is enabled upon creation. + * + * @param enabled if set to true, the user account is enabled + * @return the next stage for a user definition + */ WithCreate withAccountEnabled(boolean enabled); } /** - * A storage account definition with sufficient inputs to create a new - * storage account in the cloud, but exposing additional optional inputs to + * An AD user definition with sufficient inputs to create a new + * user in the cloud, but exposing additional optional inputs to * specify. */ interface WithCreate extends @@ -105,13 +149,13 @@ interface WithCreate extends } /** - * Grouping of all the storage account update stages. + * Grouping of all the user update stages. */ interface UpdateStages { } /** - * The template for a storage account update operation, containing all the settings that can be modified. + * The template for a user update operation, containing all the settings that can be modified. */ interface Update { } diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/Users.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/Users.java index 832ffb2bcdbf3..bce73bb9aaed0 100644 --- a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/Users.java +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/Users.java @@ -6,17 +6,56 @@ package com.microsoft.azure.management.graphrbac; -import com.microsoft.azure.management.resources.fluentcore.arm.collection.SupportsGettingByName; import com.microsoft.azure.management.resources.fluentcore.collection.SupportsCreating; import com.microsoft.azure.management.resources.fluentcore.collection.SupportsDeleting; import com.microsoft.azure.management.resources.fluentcore.collection.SupportsListing; +import com.microsoft.rest.ServiceCall; +import com.microsoft.rest.ServiceCallback; +import rx.Observable; + +import java.io.IOException; /** - * Entry point to tenant management API. + * Entry point to AD user management API. */ public interface Users extends SupportsCreating, SupportsListing, - SupportsGettingByName, SupportsDeleting { + /** + * Gets the information about a user. + * + * @param objectId the unique object id + * @return an immutable representation of the resource + * @throws GraphErrorException exceptions thrown from the graph API + * @throws IOException exceptions thrown from serialization/deserialization + */ + User getByObjectId(String objectId) throws GraphErrorException, IOException; + + /** + * Gets the information about a user. + * + * @param upn the user principal name + * @return an immutable representation of the resource + * @throws GraphErrorException exceptions thrown from the graph API + * @throws IOException exceptions thrown from serialization/deserialization + */ + User getByUserPrincipalName(String upn) throws GraphErrorException, IOException; + + /** + * Gets the information about a user. + * + * @param upn the user principal name + * @param callback the callback to handle the response + * @return an Future based service call + */ + ServiceCall getByUserPrincipalNameAsync(String upn, ServiceCallback callback); + + /** + * Gets the information about a user. + * + * @param upn the user principal name + * @return an Future based service call + */ + Observable getByUserPrincipalNameAsync(String upn); } diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/AADObjectInner.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/AADObjectInner.java index 87922b8c92fdf..79a109bb42d7f 100644 --- a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/AADObjectInner.java +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/AADObjectInner.java @@ -15,52 +15,52 @@ */ public class AADObjectInner { /** - * Gets or sets object Id. + * object Id. */ private String objectId; /** - * Gets or sets object type. + * object type. */ private String objectType; /** - * Gets or sets object display name. + * object display name. */ private String displayName; /** - * Gets or sets principal name. + * principal name. */ private String userPrincipalName; /** - * Gets or sets mail. + * mail. */ private String mail; /** - * Gets or sets MailEnabled field. + * MailEnabled field. */ private Boolean mailEnabled; /** - * Gets or sets SecurityEnabled field. + * SecurityEnabled field. */ private Boolean securityEnabled; /** - * Gets or sets signIn name. + * signIn name. */ private String signInName; /** - * Gets or sets the list of service principal names. + * the list of service principal names. */ private List servicePrincipalNames; /** - * Gets or sets the user type. + * the user type. */ private String userType; diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ADGroupInner.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ADGroupInner.java index d2fd0568b922b..b5108f421d703 100644 --- a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ADGroupInner.java +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ADGroupInner.java @@ -14,27 +14,27 @@ */ public class ADGroupInner { /** - * Gets or sets object Id. + * object Id. */ private String objectId; /** - * Gets or sets object type. + * object type. */ private String objectType; /** - * Gets or sets group display name. + * group display name. */ private String displayName; /** - * Gets or sets security enabled field. + * security enabled field. */ private Boolean securityEnabled; /** - * Gets or sets mail field. + * mail field. */ private String mail; diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ApplicationCreateParametersInner.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ApplicationCreateParametersInner.java index 334e0768005ba..ac996c9c89fa1 100644 --- a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ApplicationCreateParametersInner.java +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ApplicationCreateParametersInner.java @@ -9,8 +9,6 @@ package com.microsoft.azure.management.graphrbac.implementation; import java.util.List; -import com.microsoft.azure.management.graphrbac.KeyCredential; -import com.microsoft.azure.management.graphrbac.PasswordCredential; import com.fasterxml.jackson.annotation.JsonProperty; /** @@ -32,7 +30,6 @@ public class ApplicationCreateParametersInner { /** * Application homepage. */ - @JsonProperty(required = true) private String homepage; /** @@ -47,14 +44,14 @@ public class ApplicationCreateParametersInner { private List replyUrls; /** - * Gets or sets the list of KeyCredential objects. + * the list of KeyCredential objects. */ - private List keyCredentials; + private List keyCredentials; /** - * Gets or sets the list of PasswordCredential objects. + * the list of PasswordCredential objects. */ - private List passwordCredentials; + private List passwordCredentials; /** * Get the availableToOtherTenants value. @@ -161,7 +158,7 @@ public ApplicationCreateParametersInner withReplyUrls(List replyUrls) { * * @return the keyCredentials value */ - public List keyCredentials() { + public List keyCredentials() { return this.keyCredentials; } @@ -171,7 +168,7 @@ public List keyCredentials() { * @param keyCredentials the keyCredentials value to set * @return the ApplicationCreateParametersInner object itself. */ - public ApplicationCreateParametersInner withKeyCredentials(List keyCredentials) { + public ApplicationCreateParametersInner withKeyCredentials(List keyCredentials) { this.keyCredentials = keyCredentials; return this; } @@ -181,7 +178,7 @@ public ApplicationCreateParametersInner withKeyCredentials(List k * * @return the passwordCredentials value */ - public List passwordCredentials() { + public List passwordCredentials() { return this.passwordCredentials; } @@ -191,7 +188,7 @@ public List passwordCredentials() { * @param passwordCredentials the passwordCredentials value to set * @return the ApplicationCreateParametersInner object itself. */ - public ApplicationCreateParametersInner withPasswordCredentials(List passwordCredentials) { + public ApplicationCreateParametersInner withPasswordCredentials(List passwordCredentials) { this.passwordCredentials = passwordCredentials; return this; } diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ApplicationInner.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ApplicationInner.java index 1e4259ec221d1..443db8cdc1d1d 100644 --- a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ApplicationInner.java +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ApplicationInner.java @@ -15,22 +15,22 @@ */ public class ApplicationInner { /** - * Gets or sets object Id. + * object Id. */ private String objectId; /** - * Gets or sets object type. + * object type. */ private String objectType; /** - * Gets or sets application Id. + * application Id. */ private String appId; /** - * Gets or sets application permissions. + * application permissions. */ private List appPermissions; @@ -40,17 +40,17 @@ public class ApplicationInner { private Boolean availableToOtherTenants; /** - * Gets or sets the displayName. + * the displayName. */ private String displayName; /** - * Gets or sets the application identifier Uris. + * the application identifier Uris. */ private List identifierUris; /** - * Gets or sets the application reply Urls. + * the application reply Urls. */ private List replyUrls; diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ApplicationUpdateParametersInner.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ApplicationUpdateParametersInner.java index ea7d6deeb6629..759d2d37df6d1 100644 --- a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ApplicationUpdateParametersInner.java +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ApplicationUpdateParametersInner.java @@ -9,13 +9,16 @@ package com.microsoft.azure.management.graphrbac.implementation; import java.util.List; -import com.microsoft.azure.management.graphrbac.KeyCredential; -import com.microsoft.azure.management.graphrbac.PasswordCredential; /** * Request parameters for updating an existing application. */ public class ApplicationUpdateParametersInner { + /** + * Indicates if the application will be available to other tenants. + */ + private Boolean availableToOtherTenants; + /** * Application display name. */ @@ -37,14 +40,34 @@ public class ApplicationUpdateParametersInner { private List replyUrls; /** - * Gets or sets the list of KeyCredential objects. + * the list of KeyCredential objects. + */ + private List keyCredentials; + + /** + * the list of PasswordCredential objects. */ - private List keyCredentials; + private List passwordCredentials; /** - * Gets or sets the list of PasswordCredential objects. + * Get the availableToOtherTenants value. + * + * @return the availableToOtherTenants value */ - private List passwordCredentials; + public Boolean availableToOtherTenants() { + return this.availableToOtherTenants; + } + + /** + * Set the availableToOtherTenants value. + * + * @param availableToOtherTenants the availableToOtherTenants value to set + * @return the ApplicationUpdateParametersInner object itself. + */ + public ApplicationUpdateParametersInner withAvailableToOtherTenants(Boolean availableToOtherTenants) { + this.availableToOtherTenants = availableToOtherTenants; + return this; + } /** * Get the displayName value. @@ -131,7 +154,7 @@ public ApplicationUpdateParametersInner withReplyUrls(List replyUrls) { * * @return the keyCredentials value */ - public List keyCredentials() { + public List keyCredentials() { return this.keyCredentials; } @@ -141,7 +164,7 @@ public List keyCredentials() { * @param keyCredentials the keyCredentials value to set * @return the ApplicationUpdateParametersInner object itself. */ - public ApplicationUpdateParametersInner withKeyCredentials(List keyCredentials) { + public ApplicationUpdateParametersInner withKeyCredentials(List keyCredentials) { this.keyCredentials = keyCredentials; return this; } @@ -151,7 +174,7 @@ public ApplicationUpdateParametersInner withKeyCredentials(List k * * @return the passwordCredentials value */ - public List passwordCredentials() { + public List passwordCredentials() { return this.passwordCredentials; } @@ -161,7 +184,7 @@ public List passwordCredentials() { * @param passwordCredentials the passwordCredentials value to set * @return the ApplicationUpdateParametersInner object itself. */ - public ApplicationUpdateParametersInner withPasswordCredentials(List passwordCredentials) { + public ApplicationUpdateParametersInner withPasswordCredentials(List passwordCredentials) { this.passwordCredentials = passwordCredentials; return this; } diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ApplicationsInner.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ApplicationsInner.java index 9c6b519e4ea39..d77097b6d262b 100644 --- a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ApplicationsInner.java +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ApplicationsInner.java @@ -11,16 +11,16 @@ import retrofit2.Retrofit; import com.google.common.reflect.TypeToken; import com.microsoft.azure.AzureServiceResponseBuilder; -import com.microsoft.azure.CloudException; +import com.microsoft.azure.management.graphrbac.GraphErrorException; +import com.microsoft.azure.management.graphrbac.KeyCredentialsUpdateParameters; +import com.microsoft.azure.management.graphrbac.PasswordCredentialsUpdateParameters; import com.microsoft.rest.ServiceCall; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceResponse; -import com.microsoft.rest.ServiceResponseCallback; import com.microsoft.rest.Validator; import java.io.IOException; import java.util.List; import okhttp3.ResponseBody; -import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.Header; @@ -31,6 +31,8 @@ import retrofit2.http.POST; import retrofit2.http.Query; import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; /** * An instance of this class provides access to all the operations defined @@ -60,23 +62,39 @@ public ApplicationsInner(Retrofit retrofit, GraphRbacManagementClientImpl client interface ApplicationsService { @Headers("Content-Type: application/json; charset=utf-8") @POST("{tenantID}/applications") - Call create(@Path("tenantID") String tenantID, @Body ApplicationCreateParametersInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> create(@Path("tenantID") String tenantID, @Body ApplicationCreateParametersInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("{tenantID}/applications") - Call list(@Path("tenantID") String tenantID, @Query("$filter") String filter, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> list(@Path("tenantID") String tenantID, @Query("$filter") String filter, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @HTTP(path = "{tenantID}/applications/{applicationObjectId}", method = "DELETE", hasBody = true) - Call delete(@Path(value = "applicationObjectId", encoded = true) String applicationObjectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> delete(@Path(value = "applicationObjectId", encoded = true) String applicationObjectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("{tenantID}/applications/{applicationObjectId}") - Call get(@Path(value = "applicationObjectId", encoded = true) String applicationObjectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> get(@Path(value = "applicationObjectId", encoded = true) String applicationObjectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @PATCH("{tenantID}/applications/{applicationObjectId}") - Call patch(@Path(value = "applicationObjectId", encoded = true) String applicationObjectId, @Path("tenantID") String tenantID, @Body ApplicationUpdateParametersInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> patch(@Path(value = "applicationObjectId", encoded = true) String applicationObjectId, @Path("tenantID") String tenantID, @Body ApplicationUpdateParametersInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers("Content-Type: application/json; charset=utf-8") + @GET("{tenantID}/applications/{applicationObjectId}/keyCredentials") + Observable> listKeyCredentials(@Path(value = "applicationObjectId", encoded = true) String applicationObjectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers("Content-Type: application/json; charset=utf-8") + @PATCH("{tenantID}/applications/{applicationObjectId}/keyCredentials") + Observable> updateKeyCredentials(@Path(value = "applicationObjectId", encoded = true) String applicationObjectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body KeyCredentialsUpdateParameters parameters, @Header("User-Agent") String userAgent); + + @Headers("Content-Type: application/json; charset=utf-8") + @GET("{tenantID}/applications/{applicationObjectId}/passwordCredentials") + Observable> listPasswordCredentials(@Path(value = "applicationObjectId", encoded = true) String applicationObjectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers("Content-Type: application/json; charset=utf-8") + @PATCH("{tenantID}/applications/{applicationObjectId}/passwordCredentials") + Observable> updatePasswordCredentials(@Path(value = "applicationObjectId", encoded = true) String applicationObjectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body PasswordCredentialsUpdateParameters parameters, @Header("User-Agent") String userAgent); } @@ -84,24 +102,13 @@ interface ApplicationsService { * Create a new application. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. * * @param parameters Parameters to create an application. - * @throws CloudException exception thrown from REST call + * @throws GraphErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the ApplicationInner object wrapped in {@link ServiceResponse} if successful. + * @return the ApplicationInner object if successful. */ - public ServiceResponse create(ApplicationCreateParametersInner parameters) throws CloudException, IOException, IllegalArgumentException { - if (this.client.tenantID() == null) { - throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); - } - if (parameters == null) { - throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - Validator.validate(parameters); - Call call = service.create(this.client.tenantID(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - return createDelegate(call.execute()); + public ApplicationInner create(ApplicationCreateParametersInner parameters) throws GraphErrorException, IOException, IllegalArgumentException { + return createWithServiceResponseAsync(parameters).toBlocking().single().getBody(); } /** @@ -109,57 +116,107 @@ public ServiceResponse create(ApplicationCreateParametersInner * * @param parameters Parameters to create an application. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall createAsync(ApplicationCreateParametersInner parameters, final ServiceCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall createAsync(ApplicationCreateParametersInner parameters, final ServiceCallback serviceCallback) { + return ServiceCall.create(createWithServiceResponseAsync(parameters), serviceCallback); + } + + /** + * Create a new application. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. + * + * @param parameters Parameters to create an application. + * @return the observable to the ApplicationInner object + */ + public Observable createAsync(ApplicationCreateParametersInner parameters) { + return createWithServiceResponseAsync(parameters).map(new Func1, ApplicationInner>() { + @Override + public ApplicationInner call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Create a new application. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. + * + * @param parameters Parameters to create an application. + * @return the observable to the ApplicationInner object + */ + public Observable> createWithServiceResponseAsync(ApplicationCreateParametersInner parameters) { if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (parameters == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter parameters is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Validator.validate(parameters, serviceCallback); - Call call = service.create(this.client.tenantID(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - serviceCallback.success(createDelegate(response)); - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); + Validator.validate(parameters); + return service.create(this.client.tenantID(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = createDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } } - } - }); - return serviceCall; + }); } - private ServiceResponse createDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return new AzureServiceResponseBuilder(this.client.mapperAdapter()) + private ServiceResponse createDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder(this.client.mapperAdapter()) .register(201, new TypeToken() { }.getType()) - .registerError(CloudException.class) + .registerError(GraphErrorException.class) .build(response); } /** * Lists applications by filter parameters. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. * - * @throws CloudException exception thrown from REST call + * @throws GraphErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<ApplicationInner> object wrapped in {@link ServiceResponse} if successful. + * @return the List<ApplicationInner> object if successful. + */ + public List list() throws GraphErrorException, IOException, IllegalArgumentException { + return listWithServiceResponseAsync().toBlocking().single().getBody(); + } + + /** + * Lists applications by filter parameters. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceCall} object + */ + public ServiceCall> listAsync(final ServiceCallback> serviceCallback) { + return ServiceCall.create(listWithServiceResponseAsync(), serviceCallback); + } + + /** + * Lists applications by filter parameters. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. + * + * @return the observable to the List<ApplicationInner> object + */ + public Observable> listAsync() { + return listWithServiceResponseAsync().map(new Func1>, List>() { + @Override + public List call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * Lists applications by filter parameters. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. + * + * @return the observable to the List<ApplicationInner> object */ - public ServiceResponse> list() throws CloudException, IOException, IllegalArgumentException { + public Observable>> listWithServiceResponseAsync() { if (this.client.tenantID() == null) { throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } @@ -167,191 +224,451 @@ public ServiceResponse> list() throws CloudException, IOE throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } final String filter = null; - Call call = service.list(this.client.tenantID(), filter, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - ServiceResponse> response = listDelegate(call.execute()); - List result = response.getBody().getItems(); - return new ServiceResponse<>(result, response.getResponse()); + return service.list(this.client.tenantID(), filter, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + ServiceResponse> clientResponse = new ServiceResponse>(result.getBody().getItems(), result.getResponse()); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); } /** * Lists applications by filter parameters. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. * + * @param filter The filters to apply on the operation + * @throws GraphErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the List<ApplicationInner> object if successful. + */ + public List list(String filter) throws GraphErrorException, IOException, IllegalArgumentException { + return listWithServiceResponseAsync(filter).toBlocking().single().getBody(); + } + + /** + * Lists applications by filter parameters. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. + * + * @param filter The filters to apply on the operation * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall listAsync(final ServiceCallback> serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } - if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; - } - if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; - } - final String filter = null; - Call call = service.list(this.client.tenantID(), filter, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCallback) { + public ServiceCall> listAsync(String filter, final ServiceCallback> serviceCallback) { + return ServiceCall.create(listWithServiceResponseAsync(filter), serviceCallback); + } + + /** + * Lists applications by filter parameters. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. + * + * @param filter The filters to apply on the operation + * @return the observable to the List<ApplicationInner> object + */ + public Observable> listAsync(String filter) { + return listWithServiceResponseAsync(filter).map(new Func1>, List>() { @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = listDelegate(response); - serviceCallback.success(new ServiceResponse<>(result.getBody().getItems(), result.getResponse())); - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); - } + public List call(ServiceResponse> response) { + return response.getBody(); } }); - return serviceCall; } /** * Lists applications by filter parameters. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. * * @param filter The filters to apply on the operation - * @throws CloudException exception thrown from REST call - * @throws IOException exception thrown from serialization/deserialization - * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<ApplicationInner> object wrapped in {@link ServiceResponse} if successful. + * @return the observable to the List<ApplicationInner> object */ - public ServiceResponse> list(String filter) throws CloudException, IOException, IllegalArgumentException { + public Observable>> listWithServiceResponseAsync(String filter) { if (this.client.tenantID() == null) { throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Call call = service.list(this.client.tenantID(), filter, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - ServiceResponse> response = listDelegate(call.execute()); - List result = response.getBody().getItems(); - return new ServiceResponse<>(result, response.getResponse()); + return service.list(this.client.tenantID(), filter, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + ServiceResponse> clientResponse = new ServiceResponse>(result.getBody().getItems(), result.getResponse()); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder, GraphErrorException>(this.client.mapperAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(GraphErrorException.class) + .build(response); } /** - * Lists applications by filter parameters. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. + * Delete an application. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. * - * @param filter The filters to apply on the operation + * @param applicationObjectId Application object id + * @throws GraphErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + */ + public void delete(String applicationObjectId) throws GraphErrorException, IOException, IllegalArgumentException { + deleteWithServiceResponseAsync(applicationObjectId).toBlocking().single().getBody(); + } + + /** + * Delete an application. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. + * + * @param applicationObjectId Application object id * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object + */ + public ServiceCall deleteAsync(String applicationObjectId, final ServiceCallback serviceCallback) { + return ServiceCall.create(deleteWithServiceResponseAsync(applicationObjectId), serviceCallback); + } + + /** + * Delete an application. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. + * + * @param applicationObjectId Application object id + * @return the {@link ServiceResponse} object if successful. */ - public ServiceCall listAsync(String filter, final ServiceCallback> serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); + public Observable deleteAsync(String applicationObjectId) { + return deleteWithServiceResponseAsync(applicationObjectId).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Delete an application. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. + * + * @param applicationObjectId Application object id + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> deleteWithServiceResponseAsync(String applicationObjectId) { + if (applicationObjectId == null) { + throw new IllegalArgumentException("Parameter applicationObjectId is required and cannot be null."); } if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Call call = service.list(this.client.tenantID(), filter, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = listDelegate(response); - serviceCallback.success(new ServiceResponse<>(result.getBody().getItems(), result.getResponse())); - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); + return service.delete(applicationObjectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = deleteDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } } + }); + } + + private ServiceResponse deleteDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder(this.client.mapperAdapter()) + .register(204, new TypeToken() { }.getType()) + .registerError(GraphErrorException.class) + .build(response); + } + + /** + * Get an application by object Id. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. + * + * @param applicationObjectId Application object id + * @throws GraphErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the ApplicationInner object if successful. + */ + public ApplicationInner get(String applicationObjectId) throws GraphErrorException, IOException, IllegalArgumentException { + return getWithServiceResponseAsync(applicationObjectId).toBlocking().single().getBody(); + } + + /** + * Get an application by object Id. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. + * + * @param applicationObjectId Application object id + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceCall} object + */ + public ServiceCall getAsync(String applicationObjectId, final ServiceCallback serviceCallback) { + return ServiceCall.create(getWithServiceResponseAsync(applicationObjectId), serviceCallback); + } + + /** + * Get an application by object Id. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. + * + * @param applicationObjectId Application object id + * @return the observable to the ApplicationInner object + */ + public Observable getAsync(String applicationObjectId) { + return getWithServiceResponseAsync(applicationObjectId).map(new Func1, ApplicationInner>() { + @Override + public ApplicationInner call(ServiceResponse response) { + return response.getBody(); } }); - return serviceCall; } - private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return new AzureServiceResponseBuilder, CloudException>(this.client.mapperAdapter()) - .register(200, new TypeToken>() { }.getType()) - .registerError(CloudException.class) + /** + * Get an application by object Id. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. + * + * @param applicationObjectId Application object id + * @return the observable to the ApplicationInner object + */ + public Observable> getWithServiceResponseAsync(String applicationObjectId) { + if (applicationObjectId == null) { + throw new IllegalArgumentException("Parameter applicationObjectId is required and cannot be null."); + } + if (this.client.tenantID() == null) { + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.get(applicationObjectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder(this.client.mapperAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(GraphErrorException.class) .build(response); } /** - * Delete an application. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. + * Update existing application. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. * * @param applicationObjectId Application object id - * @throws CloudException exception thrown from REST call + * @param parameters Parameters to update an existing application. + * @throws GraphErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters + */ + public void patch(String applicationObjectId, ApplicationUpdateParametersInner parameters) throws GraphErrorException, IOException, IllegalArgumentException { + patchWithServiceResponseAsync(applicationObjectId, parameters).toBlocking().single().getBody(); + } + + /** + * Update existing application. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. + * + * @param applicationObjectId Application object id + * @param parameters Parameters to update an existing application. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceCall} object + */ + public ServiceCall patchAsync(String applicationObjectId, ApplicationUpdateParametersInner parameters, final ServiceCallback serviceCallback) { + return ServiceCall.create(patchWithServiceResponseAsync(applicationObjectId, parameters), serviceCallback); + } + + /** + * Update existing application. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. + * + * @param applicationObjectId Application object id + * @param parameters Parameters to update an existing application. * @return the {@link ServiceResponse} object if successful. */ - public ServiceResponse delete(String applicationObjectId) throws CloudException, IOException, IllegalArgumentException { + public Observable patchAsync(String applicationObjectId, ApplicationUpdateParametersInner parameters) { + return patchWithServiceResponseAsync(applicationObjectId, parameters).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Update existing application. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. + * + * @param applicationObjectId Application object id + * @param parameters Parameters to update an existing application. + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> patchWithServiceResponseAsync(String applicationObjectId, ApplicationUpdateParametersInner parameters) { if (applicationObjectId == null) { throw new IllegalArgumentException("Parameter applicationObjectId is required and cannot be null."); } if (this.client.tenantID() == null) { throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } + if (parameters == null) { + throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); + } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Call call = service.delete(applicationObjectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - return deleteDelegate(call.execute()); + Validator.validate(parameters); + return service.patch(applicationObjectId, this.client.tenantID(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = patchDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse patchDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder(this.client.mapperAdapter()) + .register(204, new TypeToken() { }.getType()) + .registerError(GraphErrorException.class) + .build(response); } /** - * Delete an application. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. + * Get keyCredentials associated with the application by object Id. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#keycredential-type. + * + * @param applicationObjectId Application object id + * @throws GraphErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the List<KeyCredentialInner> object if successful. + */ + public List listKeyCredentials(String applicationObjectId) throws GraphErrorException, IOException, IllegalArgumentException { + return listKeyCredentialsWithServiceResponseAsync(applicationObjectId).toBlocking().single().getBody(); + } + + /** + * Get keyCredentials associated with the application by object Id. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#keycredential-type. * * @param applicationObjectId Application object id * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall deleteAsync(String applicationObjectId, final ServiceCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall> listKeyCredentialsAsync(String applicationObjectId, final ServiceCallback> serviceCallback) { + return ServiceCall.create(listKeyCredentialsWithServiceResponseAsync(applicationObjectId), serviceCallback); + } + + /** + * Get keyCredentials associated with the application by object Id. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#keycredential-type. + * + * @param applicationObjectId Application object id + * @return the observable to the List<KeyCredentialInner> object + */ + public Observable> listKeyCredentialsAsync(String applicationObjectId) { + return listKeyCredentialsWithServiceResponseAsync(applicationObjectId).map(new Func1>, List>() { + @Override + public List call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * Get keyCredentials associated with the application by object Id. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#keycredential-type. + * + * @param applicationObjectId Application object id + * @return the observable to the List<KeyCredentialInner> object + */ + public Observable>> listKeyCredentialsWithServiceResponseAsync(String applicationObjectId) { if (applicationObjectId == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter applicationObjectId is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter applicationObjectId is required and cannot be null."); } if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Call call = service.delete(applicationObjectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - serviceCallback.success(deleteDelegate(response)); - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); + return service.listKeyCredentials(applicationObjectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listKeyCredentialsDelegate(response); + ServiceResponse> clientResponse = new ServiceResponse>(result.getBody().getItems(), result.getResponse()); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } } - } - }); - return serviceCall; + }); } - private ServiceResponse deleteDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return new AzureServiceResponseBuilder(this.client.mapperAdapter()) - .register(204, new TypeToken() { }.getType()) + private ServiceResponse> listKeyCredentialsDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder, GraphErrorException>(this.client.mapperAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(GraphErrorException.class) .build(response); } /** - * Get an application by object Id. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. + * Update keyCredentials associated with an existing application. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#keycredential-type. * * @param applicationObjectId Application object id - * @throws CloudException exception thrown from REST call + * @throws GraphErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the ApplicationInner object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse get(String applicationObjectId) throws CloudException, IOException, IllegalArgumentException { + public void updateKeyCredentials(String applicationObjectId) throws GraphErrorException, IOException, IllegalArgumentException { + updateKeyCredentialsWithServiceResponseAsync(applicationObjectId).toBlocking().single().getBody(); + } + + /** + * Update keyCredentials associated with an existing application. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#keycredential-type. + * + * @param applicationObjectId Application object id + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceCall} object + */ + public ServiceCall updateKeyCredentialsAsync(String applicationObjectId, final ServiceCallback serviceCallback) { + return ServiceCall.create(updateKeyCredentialsWithServiceResponseAsync(applicationObjectId), serviceCallback); + } + + /** + * Update keyCredentials associated with an existing application. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#keycredential-type. + * + * @param applicationObjectId Application object id + * @return the {@link ServiceResponse} object if successful. + */ + public Observable updateKeyCredentialsAsync(String applicationObjectId) { + return updateKeyCredentialsWithServiceResponseAsync(applicationObjectId).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Update keyCredentials associated with an existing application. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#keycredential-type. + * + * @param applicationObjectId Application object id + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> updateKeyCredentialsWithServiceResponseAsync(String applicationObjectId) { if (applicationObjectId == null) { throw new IllegalArgumentException("Parameter applicationObjectId is required and cannot be null."); } @@ -361,132 +678,332 @@ public ServiceResponse get(String applicationObjectId) throws if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Call call = service.get(applicationObjectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - return getDelegate(call.execute()); + final List value = null; + KeyCredentialsUpdateParameters parameters = new KeyCredentialsUpdateParameters(); + parameters.withValue(null); + return service.updateKeyCredentials(applicationObjectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = updateKeyCredentialsDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); } /** - * Get an application by object Id. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. + * Update keyCredentials associated with an existing application. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#keycredential-type. + * + * @param applicationObjectId Application object id + * @param value KeyCredential list. + * @throws GraphErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + */ + public void updateKeyCredentials(String applicationObjectId, List value) throws GraphErrorException, IOException, IllegalArgumentException { + updateKeyCredentialsWithServiceResponseAsync(applicationObjectId, value).toBlocking().single().getBody(); + } + + /** + * Update keyCredentials associated with an existing application. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#keycredential-type. * * @param applicationObjectId Application object id + * @param value KeyCredential list. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall getAsync(String applicationObjectId, final ServiceCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall updateKeyCredentialsAsync(String applicationObjectId, List value, final ServiceCallback serviceCallback) { + return ServiceCall.create(updateKeyCredentialsWithServiceResponseAsync(applicationObjectId, value), serviceCallback); + } + + /** + * Update keyCredentials associated with an existing application. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#keycredential-type. + * + * @param applicationObjectId Application object id + * @param value KeyCredential list. + * @return the {@link ServiceResponse} object if successful. + */ + public Observable updateKeyCredentialsAsync(String applicationObjectId, List value) { + return updateKeyCredentialsWithServiceResponseAsync(applicationObjectId, value).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Update keyCredentials associated with an existing application. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#keycredential-type. + * + * @param applicationObjectId Application object id + * @param value KeyCredential list. + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> updateKeyCredentialsWithServiceResponseAsync(String applicationObjectId, List value) { if (applicationObjectId == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter applicationObjectId is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter applicationObjectId is required and cannot be null."); } if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Call call = service.get(applicationObjectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - serviceCallback.success(getDelegate(response)); - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); + Validator.validate(value); + KeyCredentialsUpdateParameters parameters = new KeyCredentialsUpdateParameters(); + parameters.withValue(value); + return service.updateKeyCredentials(applicationObjectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = updateKeyCredentialsDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } } + }); + } + + private ServiceResponse updateKeyCredentialsDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder(this.client.mapperAdapter()) + .register(204, new TypeToken() { }.getType()) + .registerError(GraphErrorException.class) + .build(response); + } + + /** + * Gets passwordCredentials associated with an existing application. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#passwordcredential-type. + * + * @param applicationObjectId Application object id + * @throws GraphErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the List<PasswordCredentialInner> object if successful. + */ + public List listPasswordCredentials(String applicationObjectId) throws GraphErrorException, IOException, IllegalArgumentException { + return listPasswordCredentialsWithServiceResponseAsync(applicationObjectId).toBlocking().single().getBody(); + } + + /** + * Gets passwordCredentials associated with an existing application. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#passwordcredential-type. + * + * @param applicationObjectId Application object id + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceCall} object + */ + public ServiceCall> listPasswordCredentialsAsync(String applicationObjectId, final ServiceCallback> serviceCallback) { + return ServiceCall.create(listPasswordCredentialsWithServiceResponseAsync(applicationObjectId), serviceCallback); + } + + /** + * Gets passwordCredentials associated with an existing application. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#passwordcredential-type. + * + * @param applicationObjectId Application object id + * @return the observable to the List<PasswordCredentialInner> object + */ + public Observable> listPasswordCredentialsAsync(String applicationObjectId) { + return listPasswordCredentialsWithServiceResponseAsync(applicationObjectId).map(new Func1>, List>() { + @Override + public List call(ServiceResponse> response) { + return response.getBody(); } }); - return serviceCall; } - private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return new AzureServiceResponseBuilder(this.client.mapperAdapter()) - .register(200, new TypeToken() { }.getType()) - .registerError(CloudException.class) + /** + * Gets passwordCredentials associated with an existing application. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#passwordcredential-type. + * + * @param applicationObjectId Application object id + * @return the observable to the List<PasswordCredentialInner> object + */ + public Observable>> listPasswordCredentialsWithServiceResponseAsync(String applicationObjectId) { + if (applicationObjectId == null) { + throw new IllegalArgumentException("Parameter applicationObjectId is required and cannot be null."); + } + if (this.client.tenantID() == null) { + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.listPasswordCredentials(applicationObjectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listPasswordCredentialsDelegate(response); + ServiceResponse> clientResponse = new ServiceResponse>(result.getBody().getItems(), result.getResponse()); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listPasswordCredentialsDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder, GraphErrorException>(this.client.mapperAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(GraphErrorException.class) .build(response); } /** - * Update existing application. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. + * Updates passwordCredentials associated with an existing application. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#passwordcredential-type. * * @param applicationObjectId Application object id - * @param parameters Parameters to update an existing application. - * @throws CloudException exception thrown from REST call + * @throws GraphErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters + */ + public void updatePasswordCredentials(String applicationObjectId) throws GraphErrorException, IOException, IllegalArgumentException { + updatePasswordCredentialsWithServiceResponseAsync(applicationObjectId).toBlocking().single().getBody(); + } + + /** + * Updates passwordCredentials associated with an existing application. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#passwordcredential-type. + * + * @param applicationObjectId Application object id + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceCall} object + */ + public ServiceCall updatePasswordCredentialsAsync(String applicationObjectId, final ServiceCallback serviceCallback) { + return ServiceCall.create(updatePasswordCredentialsWithServiceResponseAsync(applicationObjectId), serviceCallback); + } + + /** + * Updates passwordCredentials associated with an existing application. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#passwordcredential-type. + * + * @param applicationObjectId Application object id * @return the {@link ServiceResponse} object if successful. */ - public ServiceResponse patch(String applicationObjectId, ApplicationUpdateParametersInner parameters) throws CloudException, IOException, IllegalArgumentException { + public Observable updatePasswordCredentialsAsync(String applicationObjectId) { + return updatePasswordCredentialsWithServiceResponseAsync(applicationObjectId).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Updates passwordCredentials associated with an existing application. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#passwordcredential-type. + * + * @param applicationObjectId Application object id + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> updatePasswordCredentialsWithServiceResponseAsync(String applicationObjectId) { if (applicationObjectId == null) { throw new IllegalArgumentException("Parameter applicationObjectId is required and cannot be null."); } if (this.client.tenantID() == null) { throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } - if (parameters == null) { - throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); - } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Validator.validate(parameters); - Call call = service.patch(applicationObjectId, this.client.tenantID(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - return patchDelegate(call.execute()); + final List value = null; + PasswordCredentialsUpdateParameters parameters = new PasswordCredentialsUpdateParameters(); + parameters.withValue(null); + return service.updatePasswordCredentials(applicationObjectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = updatePasswordCredentialsDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); } /** - * Update existing application. Reference: http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx. + * Updates passwordCredentials associated with an existing application. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#passwordcredential-type. * * @param applicationObjectId Application object id - * @param parameters Parameters to update an existing application. + * @param value PasswordCredential list. + * @throws GraphErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + */ + public void updatePasswordCredentials(String applicationObjectId, List value) throws GraphErrorException, IOException, IllegalArgumentException { + updatePasswordCredentialsWithServiceResponseAsync(applicationObjectId, value).toBlocking().single().getBody(); + } + + /** + * Updates passwordCredentials associated with an existing application. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#passwordcredential-type. + * + * @param applicationObjectId Application object id + * @param value PasswordCredential list. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall patchAsync(String applicationObjectId, ApplicationUpdateParametersInner parameters, final ServiceCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall updatePasswordCredentialsAsync(String applicationObjectId, List value, final ServiceCallback serviceCallback) { + return ServiceCall.create(updatePasswordCredentialsWithServiceResponseAsync(applicationObjectId, value), serviceCallback); + } + + /** + * Updates passwordCredentials associated with an existing application. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#passwordcredential-type. + * + * @param applicationObjectId Application object id + * @param value PasswordCredential list. + * @return the {@link ServiceResponse} object if successful. + */ + public Observable updatePasswordCredentialsAsync(String applicationObjectId, List value) { + return updatePasswordCredentialsWithServiceResponseAsync(applicationObjectId, value).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Updates passwordCredentials associated with an existing application. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#passwordcredential-type. + * + * @param applicationObjectId Application object id + * @param value PasswordCredential list. + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> updatePasswordCredentialsWithServiceResponseAsync(String applicationObjectId, List value) { if (applicationObjectId == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter applicationObjectId is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter applicationObjectId is required and cannot be null."); } if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; - } - if (parameters == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter parameters is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Validator.validate(parameters, serviceCallback); - Call call = service.patch(applicationObjectId, this.client.tenantID(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - serviceCallback.success(patchDelegate(response)); - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); + Validator.validate(value); + PasswordCredentialsUpdateParameters parameters = new PasswordCredentialsUpdateParameters(); + parameters.withValue(value); + return service.updatePasswordCredentials(applicationObjectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = updatePasswordCredentialsDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } } - } - }); - return serviceCall; + }); } - private ServiceResponse patchDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return new AzureServiceResponseBuilder(this.client.mapperAdapter()) + private ServiceResponse updatePasswordCredentialsDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder(this.client.mapperAdapter()) .register(204, new TypeToken() { }.getType()) + .registerError(GraphErrorException.class) .build(response); } diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/GraphRbacManagementClientImpl.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/GraphRbacManagementClientImpl.java index e95756e1703d4..56062b62394ed 100644 --- a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/GraphRbacManagementClientImpl.java +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/GraphRbacManagementClientImpl.java @@ -40,11 +40,11 @@ public String apiVersion() { return this.apiVersion; } - /** Gets or sets the tenant Id. */ + /** the tenant Id. */ private String tenantID; /** - * Gets Gets or sets the tenant Id. + * Gets the tenant Id. * * @return the tenantID value. */ @@ -53,7 +53,7 @@ public String tenantID() { } /** - * Sets Gets or sets the tenant Id. + * Sets the tenant Id. * * @param tenantID the tenantID value. * @return the service client itself diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/GraphRbacManager.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/GraphRbacManager.java index 3c0b086690d4a..570cf9456c414 100644 --- a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/GraphRbacManager.java +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/GraphRbacManager.java @@ -28,6 +28,7 @@ public final class GraphRbacManager { * Creates an instance of GraphRbacManager that exposes resource management API entry points. * * @param credentials the credentials to use + * @param tenantId the tenantId in Active Directory * @return the GraphRbacManager instance */ public static GraphRbacManager authenticate(ServiceClientCredentials credentials, String tenantId) { @@ -42,6 +43,7 @@ public static GraphRbacManager authenticate(ServiceClientCredentials credentials * Creates an instance of GraphRbacManager that exposes resource management API entry points. * * @param restClient the RestClient to be used for API calls + * @param tenantId the tenantId in Active Directory * @return the interface exposing resource management API entry points that work across subscriptions */ public static GraphRbacManager authenticate(RestClient restClient, String tenantId) { @@ -65,6 +67,7 @@ public interface Configurable extends AzureConfigurable { * Creates an instance of GraphRbacManager that exposes resource management API entry points. * * @param credentials the credentials to use + * @param tenantId the tenantId in Active Directory * @return the interface exposing resource management API entry points that work across subscriptions */ GraphRbacManager authenticate(ServiceClientCredentials credentials, String tenantId); @@ -92,7 +95,7 @@ private GraphRbacManager(RestClient restClient, String tenantId) { /** * @return the storage account management API entry point */ - public Users storageAccounts() { + public Users users() { if (users == null) { users = new UsersImpl(graphRbacManagementClient.users(), this); } diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/GroupsInner.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/GroupsInner.java index dc6fb1951e648..909a198bd2881 100644 --- a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/GroupsInner.java +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/GroupsInner.java @@ -10,22 +10,22 @@ import retrofit2.Retrofit; import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceCall; import com.microsoft.azure.AzureServiceResponseBuilder; -import com.microsoft.azure.CloudException; import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.management.graphrbac.GraphErrorException; import com.microsoft.azure.management.graphrbac.GroupAddMemberParameters; import com.microsoft.azure.management.graphrbac.GroupGetMemberGroupsParameters; import com.microsoft.azure.Page; import com.microsoft.azure.PagedList; +import com.microsoft.rest.RestException; import com.microsoft.rest.ServiceCall; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceResponse; -import com.microsoft.rest.ServiceResponseCallback; import com.microsoft.rest.Validator; import java.io.IOException; import java.util.List; import okhttp3.ResponseBody; -import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.Header; @@ -35,6 +35,8 @@ import retrofit2.http.POST; import retrofit2.http.Query; import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; /** * An instance of this class provides access to all the operations defined @@ -64,47 +66,47 @@ public GroupsInner(Retrofit retrofit, GraphRbacManagementClientImpl client) { interface GroupsService { @Headers("Content-Type: application/json; charset=utf-8") @POST("{tenantID}/isMemberOf") - Call isMemberOf(@Path("tenantID") String tenantID, @Body CheckGroupMembershipParametersInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> isMemberOf(@Path("tenantID") String tenantID, @Body CheckGroupMembershipParametersInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @HTTP(path = "{tenantID}/groups/{groupObjectId}/$links/members/{memberObjectId}", method = "DELETE", hasBody = true) - Call removeMember(@Path(value = "groupObjectId", encoded = true) String groupObjectId, @Path(value = "memberObjectId", encoded = true) String memberObjectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> removeMember(@Path(value = "groupObjectId", encoded = true) String groupObjectId, @Path(value = "memberObjectId", encoded = true) String memberObjectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @POST("{tenantID}/groups/{groupObjectId}/$links/members") - Call addMember(@Path(value = "groupObjectId", encoded = true) String groupObjectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body GroupAddMemberParameters parameters, @Header("User-Agent") String userAgent); + Observable> addMember(@Path(value = "groupObjectId", encoded = true) String groupObjectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body GroupAddMemberParameters parameters, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @HTTP(path = "{tenantID}/groups/{groupObjectId}", method = "DELETE", hasBody = true) - Call delete(@Path(value = "groupObjectId", encoded = true) String groupObjectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> delete(@Path(value = "groupObjectId", encoded = true) String groupObjectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @POST("{tenantID}/groups") - Call create(@Path("tenantID") String tenantID, @Body GroupCreateParametersInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> create(@Path("tenantID") String tenantID, @Body GroupCreateParametersInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("{tenantID}/groups") - Call list(@Path("tenantID") String tenantID, @Query("$filter") String filter, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> list(@Path("tenantID") String tenantID, @Query("$filter") String filter, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("{tenantID}/groups/{objectId}/members") - Call getGroupMembers(@Path(value = "objectId", encoded = true) String objectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> getGroupMembers(@Path(value = "objectId", encoded = true) String objectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("{tenantID}/groups/{objectId}") - Call get(@Path(value = "objectId", encoded = true) String objectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> get(@Path(value = "objectId", encoded = true) String objectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @POST("{tenantID}/groups/{objectId}/getMemberGroups") - Call getMemberGroups(@Path(value = "objectId", encoded = true) String objectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body GroupGetMemberGroupsParameters parameters, @Header("User-Agent") String userAgent); + Observable> getMemberGroups(@Path(value = "objectId", encoded = true) String objectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body GroupGetMemberGroupsParameters parameters, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("{tenantID}/{nextLink}") - Call listNext(@Path(value = "nextLink", encoded = true) String nextLink, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> listNext(@Path(value = "nextLink", encoded = true) String nextLink, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("{tenantID}/{nextLink}") - Call getGroupMembersNext(@Path(value = "nextLink", encoded = true) String nextLink, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> getGroupMembersNext(@Path(value = "nextLink", encoded = true) String nextLink, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); } @@ -112,24 +114,13 @@ interface GroupsService { * Checks whether the specified user, group, contact, or service principal is a direct or a transitive member of the specified group. * * @param parameters Check group membership parameters. - * @throws CloudException exception thrown from REST call + * @throws GraphErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the CheckGroupMembershipResultInner object wrapped in {@link ServiceResponse} if successful. + * @return the CheckGroupMembershipResultInner object if successful. */ - public ServiceResponse isMemberOf(CheckGroupMembershipParametersInner parameters) throws CloudException, IOException, IllegalArgumentException { - if (this.client.tenantID() == null) { - throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); - } - if (parameters == null) { - throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - Validator.validate(parameters); - Call call = service.isMemberOf(this.client.tenantID(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - return isMemberOfDelegate(call.execute()); + public CheckGroupMembershipResultInner isMemberOf(CheckGroupMembershipParametersInner parameters) throws GraphErrorException, IOException, IllegalArgumentException { + return isMemberOfWithServiceResponseAsync(parameters).toBlocking().single().getBody(); } /** @@ -137,45 +128,62 @@ public ServiceResponse isMemberOf(CheckGroupMem * * @param parameters Check group membership parameters. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall isMemberOfAsync(CheckGroupMembershipParametersInner parameters, final ServiceCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall isMemberOfAsync(CheckGroupMembershipParametersInner parameters, final ServiceCallback serviceCallback) { + return ServiceCall.create(isMemberOfWithServiceResponseAsync(parameters), serviceCallback); + } + + /** + * Checks whether the specified user, group, contact, or service principal is a direct or a transitive member of the specified group. + * + * @param parameters Check group membership parameters. + * @return the observable to the CheckGroupMembershipResultInner object + */ + public Observable isMemberOfAsync(CheckGroupMembershipParametersInner parameters) { + return isMemberOfWithServiceResponseAsync(parameters).map(new Func1, CheckGroupMembershipResultInner>() { + @Override + public CheckGroupMembershipResultInner call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Checks whether the specified user, group, contact, or service principal is a direct or a transitive member of the specified group. + * + * @param parameters Check group membership parameters. + * @return the observable to the CheckGroupMembershipResultInner object + */ + public Observable> isMemberOfWithServiceResponseAsync(CheckGroupMembershipParametersInner parameters) { if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (parameters == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter parameters is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Validator.validate(parameters, serviceCallback); - Call call = service.isMemberOf(this.client.tenantID(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - serviceCallback.success(isMemberOfDelegate(response)); - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); + Validator.validate(parameters); + return service.isMemberOf(this.client.tenantID(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = isMemberOfDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } } - } - }); - return serviceCall; + }); } - private ServiceResponse isMemberOfDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return new AzureServiceResponseBuilder(this.client.mapperAdapter()) + private ServiceResponse isMemberOfDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder(this.client.mapperAdapter()) .register(200, new TypeToken() { }.getType()) - .registerError(CloudException.class) + .registerError(GraphErrorException.class) .build(response); } @@ -184,26 +192,12 @@ private ServiceResponse isMemberOfDelegate(Resp * * @param groupObjectId Group object id * @param memberObjectId Member Object id - * @throws CloudException exception thrown from REST call + * @throws GraphErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the {@link ServiceResponse} object if successful. */ - public ServiceResponse removeMember(String groupObjectId, String memberObjectId) throws CloudException, IOException, IllegalArgumentException { - if (groupObjectId == null) { - throw new IllegalArgumentException("Parameter groupObjectId is required and cannot be null."); - } - if (memberObjectId == null) { - throw new IllegalArgumentException("Parameter memberObjectId is required and cannot be null."); - } - if (this.client.tenantID() == null) { - throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - Call call = service.removeMember(groupObjectId, memberObjectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - return removeMemberDelegate(call.execute()); + public void removeMember(String groupObjectId, String memberObjectId) throws GraphErrorException, IOException, IllegalArgumentException { + removeMemberWithServiceResponseAsync(groupObjectId, memberObjectId).toBlocking().single().getBody(); } /** @@ -212,47 +206,66 @@ public ServiceResponse removeMember(String groupObjectId, String memberObj * @param groupObjectId Group object id * @param memberObjectId Member Object id * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall removeMemberAsync(String groupObjectId, String memberObjectId, final ServiceCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall removeMemberAsync(String groupObjectId, String memberObjectId, final ServiceCallback serviceCallback) { + return ServiceCall.create(removeMemberWithServiceResponseAsync(groupObjectId, memberObjectId), serviceCallback); + } + + /** + * Remove a memeber from a group. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/groups-operations#DeleteGroupMember. + * + * @param groupObjectId Group object id + * @param memberObjectId Member Object id + * @return the {@link ServiceResponse} object if successful. + */ + public Observable removeMemberAsync(String groupObjectId, String memberObjectId) { + return removeMemberWithServiceResponseAsync(groupObjectId, memberObjectId).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Remove a memeber from a group. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/groups-operations#DeleteGroupMember. + * + * @param groupObjectId Group object id + * @param memberObjectId Member Object id + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> removeMemberWithServiceResponseAsync(String groupObjectId, String memberObjectId) { if (groupObjectId == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter groupObjectId is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter groupObjectId is required and cannot be null."); } if (memberObjectId == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter memberObjectId is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter memberObjectId is required and cannot be null."); } if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Call call = service.removeMember(groupObjectId, memberObjectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - serviceCallback.success(removeMemberDelegate(response)); - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); + return service.removeMember(groupObjectId, memberObjectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = removeMemberDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } } - } - }); - return serviceCall; + }); } - private ServiceResponse removeMemberDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return new AzureServiceResponseBuilder(this.client.mapperAdapter()) + private ServiceResponse removeMemberDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder(this.client.mapperAdapter()) .register(204, new TypeToken() { }.getType()) + .registerError(GraphErrorException.class) .build(response); } @@ -261,28 +274,12 @@ private ServiceResponse removeMemberDelegate(Response respon * * @param groupObjectId Group object id * @param url Member Object Url as "https://graph.windows.net/0b1f9851-1bf0-433f-aec3-cb9272f093dc/directoryObjects/f260bbc4-c254-447b-94cf-293b5ec434dd", where "0b1f9851-1bf0-433f-aec3-cb9272f093dc" is the tenantId and "f260bbc4-c254-447b-94cf-293b5ec434dd" is the objectId of the member (user, application, servicePrincipal, group) to be added. - * @throws CloudException exception thrown from REST call + * @throws GraphErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the {@link ServiceResponse} object if successful. */ - public ServiceResponse addMember(String groupObjectId, String url) throws CloudException, IOException, IllegalArgumentException { - if (groupObjectId == null) { - throw new IllegalArgumentException("Parameter groupObjectId is required and cannot be null."); - } - if (this.client.tenantID() == null) { - throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - if (url == null) { - throw new IllegalArgumentException("Parameter url is required and cannot be null."); - } - GroupAddMemberParameters parameters = new GroupAddMemberParameters(); - parameters.withUrl(url); - Call call = service.addMember(groupObjectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()); - return addMemberDelegate(call.execute()); + public void addMember(String groupObjectId, String url) throws GraphErrorException, IOException, IllegalArgumentException { + addMemberWithServiceResponseAsync(groupObjectId, url).toBlocking().single().getBody(); } /** @@ -291,49 +288,68 @@ public ServiceResponse addMember(String groupObjectId, String url) throws * @param groupObjectId Group object id * @param url Member Object Url as "https://graph.windows.net/0b1f9851-1bf0-433f-aec3-cb9272f093dc/directoryObjects/f260bbc4-c254-447b-94cf-293b5ec434dd", where "0b1f9851-1bf0-433f-aec3-cb9272f093dc" is the tenantId and "f260bbc4-c254-447b-94cf-293b5ec434dd" is the objectId of the member (user, application, servicePrincipal, group) to be added. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall addMemberAsync(String groupObjectId, String url, final ServiceCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall addMemberAsync(String groupObjectId, String url, final ServiceCallback serviceCallback) { + return ServiceCall.create(addMemberWithServiceResponseAsync(groupObjectId, url), serviceCallback); + } + + /** + * Add a memeber to a group. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/groups-operations#AddGroupMembers. + * + * @param groupObjectId Group object id + * @param url Member Object Url as "https://graph.windows.net/0b1f9851-1bf0-433f-aec3-cb9272f093dc/directoryObjects/f260bbc4-c254-447b-94cf-293b5ec434dd", where "0b1f9851-1bf0-433f-aec3-cb9272f093dc" is the tenantId and "f260bbc4-c254-447b-94cf-293b5ec434dd" is the objectId of the member (user, application, servicePrincipal, group) to be added. + * @return the {@link ServiceResponse} object if successful. + */ + public Observable addMemberAsync(String groupObjectId, String url) { + return addMemberWithServiceResponseAsync(groupObjectId, url).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Add a memeber to a group. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/groups-operations#AddGroupMembers. + * + * @param groupObjectId Group object id + * @param url Member Object Url as "https://graph.windows.net/0b1f9851-1bf0-433f-aec3-cb9272f093dc/directoryObjects/f260bbc4-c254-447b-94cf-293b5ec434dd", where "0b1f9851-1bf0-433f-aec3-cb9272f093dc" is the tenantId and "f260bbc4-c254-447b-94cf-293b5ec434dd" is the objectId of the member (user, application, servicePrincipal, group) to be added. + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> addMemberWithServiceResponseAsync(String groupObjectId, String url) { if (groupObjectId == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter groupObjectId is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter groupObjectId is required and cannot be null."); } if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } if (url == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter url is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter url is required and cannot be null."); } GroupAddMemberParameters parameters = new GroupAddMemberParameters(); parameters.withUrl(url); - Call call = service.addMember(groupObjectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - serviceCallback.success(addMemberDelegate(response)); - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); + return service.addMember(groupObjectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = addMemberDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } } - } - }); - return serviceCall; + }); } - private ServiceResponse addMemberDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return new AzureServiceResponseBuilder(this.client.mapperAdapter()) + private ServiceResponse addMemberDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder(this.client.mapperAdapter()) .register(204, new TypeToken() { }.getType()) + .registerError(GraphErrorException.class) .build(response); } @@ -341,23 +357,12 @@ private ServiceResponse addMemberDelegate(Response response) * Delete a group in the directory. Reference: http://msdn.microsoft.com/en-us/library/azure/dn151676.aspx. * * @param groupObjectId Object id - * @throws CloudException exception thrown from REST call + * @throws GraphErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the {@link ServiceResponse} object if successful. */ - public ServiceResponse delete(String groupObjectId) throws CloudException, IOException, IllegalArgumentException { - if (groupObjectId == null) { - throw new IllegalArgumentException("Parameter groupObjectId is required and cannot be null."); - } - if (this.client.tenantID() == null) { - throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - Call call = service.delete(groupObjectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - return deleteDelegate(call.execute()); + public void delete(String groupObjectId) throws GraphErrorException, IOException, IllegalArgumentException { + deleteWithServiceResponseAsync(groupObjectId).toBlocking().single().getBody(); } /** @@ -365,43 +370,61 @@ public ServiceResponse delete(String groupObjectId) throws CloudException, * * @param groupObjectId Object id * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall deleteAsync(String groupObjectId, final ServiceCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall deleteAsync(String groupObjectId, final ServiceCallback serviceCallback) { + return ServiceCall.create(deleteWithServiceResponseAsync(groupObjectId), serviceCallback); + } + + /** + * Delete a group in the directory. Reference: http://msdn.microsoft.com/en-us/library/azure/dn151676.aspx. + * + * @param groupObjectId Object id + * @return the {@link ServiceResponse} object if successful. + */ + public Observable deleteAsync(String groupObjectId) { + return deleteWithServiceResponseAsync(groupObjectId).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Delete a group in the directory. Reference: http://msdn.microsoft.com/en-us/library/azure/dn151676.aspx. + * + * @param groupObjectId Object id + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> deleteWithServiceResponseAsync(String groupObjectId) { if (groupObjectId == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter groupObjectId is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter groupObjectId is required and cannot be null."); } if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Call call = service.delete(groupObjectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - serviceCallback.success(deleteDelegate(response)); - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); + return service.delete(groupObjectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = deleteDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } } - } - }); - return serviceCall; + }); } - private ServiceResponse deleteDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return new AzureServiceResponseBuilder(this.client.mapperAdapter()) + private ServiceResponse deleteDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder(this.client.mapperAdapter()) .register(204, new TypeToken() { }.getType()) + .registerError(GraphErrorException.class) .build(response); } @@ -409,24 +432,13 @@ private ServiceResponse deleteDelegate(Response response) th * Create a group in the directory. Reference: http://msdn.microsoft.com/en-us/library/azure/dn151676.aspx. * * @param parameters Parameters to create a group - * @throws CloudException exception thrown from REST call + * @throws GraphErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the ADGroupInner object wrapped in {@link ServiceResponse} if successful. + * @return the ADGroupInner object if successful. */ - public ServiceResponse create(GroupCreateParametersInner parameters) throws CloudException, IOException, IllegalArgumentException { - if (this.client.tenantID() == null) { - throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); - } - if (parameters == null) { - throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - Validator.validate(parameters); - Call call = service.create(this.client.tenantID(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - return createDelegate(call.execute()); + public ADGroupInner create(GroupCreateParametersInner parameters) throws GraphErrorException, IOException, IllegalArgumentException { + return createWithServiceResponseAsync(parameters).toBlocking().single().getBody(); } /** @@ -434,142 +446,179 @@ public ServiceResponse create(GroupCreateParametersInner parameter * * @param parameters Parameters to create a group * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall createAsync(GroupCreateParametersInner parameters, final ServiceCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall createAsync(GroupCreateParametersInner parameters, final ServiceCallback serviceCallback) { + return ServiceCall.create(createWithServiceResponseAsync(parameters), serviceCallback); + } + + /** + * Create a group in the directory. Reference: http://msdn.microsoft.com/en-us/library/azure/dn151676.aspx. + * + * @param parameters Parameters to create a group + * @return the observable to the ADGroupInner object + */ + public Observable createAsync(GroupCreateParametersInner parameters) { + return createWithServiceResponseAsync(parameters).map(new Func1, ADGroupInner>() { + @Override + public ADGroupInner call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Create a group in the directory. Reference: http://msdn.microsoft.com/en-us/library/azure/dn151676.aspx. + * + * @param parameters Parameters to create a group + * @return the observable to the ADGroupInner object + */ + public Observable> createWithServiceResponseAsync(GroupCreateParametersInner parameters) { if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (parameters == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter parameters is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Validator.validate(parameters, serviceCallback); - Call call = service.create(this.client.tenantID(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - serviceCallback.success(createDelegate(response)); - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); + Validator.validate(parameters); + return service.create(this.client.tenantID(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = createDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } } - } - }); - return serviceCall; + }); } - private ServiceResponse createDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return new AzureServiceResponseBuilder(this.client.mapperAdapter()) + private ServiceResponse createDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder(this.client.mapperAdapter()) .register(201, new TypeToken() { }.getType()) - .registerError(CloudException.class) + .registerError(GraphErrorException.class) .build(response); } /** * Gets list of groups for the current tenant. * - * @throws CloudException exception thrown from REST call + * @throws GraphErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<ADGroupInner> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<ADGroupInner> object if successful. */ - public ServiceResponse> list() throws CloudException, IOException, IllegalArgumentException { - if (this.client.tenantID() == null) { - throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - final String filter = null; - Call call = service.list(this.client.tenantID(), filter, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - ServiceResponse> response = listDelegate(call.execute()); - PagedList result = new PagedList(response.getBody()) { + public PagedList list() throws GraphErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = listSinglePageAsync().toBlocking().single(); + return new PagedList(response.getBody()) { @Override - public Page nextPage(String nextLink) throws CloudException, IOException { - return listNext(nextLink).getBody(); + public Page nextPage(String nextLink) throws RestException, IOException { + return listNextSinglePageAsync(nextLink).toBlocking().single().getBody(); } }; - return new ServiceResponse<>(result, response.getResponse()); } /** * Gets list of groups for the current tenant. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall listAsync(final ListOperationCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall> listAsync(final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + listSinglePageAsync(), + new Func1>>>() { + @Override + public Observable>> call(String nextLink) { + return listNextSinglePageAsync(nextLink); + } + }, + serviceCallback); + } + + /** + * Gets list of groups for the current tenant. + * + * @return the observable to the PagedList<ADGroupInner> object + */ + public Observable> listAsync() { + return listWithServiceResponseAsync() + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * Gets list of groups for the current tenant. + * + * @return the observable to the PagedList<ADGroupInner> object + */ + public Observable>> listWithServiceResponseAsync() { + return listSinglePageAsync() + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextLink = page.getBody().getNextPageLink(); + if (nextLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextLink)); + } + }); + } + + /** + * Gets list of groups for the current tenant. + * + * @return the PagedList<ADGroupInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync() { if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } final String filter = null; - Call call = service.list(this.client.tenantID(), filter, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = listDelegate(response); - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - listNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); + return service.list(this.client.tenantID(), filter, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); } - } - }); - return serviceCall; + }); } /** * Gets list of groups for the current tenant. * * @param filter The filter to apply on the operation. - * @throws CloudException exception thrown from REST call + * @throws GraphErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<ADGroupInner> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<ADGroupInner> object if successful. */ - public ServiceResponse> list(final String filter) throws CloudException, IOException, IllegalArgumentException { - if (this.client.tenantID() == null) { - throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - Call call = service.list(this.client.tenantID(), filter, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - ServiceResponse> response = listDelegate(call.execute()); - PagedList result = new PagedList(response.getBody()) { + public PagedList list(final String filter) throws GraphErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = listSinglePageAsync(filter).toBlocking().single(); + return new PagedList(response.getBody()) { @Override - public Page nextPage(String nextLink) throws CloudException, IOException { - return listNext(nextLink).getBody(); + public Page nextPage(String nextLink) throws RestException, IOException { + return listNextSinglePageAsync(nextLink).toBlocking().single().getBody(); } }; - return new ServiceResponse<>(result, response.getResponse()); } /** @@ -577,47 +626,87 @@ public Page nextPage(String nextLink) throws CloudException, IOExc * * @param filter The filter to apply on the operation. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall listAsync(final String filter, final ListOperationCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall> listAsync(final String filter, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + listSinglePageAsync(filter), + new Func1>>>() { + @Override + public Observable>> call(String nextLink) { + return listNextSinglePageAsync(nextLink); + } + }, + serviceCallback); + } + + /** + * Gets list of groups for the current tenant. + * + * @param filter The filter to apply on the operation. + * @return the observable to the PagedList<ADGroupInner> object + */ + public Observable> listAsync(final String filter) { + return listWithServiceResponseAsync(filter) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * Gets list of groups for the current tenant. + * + * @param filter The filter to apply on the operation. + * @return the observable to the PagedList<ADGroupInner> object + */ + public Observable>> listWithServiceResponseAsync(final String filter) { + return listSinglePageAsync(filter) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextLink = page.getBody().getNextPageLink(); + if (nextLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextLink)); + } + }); + } + + /** + * Gets list of groups for the current tenant. + * + ServiceResponse> * @param filter The filter to apply on the operation. + * @return the PagedList<ADGroupInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync(final String filter) { if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Call call = service.list(this.client.tenantID(), filter, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = listDelegate(response); - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - listNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); + return service.list(this.client.tenantID(), filter, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); } - } - }); - return serviceCall; + }); } - private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return new AzureServiceResponseBuilder, CloudException>(this.client.mapperAdapter()) + private ServiceResponse> listDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder, GraphErrorException>(this.client.mapperAdapter()) .register(200, new TypeToken>() { }.getType()) - .registerError(CloudException.class) + .registerError(GraphErrorException.class) .build(response); } @@ -625,30 +714,19 @@ private ServiceResponse> listDelegate(Response> getGroupMembers(final String objectId) throws CloudException, IOException, IllegalArgumentException { - if (objectId == null) { - throw new IllegalArgumentException("Parameter objectId is required and cannot be null."); - } - if (this.client.tenantID() == null) { - throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - Call call = service.getGroupMembers(objectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - ServiceResponse> response = getGroupMembersDelegate(call.execute()); - PagedList result = new PagedList(response.getBody()) { + public PagedList getGroupMembers(final String objectId) throws GraphErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getGroupMembersSinglePageAsync(objectId).toBlocking().single(); + return new PagedList(response.getBody()) { @Override - public Page nextPage(String nextLink) throws CloudException, IOException { - return getGroupMembersNext(nextLink).getBody(); + public Page nextPage(String nextLink) throws RestException, IOException { + return getGroupMembersNextSinglePageAsync(nextLink).toBlocking().single().getBody(); } }; - return new ServiceResponse<>(result, response.getResponse()); } /** @@ -656,51 +734,90 @@ public Page nextPage(String nextLink) throws CloudException, IOE * * @param objectId Group object Id who's members should be retrieved. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall getGroupMembersAsync(final String objectId, final ListOperationCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall> getGroupMembersAsync(final String objectId, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + getGroupMembersSinglePageAsync(objectId), + new Func1>>>() { + @Override + public Observable>> call(String nextLink) { + return getGroupMembersNextSinglePageAsync(nextLink); + } + }, + serviceCallback); + } + + /** + * Gets the members of a group. + * + * @param objectId Group object Id who's members should be retrieved. + * @return the observable to the PagedList<AADObjectInner> object + */ + public Observable> getGroupMembersAsync(final String objectId) { + return getGroupMembersWithServiceResponseAsync(objectId) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * Gets the members of a group. + * + * @param objectId Group object Id who's members should be retrieved. + * @return the observable to the PagedList<AADObjectInner> object + */ + public Observable>> getGroupMembersWithServiceResponseAsync(final String objectId) { + return getGroupMembersSinglePageAsync(objectId) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextLink = page.getBody().getNextPageLink(); + if (nextLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getGroupMembersNextWithServiceResponseAsync(nextLink)); + } + }); + } + + /** + * Gets the members of a group. + * + ServiceResponse> * @param objectId Group object Id who's members should be retrieved. + * @return the PagedList<AADObjectInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> getGroupMembersSinglePageAsync(final String objectId) { if (objectId == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter objectId is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter objectId is required and cannot be null."); } if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Call call = service.getGroupMembers(objectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = getGroupMembersDelegate(response); - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - getGroupMembersNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); + return service.getGroupMembers(objectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = getGroupMembersDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); } - } - }); - return serviceCall; + }); } - private ServiceResponse> getGroupMembersDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return new AzureServiceResponseBuilder, CloudException>(this.client.mapperAdapter()) + private ServiceResponse> getGroupMembersDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder, GraphErrorException>(this.client.mapperAdapter()) .register(200, new TypeToken>() { }.getType()) - .registerError(CloudException.class) + .registerError(GraphErrorException.class) .build(response); } @@ -708,23 +825,13 @@ private ServiceResponse> getGroupMembersDelegate(Respo * Gets group information from the directory. * * @param objectId User objectId to get group information. - * @throws CloudException exception thrown from REST call + * @throws GraphErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the ADGroupInner object wrapped in {@link ServiceResponse} if successful. + * @return the ADGroupInner object if successful. */ - public ServiceResponse get(String objectId) throws CloudException, IOException, IllegalArgumentException { - if (objectId == null) { - throw new IllegalArgumentException("Parameter objectId is required and cannot be null."); - } - if (this.client.tenantID() == null) { - throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - Call call = service.get(objectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - return getDelegate(call.execute()); + public ADGroupInner get(String objectId) throws GraphErrorException, IOException, IllegalArgumentException { + return getWithServiceResponseAsync(objectId).toBlocking().single().getBody(); } /** @@ -732,44 +839,61 @@ public ServiceResponse get(String objectId) throws CloudException, * * @param objectId User objectId to get group information. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall getAsync(String objectId, final ServiceCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall getAsync(String objectId, final ServiceCallback serviceCallback) { + return ServiceCall.create(getWithServiceResponseAsync(objectId), serviceCallback); + } + + /** + * Gets group information from the directory. + * + * @param objectId User objectId to get group information. + * @return the observable to the ADGroupInner object + */ + public Observable getAsync(String objectId) { + return getWithServiceResponseAsync(objectId).map(new Func1, ADGroupInner>() { + @Override + public ADGroupInner call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Gets group information from the directory. + * + * @param objectId User objectId to get group information. + * @return the observable to the ADGroupInner object + */ + public Observable> getWithServiceResponseAsync(String objectId) { if (objectId == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter objectId is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter objectId is required and cannot be null."); } if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Call call = service.get(objectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - serviceCallback.success(getDelegate(response)); - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); + return service.get(objectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } } - } - }); - return serviceCall; + }); } - private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return new AzureServiceResponseBuilder(this.client.mapperAdapter()) + private ServiceResponse getDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder(this.client.mapperAdapter()) .register(200, new TypeToken() { }.getType()) - .registerError(CloudException.class) + .registerError(GraphErrorException.class) .build(response); } @@ -778,27 +902,13 @@ private ServiceResponse getDelegate(Response respons * * @param objectId Group filtering parameters. * @param securityEnabledOnly If true only membership in security enabled groups should be checked. Otherwise membership in all groups should be checked - * @throws CloudException exception thrown from REST call + * @throws GraphErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<String> object wrapped in {@link ServiceResponse} if successful. + * @return the List<String> object if successful. */ - public ServiceResponse> getMemberGroups(String objectId, boolean securityEnabledOnly) throws CloudException, IOException, IllegalArgumentException { - if (objectId == null) { - throw new IllegalArgumentException("Parameter objectId is required and cannot be null."); - } - if (this.client.tenantID() == null) { - throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - GroupGetMemberGroupsParameters parameters = new GroupGetMemberGroupsParameters(); - parameters.withSecurityEnabledOnly(securityEnabledOnly); - Call call = service.getMemberGroups(objectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()); - ServiceResponse> response = getMemberGroupsDelegate(call.execute()); - List result = response.getBody().getItems(); - return new ServiceResponse<>(result, response.getResponse()); + public List getMemberGroups(String objectId, boolean securityEnabledOnly) throws GraphErrorException, IOException, IllegalArgumentException { + return getMemberGroupsWithServiceResponseAsync(objectId, securityEnabledOnly).toBlocking().single().getBody(); } /** @@ -807,47 +917,66 @@ public ServiceResponse> getMemberGroups(String objectId, boolean se * @param objectId Group filtering parameters. * @param securityEnabledOnly If true only membership in security enabled groups should be checked. Otherwise membership in all groups should be checked * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall getMemberGroupsAsync(String objectId, boolean securityEnabledOnly, final ServiceCallback> serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall> getMemberGroupsAsync(String objectId, boolean securityEnabledOnly, final ServiceCallback> serviceCallback) { + return ServiceCall.create(getMemberGroupsWithServiceResponseAsync(objectId, securityEnabledOnly), serviceCallback); + } + + /** + * Gets a collection that contains the Object IDs of the groups of which the group is a member. + * + * @param objectId Group filtering parameters. + * @param securityEnabledOnly If true only membership in security enabled groups should be checked. Otherwise membership in all groups should be checked + * @return the observable to the List<String> object + */ + public Observable> getMemberGroupsAsync(String objectId, boolean securityEnabledOnly) { + return getMemberGroupsWithServiceResponseAsync(objectId, securityEnabledOnly).map(new Func1>, List>() { + @Override + public List call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * Gets a collection that contains the Object IDs of the groups of which the group is a member. + * + * @param objectId Group filtering parameters. + * @param securityEnabledOnly If true only membership in security enabled groups should be checked. Otherwise membership in all groups should be checked + * @return the observable to the List<String> object + */ + public Observable>> getMemberGroupsWithServiceResponseAsync(String objectId, boolean securityEnabledOnly) { if (objectId == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter objectId is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter objectId is required and cannot be null."); } if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } GroupGetMemberGroupsParameters parameters = new GroupGetMemberGroupsParameters(); parameters.withSecurityEnabledOnly(securityEnabledOnly); - Call call = service.getMemberGroups(objectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = getMemberGroupsDelegate(response); - serviceCallback.success(new ServiceResponse<>(result.getBody().getItems(), result.getResponse())); - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); + return service.getMemberGroups(objectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = getMemberGroupsDelegate(response); + ServiceResponse> clientResponse = new ServiceResponse>(result.getBody().getItems(), result.getResponse()); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } } - } - }); - return serviceCall; + }); } - private ServiceResponse> getMemberGroupsDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return new AzureServiceResponseBuilder, CloudException>(this.client.mapperAdapter()) + private ServiceResponse> getMemberGroupsDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder, GraphErrorException>(this.client.mapperAdapter()) .register(200, new TypeToken>() { }.getType()) - .registerError(CloudException.class) + .registerError(GraphErrorException.class) .build(response); } @@ -855,23 +984,19 @@ private ServiceResponse> getMemberGroupsDelegate(Response> listNext(final String nextLink) throws CloudException, IOException, IllegalArgumentException { - if (nextLink == null) { - throw new IllegalArgumentException("Parameter nextLink is required and cannot be null."); - } - if (this.client.tenantID() == null) { - throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - Call call = service.listNext(nextLink, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - return listNextDelegate(call.execute()); + public PagedList listNext(final String nextLink) throws GraphErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = listNextSinglePageAsync(nextLink).toBlocking().single(); + return new PagedList(response.getBody()) { + @Override + public Page nextPage(String nextLink) throws RestException, IOException { + return listNextSinglePageAsync(nextLink).toBlocking().single().getBody(); + } + }; } /** @@ -880,51 +1005,90 @@ public ServiceResponse> listNext(final String nextLink) * @param nextLink Next link for list operation. * @param serviceCall the ServiceCall object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall listNextAsync(final String nextLink, final ServiceCall serviceCall, final ListOperationCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall> listNextAsync(final String nextLink, final ServiceCall> serviceCall, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + listNextSinglePageAsync(nextLink), + new Func1>>>() { + @Override + public Observable>> call(String nextLink) { + return listNextSinglePageAsync(nextLink); + } + }, + serviceCallback); + } + + /** + * Gets list of groups for the current tenant. + * + * @param nextLink Next link for list operation. + * @return the observable to the PagedList<ADGroupInner> object + */ + public Observable> listNextAsync(final String nextLink) { + return listNextWithServiceResponseAsync(nextLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * Gets list of groups for the current tenant. + * + * @param nextLink Next link for list operation. + * @return the observable to the PagedList<ADGroupInner> object + */ + public Observable>> listNextWithServiceResponseAsync(final String nextLink) { + return listNextSinglePageAsync(nextLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextLink = page.getBody().getNextPageLink(); + if (nextLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextLink)); + } + }); + } + + /** + * Gets list of groups for the current tenant. + * + ServiceResponse> * @param nextLink Next link for list operation. + * @return the PagedList<ADGroupInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listNextSinglePageAsync(final String nextLink) { if (nextLink == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter nextLink is required and cannot be null."); } if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Call call = service.listNext(nextLink, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - serviceCall.newCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = listNextDelegate(response); - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - listNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); + return service.listNext(nextLink, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listNextDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); } - } - }); - return serviceCall; + }); } - private ServiceResponse> listNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return new AzureServiceResponseBuilder, CloudException>(this.client.mapperAdapter()) + private ServiceResponse> listNextDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder, GraphErrorException>(this.client.mapperAdapter()) .register(200, new TypeToken>() { }.getType()) - .registerError(CloudException.class) + .registerError(GraphErrorException.class) .build(response); } @@ -932,23 +1096,19 @@ private ServiceResponse> listNextDelegate(Response> getGroupMembersNext(final String nextLink) throws CloudException, IOException, IllegalArgumentException { - if (nextLink == null) { - throw new IllegalArgumentException("Parameter nextLink is required and cannot be null."); - } - if (this.client.tenantID() == null) { - throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - Call call = service.getGroupMembersNext(nextLink, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - return getGroupMembersNextDelegate(call.execute()); + public PagedList getGroupMembersNext(final String nextLink) throws GraphErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = getGroupMembersNextSinglePageAsync(nextLink).toBlocking().single(); + return new PagedList(response.getBody()) { + @Override + public Page nextPage(String nextLink) throws RestException, IOException { + return getGroupMembersNextSinglePageAsync(nextLink).toBlocking().single().getBody(); + } + }; } /** @@ -957,51 +1117,90 @@ public ServiceResponse> getGroupMembersNext(final Stri * @param nextLink Next link for list operation. * @param serviceCall the ServiceCall object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall getGroupMembersNextAsync(final String nextLink, final ServiceCall serviceCall, final ListOperationCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall> getGroupMembersNextAsync(final String nextLink, final ServiceCall> serviceCall, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + getGroupMembersNextSinglePageAsync(nextLink), + new Func1>>>() { + @Override + public Observable>> call(String nextLink) { + return getGroupMembersNextSinglePageAsync(nextLink); + } + }, + serviceCallback); + } + + /** + * Gets the members of a group. + * + * @param nextLink Next link for list operation. + * @return the observable to the PagedList<AADObjectInner> object + */ + public Observable> getGroupMembersNextAsync(final String nextLink) { + return getGroupMembersNextWithServiceResponseAsync(nextLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * Gets the members of a group. + * + * @param nextLink Next link for list operation. + * @return the observable to the PagedList<AADObjectInner> object + */ + public Observable>> getGroupMembersNextWithServiceResponseAsync(final String nextLink) { + return getGroupMembersNextSinglePageAsync(nextLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextLink = page.getBody().getNextPageLink(); + if (nextLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(getGroupMembersNextWithServiceResponseAsync(nextLink)); + } + }); + } + + /** + * Gets the members of a group. + * + ServiceResponse> * @param nextLink Next link for list operation. + * @return the PagedList<AADObjectInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> getGroupMembersNextSinglePageAsync(final String nextLink) { if (nextLink == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter nextLink is required and cannot be null."); } if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Call call = service.getGroupMembersNext(nextLink, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - serviceCall.newCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = getGroupMembersNextDelegate(response); - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - getGroupMembersNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); + return service.getGroupMembersNext(nextLink, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = getGroupMembersNextDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); } - } - }); - return serviceCall; + }); } - private ServiceResponse> getGroupMembersNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return new AzureServiceResponseBuilder, CloudException>(this.client.mapperAdapter()) + private ServiceResponse> getGroupMembersNextDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder, GraphErrorException>(this.client.mapperAdapter()) .register(200, new TypeToken>() { }.getType()) - .registerError(CloudException.class) + .registerError(GraphErrorException.class) .build(response); } diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/KeyCredential.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/KeyCredentialInner.java similarity index 69% rename from azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/KeyCredential.java rename to azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/KeyCredentialInner.java index a872fc2465af8..9ce3370d8ebff 100644 --- a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/KeyCredential.java +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/KeyCredentialInner.java @@ -6,41 +6,41 @@ * Code generated by Microsoft (R) AutoRest Code Generator. */ -package com.microsoft.azure.management.graphrbac; +package com.microsoft.azure.management.graphrbac.implementation; import org.joda.time.DateTime; /** - * Active Directory service principal Key Credential information. + * Active Directory Key Credential information. */ -public class KeyCredential { +public class KeyCredentialInner { /** - * Gets or sets start date. + * start date. */ private DateTime startDate; /** - * Gets or sets end date. + * end date. */ private DateTime endDate; /** - * Gets or sets value. + * value. */ private String value; /** - * Gets or sets key Id. + * key Id. */ private String keyId; /** - * Gets or sets usage. + * usage. Acceptable values are 'Verify' and 'Sign'. */ private String usage; /** - * Gets or sets type. + * type. Acceptable values are 'AsymmetricX509Cert' and 'Symmetric'. */ private String type; @@ -57,9 +57,9 @@ public DateTime startDate() { * Set the startDate value. * * @param startDate the startDate value to set - * @return the KeyCredential object itself. + * @return the KeyCredentialInner object itself. */ - public KeyCredential withStartDate(DateTime startDate) { + public KeyCredentialInner withStartDate(DateTime startDate) { this.startDate = startDate; return this; } @@ -77,9 +77,9 @@ public DateTime endDate() { * Set the endDate value. * * @param endDate the endDate value to set - * @return the KeyCredential object itself. + * @return the KeyCredentialInner object itself. */ - public KeyCredential withEndDate(DateTime endDate) { + public KeyCredentialInner withEndDate(DateTime endDate) { this.endDate = endDate; return this; } @@ -97,9 +97,9 @@ public String value() { * Set the value value. * * @param value the value value to set - * @return the KeyCredential object itself. + * @return the KeyCredentialInner object itself. */ - public KeyCredential withValue(String value) { + public KeyCredentialInner withValue(String value) { this.value = value; return this; } @@ -117,9 +117,9 @@ public String keyId() { * Set the keyId value. * * @param keyId the keyId value to set - * @return the KeyCredential object itself. + * @return the KeyCredentialInner object itself. */ - public KeyCredential withKeyId(String keyId) { + public KeyCredentialInner withKeyId(String keyId) { this.keyId = keyId; return this; } @@ -137,9 +137,9 @@ public String usage() { * Set the usage value. * * @param usage the usage value to set - * @return the KeyCredential object itself. + * @return the KeyCredentialInner object itself. */ - public KeyCredential withUsage(String usage) { + public KeyCredentialInner withUsage(String usage) { this.usage = usage; return this; } @@ -157,9 +157,9 @@ public String type() { * Set the type value. * * @param type the type value to set - * @return the KeyCredential object itself. + * @return the KeyCredentialInner object itself. */ - public KeyCredential withType(String type) { + public KeyCredentialInner withType(String type) { this.type = type; return this; } diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ObjectsInner.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ObjectsInner.java index 51d87506eecef..98ae94a7696e8 100644 --- a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ObjectsInner.java +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ObjectsInner.java @@ -11,20 +11,20 @@ import retrofit2.Retrofit; import com.google.common.reflect.TypeToken; import com.microsoft.azure.AzureServiceResponseBuilder; -import com.microsoft.azure.CloudException; +import com.microsoft.azure.management.graphrbac.GraphErrorException; import com.microsoft.rest.ServiceCall; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceResponse; -import com.microsoft.rest.ServiceResponseCallback; import java.io.IOException; import okhttp3.ResponseBody; -import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Headers; import retrofit2.http.Path; import retrofit2.http.Query; import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; /** * An instance of this class provides access to all the operations defined @@ -54,67 +54,76 @@ public ObjectsInner(Retrofit retrofit, GraphRbacManagementClientImpl client) { interface ObjectsService { @Headers("Content-Type: application/json; charset=utf-8") @GET("{tenantID}/me") - Call getCurrentUser(@Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> getCurrentUser(@Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); } /** * Gets the details for current logged in user. * - * @throws CloudException exception thrown from REST call + * @throws GraphErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the AADObjectInner object wrapped in {@link ServiceResponse} if successful. + * @return the AADObjectInner object if successful. */ - public ServiceResponse getCurrentUser() throws CloudException, IOException, IllegalArgumentException { - if (this.client.tenantID() == null) { - throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - Call call = service.getCurrentUser(this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - return getCurrentUserDelegate(call.execute()); + public AADObjectInner getCurrentUser() throws GraphErrorException, IOException, IllegalArgumentException { + return getCurrentUserWithServiceResponseAsync().toBlocking().single().getBody(); } /** * Gets the details for current logged in user. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall getCurrentUserAsync(final ServiceCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall getCurrentUserAsync(final ServiceCallback serviceCallback) { + return ServiceCall.create(getCurrentUserWithServiceResponseAsync(), serviceCallback); + } + + /** + * Gets the details for current logged in user. + * + * @return the observable to the AADObjectInner object + */ + public Observable getCurrentUserAsync() { + return getCurrentUserWithServiceResponseAsync().map(new Func1, AADObjectInner>() { + @Override + public AADObjectInner call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Gets the details for current logged in user. + * + * @return the observable to the AADObjectInner object + */ + public Observable> getCurrentUserWithServiceResponseAsync() { if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Call call = service.getCurrentUser(this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - serviceCallback.success(getCurrentUserDelegate(response)); - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); + return service.getCurrentUser(this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getCurrentUserDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } } - } - }); - return serviceCall; + }); } - private ServiceResponse getCurrentUserDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return new AzureServiceResponseBuilder(this.client.mapperAdapter()) + private ServiceResponse getCurrentUserDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder(this.client.mapperAdapter()) .register(200, new TypeToken() { }.getType()) - .registerError(CloudException.class) + .registerError(GraphErrorException.class) .build(response); } diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/PasswordCredential.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/PasswordCredentialInner.java similarity index 70% rename from azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/PasswordCredential.java rename to azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/PasswordCredentialInner.java index 67660ebb9d30a..c39714365dbfe 100644 --- a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/PasswordCredential.java +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/PasswordCredentialInner.java @@ -6,31 +6,31 @@ * Code generated by Microsoft (R) AutoRest Code Generator. */ -package com.microsoft.azure.management.graphrbac; +package com.microsoft.azure.management.graphrbac.implementation; import org.joda.time.DateTime; /** - * Active Directory service principal Password Credential information. + * Active Directory PasswordCredential information. */ -public class PasswordCredential { +public class PasswordCredentialInner { /** - * Gets or sets start date. + * start date. */ private DateTime startDate; /** - * Gets or sets end date. + * end date. */ private DateTime endDate; /** - * Gets or sets key Id. + * key Id. */ private String keyId; /** - * Gets or sets value. + * value. */ private String value; @@ -47,9 +47,9 @@ public DateTime startDate() { * Set the startDate value. * * @param startDate the startDate value to set - * @return the PasswordCredential object itself. + * @return the PasswordCredentialInner object itself. */ - public PasswordCredential withStartDate(DateTime startDate) { + public PasswordCredentialInner withStartDate(DateTime startDate) { this.startDate = startDate; return this; } @@ -67,9 +67,9 @@ public DateTime endDate() { * Set the endDate value. * * @param endDate the endDate value to set - * @return the PasswordCredential object itself. + * @return the PasswordCredentialInner object itself. */ - public PasswordCredential withEndDate(DateTime endDate) { + public PasswordCredentialInner withEndDate(DateTime endDate) { this.endDate = endDate; return this; } @@ -87,9 +87,9 @@ public String keyId() { * Set the keyId value. * * @param keyId the keyId value to set - * @return the PasswordCredential object itself. + * @return the PasswordCredentialInner object itself. */ - public PasswordCredential withKeyId(String keyId) { + public PasswordCredentialInner withKeyId(String keyId) { this.keyId = keyId; return this; } @@ -107,9 +107,9 @@ public String value() { * Set the value value. * * @param value the value value to set - * @return the PasswordCredential object itself. + * @return the PasswordCredentialInner object itself. */ - public PasswordCredential withValue(String value) { + public PasswordCredentialInner withValue(String value) { this.value = value; return this; } diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ServicePrincipalCreateParametersInner.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ServicePrincipalCreateParametersInner.java index aa4aa749beced..83174b9cb180d 100644 --- a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ServicePrincipalCreateParametersInner.java +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ServicePrincipalCreateParametersInner.java @@ -8,6 +8,7 @@ package com.microsoft.azure.management.graphrbac.implementation; +import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; /** @@ -15,7 +16,7 @@ */ public class ServicePrincipalCreateParametersInner { /** - * Gets or sets application Id. + * application Id. */ @JsonProperty(required = true) private String appId; @@ -26,6 +27,16 @@ public class ServicePrincipalCreateParametersInner { @JsonProperty(required = true) private boolean accountEnabled; + /** + * the list of KeyCredential objects. + */ + private List keyCredentials; + + /** + * the list of PasswordCredential objects. + */ + private List passwordCredentials; + /** * Get the appId value. * @@ -66,4 +77,44 @@ public ServicePrincipalCreateParametersInner withAccountEnabled(boolean accountE return this; } + /** + * Get the keyCredentials value. + * + * @return the keyCredentials value + */ + public List keyCredentials() { + return this.keyCredentials; + } + + /** + * Set the keyCredentials value. + * + * @param keyCredentials the keyCredentials value to set + * @return the ServicePrincipalCreateParametersInner object itself. + */ + public ServicePrincipalCreateParametersInner withKeyCredentials(List keyCredentials) { + this.keyCredentials = keyCredentials; + return this; + } + + /** + * Get the passwordCredentials value. + * + * @return the passwordCredentials value + */ + public List passwordCredentials() { + return this.passwordCredentials; + } + + /** + * Set the passwordCredentials value. + * + * @param passwordCredentials the passwordCredentials value to set + * @return the ServicePrincipalCreateParametersInner object itself. + */ + public ServicePrincipalCreateParametersInner withPasswordCredentials(List passwordCredentials) { + this.passwordCredentials = passwordCredentials; + return this; + } + } diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ServicePrincipalImpl.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ServicePrincipalImpl.java index 93a040a896f59..c3d44c2b99f7d 100644 --- a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ServicePrincipalImpl.java +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ServicePrincipalImpl.java @@ -7,18 +7,16 @@ package com.microsoft.azure.management.graphrbac.implementation; import com.microsoft.azure.management.graphrbac.ServicePrincipal; -import com.microsoft.azure.management.resources.fluentcore.model.implementation.WrapperImpl; -import com.microsoft.rest.ServiceCall; -import com.microsoft.rest.ServiceCallback; -import com.microsoft.rest.ServiceResponse; +import com.microsoft.azure.management.resources.fluentcore.model.implementation.CreatableUpdatableImpl; +import rx.Observable; import java.util.List; /** - * Implementation for StorageAccount and its parent interfaces. + * Implementation for ServicePrincipal and its parent interfaces. */ class ServicePrincipalImpl - extends WrapperImpl + extends CreatableUpdatableImpl implements ServicePrincipal, ServicePrincipal.Definition, @@ -27,13 +25,13 @@ class ServicePrincipalImpl private ServicePrincipalCreateParametersInner createParameters; ServicePrincipalImpl(String appId, ServicePrincipalsInner client) { - super(new ServicePrincipalInner()); + super(appId, new ServicePrincipalInner()); this.client = client; this.createParameters = new ServicePrincipalCreateParametersInner().withAppId(appId); } ServicePrincipalImpl(ServicePrincipalInner innerObject, ServicePrincipalsInner client) { - super(innerObject); + super(innerObject.appId(), innerObject); this.client = client; this.createParameters = new ServicePrincipalCreateParametersInner(); } @@ -70,30 +68,17 @@ public ServicePrincipalImpl withAccountEnabled(boolean enabled) { } @Override - public ServicePrincipalImpl create() throws Exception { - this.setInner(client.create(createParameters).getBody()); - return this; + public ServicePrincipal refresh() throws Exception { + return null; } @Override - public ServiceCall createAsync(final ServiceCallback callback) { - final ServicePrincipalImpl self = this; - return client.createAsync(createParameters, new ServiceCallback() { - @Override - public void failure(Throwable t) { - callback.failure(t); - } - - @Override - public void success(ServiceResponse result) { - self.setInner(result.getBody()); - callback.success(new ServiceResponse(self, result.getResponse())); - } - }); + public Observable createResourceAsync() { + return null; } @Override - public String key() { - return objectId(); + public Observable applyAsync() { + return null; } } diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ServicePrincipalInner.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ServicePrincipalInner.java index c5b41719ebd70..b3c2dd63a7392 100644 --- a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ServicePrincipalInner.java +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ServicePrincipalInner.java @@ -15,27 +15,27 @@ */ public class ServicePrincipalInner { /** - * Gets or sets object Id. + * object Id. */ private String objectId; /** - * Gets or sets object type. + * object type. */ private String objectType; /** - * Gets or sets service principal display name. + * service principal display name. */ private String displayName; /** - * Gets or sets app id. + * app id. */ private String appId; /** - * Gets or sets the list of names. + * the list of names. */ private List servicePrincipalNames; diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ServicePrincipalsImpl.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ServicePrincipalsImpl.java index 5304ba661fc4d..1268109be659a 100644 --- a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ServicePrincipalsImpl.java +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ServicePrincipalsImpl.java @@ -6,16 +6,23 @@ package com.microsoft.azure.management.graphrbac.implementation; -import com.microsoft.azure.CloudException; +import com.microsoft.azure.Page; import com.microsoft.azure.PagedList; +import com.microsoft.azure.management.graphrbac.GraphErrorException; import com.microsoft.azure.management.graphrbac.ServicePrincipal; import com.microsoft.azure.management.graphrbac.ServicePrincipals; import com.microsoft.azure.management.resources.fluentcore.arm.collection.implementation.CreatableWrappersImpl; +import com.microsoft.rest.ServiceCall; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceResponse; +import rx.Observable; +import rx.functions.Func1; import java.io.IOException; +import java.util.List; /** - * The implementation of StorageAccounts and its parent interfaces. + * The implementation of ServicePrincipals and its parent interfaces. */ class ServicePrincipalsImpl extends CreatableWrappersImpl< @@ -34,8 +41,8 @@ class ServicePrincipalsImpl } @Override - public PagedList list() throws CloudException, IOException { - return wrapList(this.innerCollection.list().getBody()); + public PagedList list() throws GraphErrorException, IOException { + return wrapList(this.innerCollection.list()); } @Override @@ -59,7 +66,48 @@ protected ServicePrincipalImpl wrapModel(ServicePrincipalInner servicePrincipalI } @Override - public ServicePrincipalImpl getByName(String objectId) throws CloudException, IOException { - return new ServicePrincipalImpl(innerCollection.get(objectId).getBody(), innerCollection); + public ServicePrincipalImpl getByObjectId(String objectId) throws GraphErrorException, IOException { + return new ServicePrincipalImpl(innerCollection.get(objectId), innerCollection); + } + + @Override + public ServicePrincipal getByAppId(String appId) throws GraphErrorException, IOException { + return null; + } + + @Override + public ServicePrincipal getByServicePrincipalName(String spn) throws GraphErrorException, IOException { + List spList = innerCollection.list(String.format("servicePrincipalNames/any(c:c eq '%s')", spn)); + if (spList == null || spList.isEmpty()) { + return null; + } else { + return new ServicePrincipalImpl(spList.get(0), innerCollection); + } + } + + @Override + public ServiceCall getByServicePrincipalNameAsync(final String spn, final ServiceCallback callback) { + return ServiceCall.create( + getByServicePrincipalNameAsync(spn).map(new Func1>() { + @Override + public ServiceResponse call(ServicePrincipal fluentModelT) { + return new ServiceResponse<>(fluentModelT, null); + } + }), callback + ); + } + + @Override + public Observable getByServicePrincipalNameAsync(final String spn) { + return innerCollection.listAsync(String.format("servicePrincipalNames/any(c:c eq '%s')", spn)) + .map(new Func1, ServicePrincipal>() { + @Override + public ServicePrincipal call(Page result) { + if (result == null || result.getItems() == null || result.getItems().isEmpty()) { + throw new GraphErrorException("Service principal not found for SPN: " + spn); + } + return new ServicePrincipalImpl(result.getItems().get(0), innerCollection); + } + }); } } diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ServicePrincipalsInner.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ServicePrincipalsInner.java index d24ea4be93f1f..963ea8bfe2840 100644 --- a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ServicePrincipalsInner.java +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/ServicePrincipalsInner.java @@ -10,29 +10,34 @@ import retrofit2.Retrofit; import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceCall; import com.microsoft.azure.AzureServiceResponseBuilder; -import com.microsoft.azure.CloudException; import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.management.graphrbac.GraphErrorException; +import com.microsoft.azure.management.graphrbac.KeyCredentialsUpdateParameters; +import com.microsoft.azure.management.graphrbac.PasswordCredentialsUpdateParameters; import com.microsoft.azure.Page; import com.microsoft.azure.PagedList; +import com.microsoft.rest.RestException; import com.microsoft.rest.ServiceCall; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceResponse; -import com.microsoft.rest.ServiceResponseCallback; import com.microsoft.rest.Validator; import java.io.IOException; import java.util.List; import okhttp3.ResponseBody; -import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Headers; import retrofit2.http.HTTP; +import retrofit2.http.PATCH; import retrofit2.http.Path; import retrofit2.http.POST; import retrofit2.http.Query; import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; /** * An instance of this class provides access to all the operations defined @@ -62,23 +67,39 @@ public ServicePrincipalsInner(Retrofit retrofit, GraphRbacManagementClientImpl c interface ServicePrincipalsService { @Headers("Content-Type: application/json; charset=utf-8") @POST("{tenantID}/servicePrincipals") - Call create(@Path("tenantID") String tenantID, @Body ServicePrincipalCreateParametersInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> create(@Path("tenantID") String tenantID, @Body ServicePrincipalCreateParametersInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("{tenantID}/servicePrincipals") - Call list(@Path("tenantID") String tenantID, @Query("$filter") String filter, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> list(@Path("tenantID") String tenantID, @Query("$filter") String filter, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @HTTP(path = "{tenantID}/servicePrincipals/{objectId}", method = "DELETE", hasBody = true) - Call delete(@Path(value = "objectId", encoded = true) String objectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> delete(@Path(value = "objectId", encoded = true) String objectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("{tenantID}/servicePrincipals/{objectId}") - Call get(@Path(value = "objectId", encoded = true) String objectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> get(@Path(value = "objectId", encoded = true) String objectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers("Content-Type: application/json; charset=utf-8") + @GET("{tenantID}/servicePrincipals/{objectId}/keyCredentials") + Observable> listKeyCredentials(@Path(value = "objectId", encoded = true) String objectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers("Content-Type: application/json; charset=utf-8") + @PATCH("{tenantID}/servicePrincipals/{objectId}/keyCredentials") + Observable> updateKeyCredentials(@Path(value = "objectId", encoded = true) String objectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body KeyCredentialsUpdateParameters parameters, @Header("User-Agent") String userAgent); + + @Headers("Content-Type: application/json; charset=utf-8") + @GET("{tenantID}/servicePrincipals/{objectId}/passwordCredentials") + Observable> listPasswordCredentials(@Path(value = "objectId", encoded = true) String objectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers("Content-Type: application/json; charset=utf-8") + @PATCH("{tenantID}/servicePrincipals/{objectId}/passwordCredentials") + Observable> updatePasswordCredentials(@Path(value = "objectId", encoded = true) String objectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body PasswordCredentialsUpdateParameters parameters, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("{tenantID}/{nextLink}") - Call listNext(@Path(value = "nextLink", encoded = true) String nextLink, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> listNext(@Path(value = "nextLink", encoded = true) String nextLink, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); } @@ -86,24 +107,13 @@ interface ServicePrincipalsService { * Creates a service principal in the directory. * * @param parameters Parameters to create a service principal. - * @throws CloudException exception thrown from REST call + * @throws GraphErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the ServicePrincipalInner object wrapped in {@link ServiceResponse} if successful. + * @return the ServicePrincipalInner object if successful. */ - public ServiceResponse create(ServicePrincipalCreateParametersInner parameters) throws CloudException, IOException, IllegalArgumentException { - if (this.client.tenantID() == null) { - throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); - } - if (parameters == null) { - throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - Validator.validate(parameters); - Call call = service.create(this.client.tenantID(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - return createDelegate(call.execute()); + public ServicePrincipalInner create(ServicePrincipalCreateParametersInner parameters) throws GraphErrorException, IOException, IllegalArgumentException { + return createWithServiceResponseAsync(parameters).toBlocking().single().getBody(); } /** @@ -111,142 +121,179 @@ public ServiceResponse create(ServicePrincipalCreateParam * * @param parameters Parameters to create a service principal. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall createAsync(ServicePrincipalCreateParametersInner parameters, final ServiceCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall createAsync(ServicePrincipalCreateParametersInner parameters, final ServiceCallback serviceCallback) { + return ServiceCall.create(createWithServiceResponseAsync(parameters), serviceCallback); + } + + /** + * Creates a service principal in the directory. + * + * @param parameters Parameters to create a service principal. + * @return the observable to the ServicePrincipalInner object + */ + public Observable createAsync(ServicePrincipalCreateParametersInner parameters) { + return createWithServiceResponseAsync(parameters).map(new Func1, ServicePrincipalInner>() { + @Override + public ServicePrincipalInner call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Creates a service principal in the directory. + * + * @param parameters Parameters to create a service principal. + * @return the observable to the ServicePrincipalInner object + */ + public Observable> createWithServiceResponseAsync(ServicePrincipalCreateParametersInner parameters) { if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (parameters == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter parameters is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Validator.validate(parameters, serviceCallback); - Call call = service.create(this.client.tenantID(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - serviceCallback.success(createDelegate(response)); - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); + Validator.validate(parameters); + return service.create(this.client.tenantID(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = createDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } } - } - }); - return serviceCall; + }); } - private ServiceResponse createDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return new AzureServiceResponseBuilder(this.client.mapperAdapter()) + private ServiceResponse createDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder(this.client.mapperAdapter()) .register(201, new TypeToken() { }.getType()) - .registerError(CloudException.class) + .registerError(GraphErrorException.class) .build(response); } /** * Gets list of service principals from the current tenant. * - * @throws CloudException exception thrown from REST call + * @throws GraphErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<ServicePrincipalInner> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<ServicePrincipalInner> object if successful. */ - public ServiceResponse> list() throws CloudException, IOException, IllegalArgumentException { - if (this.client.tenantID() == null) { - throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - final String filter = null; - Call call = service.list(this.client.tenantID(), filter, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - ServiceResponse> response = listDelegate(call.execute()); - PagedList result = new PagedList(response.getBody()) { + public PagedList list() throws GraphErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = listSinglePageAsync().toBlocking().single(); + return new PagedList(response.getBody()) { @Override - public Page nextPage(String nextLink) throws CloudException, IOException { - return listNext(nextLink).getBody(); + public Page nextPage(String nextLink) throws RestException, IOException { + return listNextSinglePageAsync(nextLink).toBlocking().single().getBody(); } }; - return new ServiceResponse<>(result, response.getResponse()); } /** * Gets list of service principals from the current tenant. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall listAsync(final ListOperationCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall> listAsync(final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + listSinglePageAsync(), + new Func1>>>() { + @Override + public Observable>> call(String nextLink) { + return listNextSinglePageAsync(nextLink); + } + }, + serviceCallback); + } + + /** + * Gets list of service principals from the current tenant. + * + * @return the observable to the PagedList<ServicePrincipalInner> object + */ + public Observable> listAsync() { + return listWithServiceResponseAsync() + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * Gets list of service principals from the current tenant. + * + * @return the observable to the PagedList<ServicePrincipalInner> object + */ + public Observable>> listWithServiceResponseAsync() { + return listSinglePageAsync() + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextLink = page.getBody().getNextPageLink(); + if (nextLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextLink)); + } + }); + } + + /** + * Gets list of service principals from the current tenant. + * + * @return the PagedList<ServicePrincipalInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync() { if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } final String filter = null; - Call call = service.list(this.client.tenantID(), filter, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = listDelegate(response); - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - listNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); + return service.list(this.client.tenantID(), filter, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); } - } - }); - return serviceCall; + }); } /** * Gets list of service principals from the current tenant. * * @param filter The filter to apply on the operation. - * @throws CloudException exception thrown from REST call + * @throws GraphErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<ServicePrincipalInner> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<ServicePrincipalInner> object if successful. */ - public ServiceResponse> list(final String filter) throws CloudException, IOException, IllegalArgumentException { - if (this.client.tenantID() == null) { - throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - Call call = service.list(this.client.tenantID(), filter, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - ServiceResponse> response = listDelegate(call.execute()); - PagedList result = new PagedList(response.getBody()) { + public PagedList list(final String filter) throws GraphErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = listSinglePageAsync(filter).toBlocking().single(); + return new PagedList(response.getBody()) { @Override - public Page nextPage(String nextLink) throws CloudException, IOException { - return listNext(nextLink).getBody(); + public Page nextPage(String nextLink) throws RestException, IOException { + return listNextSinglePageAsync(nextLink).toBlocking().single().getBody(); } }; - return new ServiceResponse<>(result, response.getResponse()); } /** @@ -254,47 +301,87 @@ public Page nextPage(String nextLink) throws CloudExcepti * * @param filter The filter to apply on the operation. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall listAsync(final String filter, final ListOperationCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall> listAsync(final String filter, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + listSinglePageAsync(filter), + new Func1>>>() { + @Override + public Observable>> call(String nextLink) { + return listNextSinglePageAsync(nextLink); + } + }, + serviceCallback); + } + + /** + * Gets list of service principals from the current tenant. + * + * @param filter The filter to apply on the operation. + * @return the observable to the PagedList<ServicePrincipalInner> object + */ + public Observable> listAsync(final String filter) { + return listWithServiceResponseAsync(filter) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * Gets list of service principals from the current tenant. + * + * @param filter The filter to apply on the operation. + * @return the observable to the PagedList<ServicePrincipalInner> object + */ + public Observable>> listWithServiceResponseAsync(final String filter) { + return listSinglePageAsync(filter) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextLink = page.getBody().getNextPageLink(); + if (nextLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextLink)); + } + }); + } + + /** + * Gets list of service principals from the current tenant. + * + ServiceResponse> * @param filter The filter to apply on the operation. + * @return the PagedList<ServicePrincipalInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync(final String filter) { if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Call call = service.list(this.client.tenantID(), filter, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = listDelegate(response); - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - listNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); + return service.list(this.client.tenantID(), filter, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); } - } - }); - return serviceCall; + }); } - private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return new AzureServiceResponseBuilder, CloudException>(this.client.mapperAdapter()) + private ServiceResponse> listDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder, GraphErrorException>(this.client.mapperAdapter()) .register(200, new TypeToken>() { }.getType()) - .registerError(CloudException.class) + .registerError(GraphErrorException.class) .build(response); } @@ -302,12 +389,47 @@ private ServiceResponse> listDelegate(Response< * Deletes service principal from the directory. * * @param objectId Object id to delete service principal information. - * @throws CloudException exception thrown from REST call + * @throws GraphErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters + */ + public void delete(String objectId) throws GraphErrorException, IOException, IllegalArgumentException { + deleteWithServiceResponseAsync(objectId).toBlocking().single().getBody(); + } + + /** + * Deletes service principal from the directory. + * + * @param objectId Object id to delete service principal information. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceCall} object + */ + public ServiceCall deleteAsync(String objectId, final ServiceCallback serviceCallback) { + return ServiceCall.create(deleteWithServiceResponseAsync(objectId), serviceCallback); + } + + /** + * Deletes service principal from the directory. + * + * @param objectId Object id to delete service principal information. + * @return the {@link ServiceResponse} object if successful. + */ + public Observable deleteAsync(String objectId) { + return deleteWithServiceResponseAsync(objectId).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Deletes service principal from the directory. + * + * @param objectId Object id to delete service principal information. * @return the {@link ServiceResponse} object if successful. */ - public ServiceResponse delete(String objectId) throws CloudException, IOException, IllegalArgumentException { + public Observable> deleteWithServiceResponseAsync(String objectId) { if (objectId == null) { throw new IllegalArgumentException("Parameter objectId is required and cannot be null."); } @@ -317,65 +439,225 @@ public ServiceResponse delete(String objectId) throws CloudException, IOEx if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Call call = service.delete(objectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - return deleteDelegate(call.execute()); + return service.delete(objectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = deleteDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse deleteDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder(this.client.mapperAdapter()) + .register(204, new TypeToken() { }.getType()) + .registerError(GraphErrorException.class) + .build(response); } /** - * Deletes service principal from the directory. + * Gets service principal information from the directory. * - * @param objectId Object id to delete service principal information. + * @param objectId Object id to get service principal information. + * @throws GraphErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the ServicePrincipalInner object if successful. + */ + public ServicePrincipalInner get(String objectId) throws GraphErrorException, IOException, IllegalArgumentException { + return getWithServiceResponseAsync(objectId).toBlocking().single().getBody(); + } + + /** + * Gets service principal information from the directory. + * + * @param objectId Object id to get service principal information. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall deleteAsync(String objectId, final ServiceCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall getAsync(String objectId, final ServiceCallback serviceCallback) { + return ServiceCall.create(getWithServiceResponseAsync(objectId), serviceCallback); + } + + /** + * Gets service principal information from the directory. + * + * @param objectId Object id to get service principal information. + * @return the observable to the ServicePrincipalInner object + */ + public Observable getAsync(String objectId) { + return getWithServiceResponseAsync(objectId).map(new Func1, ServicePrincipalInner>() { + @Override + public ServicePrincipalInner call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Gets service principal information from the directory. + * + * @param objectId Object id to get service principal information. + * @return the observable to the ServicePrincipalInner object + */ + public Observable> getWithServiceResponseAsync(String objectId) { if (objectId == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter objectId is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter objectId is required and cannot be null."); } if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Call call = service.delete(objectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - serviceCallback.success(deleteDelegate(response)); - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); + return service.get(objectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } } + }); + } + + private ServiceResponse getDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder(this.client.mapperAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(GraphErrorException.class) + .build(response); + } + + /** + * Get keyCredentials associated with the service principal by object Id. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#keycredential-type. + * + * @param objectId Object id to get service principal information. + * @throws GraphErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the List<KeyCredentialInner> object if successful. + */ + public List listKeyCredentials(String objectId) throws GraphErrorException, IOException, IllegalArgumentException { + return listKeyCredentialsWithServiceResponseAsync(objectId).toBlocking().single().getBody(); + } + + /** + * Get keyCredentials associated with the service principal by object Id. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#keycredential-type. + * + * @param objectId Object id to get service principal information. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceCall} object + */ + public ServiceCall> listKeyCredentialsAsync(String objectId, final ServiceCallback> serviceCallback) { + return ServiceCall.create(listKeyCredentialsWithServiceResponseAsync(objectId), serviceCallback); + } + + /** + * Get keyCredentials associated with the service principal by object Id. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#keycredential-type. + * + * @param objectId Object id to get service principal information. + * @return the observable to the List<KeyCredentialInner> object + */ + public Observable> listKeyCredentialsAsync(String objectId) { + return listKeyCredentialsWithServiceResponseAsync(objectId).map(new Func1>, List>() { + @Override + public List call(ServiceResponse> response) { + return response.getBody(); } }); - return serviceCall; } - private ServiceResponse deleteDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return new AzureServiceResponseBuilder(this.client.mapperAdapter()) - .register(204, new TypeToken() { }.getType()) + /** + * Get keyCredentials associated with the service principal by object Id. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#keycredential-type. + * + * @param objectId Object id to get service principal information. + * @return the observable to the List<KeyCredentialInner> object + */ + public Observable>> listKeyCredentialsWithServiceResponseAsync(String objectId) { + if (objectId == null) { + throw new IllegalArgumentException("Parameter objectId is required and cannot be null."); + } + if (this.client.tenantID() == null) { + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.listKeyCredentials(objectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listKeyCredentialsDelegate(response); + ServiceResponse> clientResponse = new ServiceResponse>(result.getBody().getItems(), result.getResponse()); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listKeyCredentialsDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder, GraphErrorException>(this.client.mapperAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(GraphErrorException.class) .build(response); } /** - * Gets service principal information from the directory. + * Update keyCredentials associated with an existing service principal. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#keycredential-type. * * @param objectId Object id to get service principal information. - * @throws CloudException exception thrown from REST call + * @throws GraphErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the ServicePrincipalInner object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse get(String objectId) throws CloudException, IOException, IllegalArgumentException { + public void updateKeyCredentials(String objectId) throws GraphErrorException, IOException, IllegalArgumentException { + updateKeyCredentialsWithServiceResponseAsync(objectId).toBlocking().single().getBody(); + } + + /** + * Update keyCredentials associated with an existing service principal. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#keycredential-type. + * + * @param objectId Object id to get service principal information. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceCall} object + */ + public ServiceCall updateKeyCredentialsAsync(String objectId, final ServiceCallback serviceCallback) { + return ServiceCall.create(updateKeyCredentialsWithServiceResponseAsync(objectId), serviceCallback); + } + + /** + * Update keyCredentials associated with an existing service principal. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#keycredential-type. + * + * @param objectId Object id to get service principal information. + * @return the {@link ServiceResponse} object if successful. + */ + public Observable updateKeyCredentialsAsync(String objectId) { + return updateKeyCredentialsWithServiceResponseAsync(objectId).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Update keyCredentials associated with an existing service principal. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#keycredential-type. + * + * @param objectId Object id to get service principal information. + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> updateKeyCredentialsWithServiceResponseAsync(String objectId) { if (objectId == null) { throw new IllegalArgumentException("Parameter objectId is required and cannot be null."); } @@ -385,68 +667,229 @@ public ServiceResponse get(String objectId) throws CloudE if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Call call = service.get(objectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - return getDelegate(call.execute()); + final List value = null; + KeyCredentialsUpdateParameters parameters = new KeyCredentialsUpdateParameters(); + parameters.withValue(null); + return service.updateKeyCredentials(objectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = updateKeyCredentialsDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); } /** - * Gets service principal information from the directory. + * Update keyCredentials associated with an existing service principal. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#keycredential-type. * * @param objectId Object id to get service principal information. + * @param value KeyCredential list. + * @throws GraphErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + */ + public void updateKeyCredentials(String objectId, List value) throws GraphErrorException, IOException, IllegalArgumentException { + updateKeyCredentialsWithServiceResponseAsync(objectId, value).toBlocking().single().getBody(); + } + + /** + * Update keyCredentials associated with an existing service principal. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#keycredential-type. + * + * @param objectId Object id to get service principal information. + * @param value KeyCredential list. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall getAsync(String objectId, final ServiceCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall updateKeyCredentialsAsync(String objectId, List value, final ServiceCallback serviceCallback) { + return ServiceCall.create(updateKeyCredentialsWithServiceResponseAsync(objectId, value), serviceCallback); + } + + /** + * Update keyCredentials associated with an existing service principal. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#keycredential-type. + * + * @param objectId Object id to get service principal information. + * @param value KeyCredential list. + * @return the {@link ServiceResponse} object if successful. + */ + public Observable updateKeyCredentialsAsync(String objectId, List value) { + return updateKeyCredentialsWithServiceResponseAsync(objectId, value).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Update keyCredentials associated with an existing service principal. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#keycredential-type. + * + * @param objectId Object id to get service principal information. + * @param value KeyCredential list. + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> updateKeyCredentialsWithServiceResponseAsync(String objectId, List value) { if (objectId == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter objectId is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter objectId is required and cannot be null."); } if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Call call = service.get(objectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - serviceCallback.success(getDelegate(response)); - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); + Validator.validate(value); + KeyCredentialsUpdateParameters parameters = new KeyCredentialsUpdateParameters(); + parameters.withValue(value); + return service.updateKeyCredentials(objectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = updateKeyCredentialsDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } } + }); + } + + private ServiceResponse updateKeyCredentialsDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder(this.client.mapperAdapter()) + .register(204, new TypeToken() { }.getType()) + .registerError(GraphErrorException.class) + .build(response); + } + + /** + * Gets passwordCredentials associated with an existing service principal. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#passwordcredential-type. + * + * @param objectId Object id to get service principal information. + * @throws GraphErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the List<PasswordCredentialInner> object if successful. + */ + public List listPasswordCredentials(String objectId) throws GraphErrorException, IOException, IllegalArgumentException { + return listPasswordCredentialsWithServiceResponseAsync(objectId).toBlocking().single().getBody(); + } + + /** + * Gets passwordCredentials associated with an existing service principal. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#passwordcredential-type. + * + * @param objectId Object id to get service principal information. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceCall} object + */ + public ServiceCall> listPasswordCredentialsAsync(String objectId, final ServiceCallback> serviceCallback) { + return ServiceCall.create(listPasswordCredentialsWithServiceResponseAsync(objectId), serviceCallback); + } + + /** + * Gets passwordCredentials associated with an existing service principal. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#passwordcredential-type. + * + * @param objectId Object id to get service principal information. + * @return the observable to the List<PasswordCredentialInner> object + */ + public Observable> listPasswordCredentialsAsync(String objectId) { + return listPasswordCredentialsWithServiceResponseAsync(objectId).map(new Func1>, List>() { + @Override + public List call(ServiceResponse> response) { + return response.getBody(); } }); - return serviceCall; } - private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return new AzureServiceResponseBuilder(this.client.mapperAdapter()) - .register(200, new TypeToken() { }.getType()) - .registerError(CloudException.class) + /** + * Gets passwordCredentials associated with an existing service principal. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#passwordcredential-type. + * + * @param objectId Object id to get service principal information. + * @return the observable to the List<PasswordCredentialInner> object + */ + public Observable>> listPasswordCredentialsWithServiceResponseAsync(String objectId) { + if (objectId == null) { + throw new IllegalArgumentException("Parameter objectId is required and cannot be null."); + } + if (this.client.tenantID() == null) { + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.listPasswordCredentials(objectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listPasswordCredentialsDelegate(response); + ServiceResponse> clientResponse = new ServiceResponse>(result.getBody().getItems(), result.getResponse()); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listPasswordCredentialsDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder, GraphErrorException>(this.client.mapperAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(GraphErrorException.class) .build(response); } /** - * Gets list of service principals from the current tenant. + * Updates passwordCredentials associated with an existing service principal. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#passwordcredential-type. * - * @param nextLink Next link for list operation. - * @throws CloudException exception thrown from REST call + * @param objectId Object id to get service principal information. + * @throws GraphErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<ServicePrincipalInner> object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse> listNext(final String nextLink) throws CloudException, IOException, IllegalArgumentException { - if (nextLink == null) { - throw new IllegalArgumentException("Parameter nextLink is required and cannot be null."); + public void updatePasswordCredentials(String objectId) throws GraphErrorException, IOException, IllegalArgumentException { + updatePasswordCredentialsWithServiceResponseAsync(objectId).toBlocking().single().getBody(); + } + + /** + * Updates passwordCredentials associated with an existing service principal. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#passwordcredential-type. + * + * @param objectId Object id to get service principal information. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceCall} object + */ + public ServiceCall updatePasswordCredentialsAsync(String objectId, final ServiceCallback serviceCallback) { + return ServiceCall.create(updatePasswordCredentialsWithServiceResponseAsync(objectId), serviceCallback); + } + + /** + * Updates passwordCredentials associated with an existing service principal. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#passwordcredential-type. + * + * @param objectId Object id to get service principal information. + * @return the {@link ServiceResponse} object if successful. + */ + public Observable updatePasswordCredentialsAsync(String objectId) { + return updatePasswordCredentialsWithServiceResponseAsync(objectId).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Updates passwordCredentials associated with an existing service principal. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#passwordcredential-type. + * + * @param objectId Object id to get service principal information. + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> updatePasswordCredentialsWithServiceResponseAsync(String objectId) { + if (objectId == null) { + throw new IllegalArgumentException("Parameter objectId is required and cannot be null."); } if (this.client.tenantID() == null) { throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); @@ -454,8 +897,122 @@ public ServiceResponse> listNext(final String n if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Call call = service.listNext(nextLink, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - return listNextDelegate(call.execute()); + final List value = null; + PasswordCredentialsUpdateParameters parameters = new PasswordCredentialsUpdateParameters(); + parameters.withValue(null); + return service.updatePasswordCredentials(objectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = updatePasswordCredentialsDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Updates passwordCredentials associated with an existing service principal. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#passwordcredential-type. + * + * @param objectId Object id to get service principal information. + * @param value PasswordCredential list. + * @throws GraphErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + */ + public void updatePasswordCredentials(String objectId, List value) throws GraphErrorException, IOException, IllegalArgumentException { + updatePasswordCredentialsWithServiceResponseAsync(objectId, value).toBlocking().single().getBody(); + } + + /** + * Updates passwordCredentials associated with an existing service principal. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#passwordcredential-type. + * + * @param objectId Object id to get service principal information. + * @param value PasswordCredential list. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceCall} object + */ + public ServiceCall updatePasswordCredentialsAsync(String objectId, List value, final ServiceCallback serviceCallback) { + return ServiceCall.create(updatePasswordCredentialsWithServiceResponseAsync(objectId, value), serviceCallback); + } + + /** + * Updates passwordCredentials associated with an existing service principal. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#passwordcredential-type. + * + * @param objectId Object id to get service principal information. + * @param value PasswordCredential list. + * @return the {@link ServiceResponse} object if successful. + */ + public Observable updatePasswordCredentialsAsync(String objectId, List value) { + return updatePasswordCredentialsWithServiceResponseAsync(objectId, value).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Updates passwordCredentials associated with an existing service principal. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#passwordcredential-type. + * + * @param objectId Object id to get service principal information. + * @param value PasswordCredential list. + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> updatePasswordCredentialsWithServiceResponseAsync(String objectId, List value) { + if (objectId == null) { + throw new IllegalArgumentException("Parameter objectId is required and cannot be null."); + } + if (this.client.tenantID() == null) { + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(value); + PasswordCredentialsUpdateParameters parameters = new PasswordCredentialsUpdateParameters(); + parameters.withValue(value); + return service.updatePasswordCredentials(objectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = updatePasswordCredentialsDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse updatePasswordCredentialsDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder(this.client.mapperAdapter()) + .register(204, new TypeToken() { }.getType()) + .registerError(GraphErrorException.class) + .build(response); + } + + /** + * Gets list of service principals from the current tenant. + * + * @param nextLink Next link for list operation. + * @throws GraphErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the PagedList<ServicePrincipalInner> object if successful. + */ + public PagedList listNext(final String nextLink) throws GraphErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = listNextSinglePageAsync(nextLink).toBlocking().single(); + return new PagedList(response.getBody()) { + @Override + public Page nextPage(String nextLink) throws RestException, IOException { + return listNextSinglePageAsync(nextLink).toBlocking().single().getBody(); + } + }; } /** @@ -464,51 +1021,90 @@ public ServiceResponse> listNext(final String n * @param nextLink Next link for list operation. * @param serviceCall the ServiceCall object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall listNextAsync(final String nextLink, final ServiceCall serviceCall, final ListOperationCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall> listNextAsync(final String nextLink, final ServiceCall> serviceCall, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + listNextSinglePageAsync(nextLink), + new Func1>>>() { + @Override + public Observable>> call(String nextLink) { + return listNextSinglePageAsync(nextLink); + } + }, + serviceCallback); + } + + /** + * Gets list of service principals from the current tenant. + * + * @param nextLink Next link for list operation. + * @return the observable to the PagedList<ServicePrincipalInner> object + */ + public Observable> listNextAsync(final String nextLink) { + return listNextWithServiceResponseAsync(nextLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * Gets list of service principals from the current tenant. + * + * @param nextLink Next link for list operation. + * @return the observable to the PagedList<ServicePrincipalInner> object + */ + public Observable>> listNextWithServiceResponseAsync(final String nextLink) { + return listNextSinglePageAsync(nextLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextLink = page.getBody().getNextPageLink(); + if (nextLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextLink)); + } + }); + } + + /** + * Gets list of service principals from the current tenant. + * + ServiceResponse> * @param nextLink Next link for list operation. + * @return the PagedList<ServicePrincipalInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listNextSinglePageAsync(final String nextLink) { if (nextLink == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter nextLink is required and cannot be null."); } if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Call call = service.listNext(nextLink, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - serviceCall.newCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = listNextDelegate(response); - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - listNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); + return service.listNext(nextLink, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listNextDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); } - } - }); - return serviceCall; + }); } - private ServiceResponse> listNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return new AzureServiceResponseBuilder, CloudException>(this.client.mapperAdapter()) + private ServiceResponse> listNextDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder, GraphErrorException>(this.client.mapperAdapter()) .register(200, new TypeToken>() { }.getType()) - .registerError(CloudException.class) + .registerError(GraphErrorException.class) .build(response); } diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/UserImpl.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/UserImpl.java index fb48278c65ff2..1180a58cac48e 100644 --- a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/UserImpl.java +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/UserImpl.java @@ -8,16 +8,14 @@ import com.microsoft.azure.management.graphrbac.PasswordProfile; import com.microsoft.azure.management.graphrbac.User; -import com.microsoft.azure.management.resources.fluentcore.model.implementation.WrapperImpl; -import com.microsoft.rest.ServiceCall; -import com.microsoft.rest.ServiceCallback; -import com.microsoft.rest.ServiceResponse; +import com.microsoft.azure.management.resources.fluentcore.model.implementation.CreatableUpdatableImpl; +import rx.Observable; /** - * Implementation for StorageAccount and its parent interfaces. + * Implementation for User and its parent interfaces. */ class UserImpl - extends WrapperImpl + extends CreatableUpdatableImpl implements User, User.Definition, @@ -26,13 +24,13 @@ class UserImpl private UserCreateParametersInner createParameters; UserImpl(String userPrincipalName, UsersInner client) { - super(new UserInner()); + super(userPrincipalName, new UserInner()); this.client = client; this.createParameters = new UserCreateParametersInner().withUserPrincipalName(userPrincipalName); } UserImpl(UserInner innerObject, UsersInner client) { - super(innerObject); + super(innerObject.userPrincipalName(), innerObject); this.client = client; this.createParameters = new UserCreateParametersInner(); } @@ -72,34 +70,6 @@ public String mailNickname() { return inner().mailNickname(); } - @Override - public UserImpl create() throws Exception { - setInner(client.create(createParameters).getBody()); - return this; - } - - @Override - public ServiceCall createAsync(final ServiceCallback callback) { - final UserImpl self = this; - return client.createAsync(createParameters, new ServiceCallback() { - @Override - public void failure(Throwable t) { - callback.failure(t); - } - - @Override - public void success(ServiceResponse result) { - setInner(result.getBody()); - callback.success(new ServiceResponse(self, result.getResponse())); - } - }); - } - - @Override - public String key() { - return objectId(); - } - @Override public UserImpl withAccountEnabled(boolean enabled) { createParameters.withAccountEnabled(enabled); @@ -129,4 +99,19 @@ public UserImpl withPassword(String password, boolean forceChangePasswordNextLog createParameters.withPasswordProfile(new PasswordProfile().withPassword(password).withForceChangePasswordNextLogin(forceChangePasswordNextLogin)); return this; } + + @Override + public User refresh() throws Exception { + return null; + } + + @Override + public Observable createResourceAsync() { + return null; + } + + @Override + public Observable applyAsync() { + return null; + } } diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/UserInner.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/UserInner.java index 33cff51127ea8..00785fa6dc3e4 100644 --- a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/UserInner.java +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/UserInner.java @@ -14,32 +14,32 @@ */ public class UserInner { /** - * Gets or sets object Id. + * object Id. */ private String objectId; /** - * Gets or sets object type. + * object type. */ private String objectType; /** - * Gets or sets user principal name. + * user principal name. */ private String userPrincipalName; /** - * Gets or sets user display name. + * user display name. */ private String displayName; /** - * Gets or sets user signIn name. + * user signIn name. */ private String signInName; /** - * Gets or sets user mail. + * user mail. */ private String mail; diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/UsersImpl.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/UsersImpl.java index 782959a65bee8..6f4504497f9f2 100644 --- a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/UsersImpl.java +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/UsersImpl.java @@ -6,16 +6,22 @@ package com.microsoft.azure.management.graphrbac.implementation; -import com.microsoft.azure.CloudException; import com.microsoft.azure.PagedList; +import com.microsoft.azure.management.graphrbac.GraphErrorException; import com.microsoft.azure.management.graphrbac.User; import com.microsoft.azure.management.graphrbac.Users; import com.microsoft.azure.management.resources.fluentcore.arm.collection.implementation.CreatableWrappersImpl; +import com.microsoft.rest.RestException; +import com.microsoft.rest.ServiceCall; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceResponse; +import rx.Observable; +import rx.functions.Func1; import java.io.IOException; /** - * The implementation of StorageAccounts and its parent interfaces. + * The implementation of Users and its parent interfaces. */ class UsersImpl extends CreatableWrappersImpl< @@ -34,8 +40,8 @@ class UsersImpl } @Override - public PagedList list() throws CloudException, IOException { - return wrapList(this.innerCollection.list().getBody()); + public PagedList list() throws RestException, IOException { + return wrapList(this.innerCollection.list()); } @Override @@ -44,8 +50,8 @@ public void delete(String id) throws Exception { } @Override - public UserImpl define(String userPrincipalName) { - return wrapModel(userPrincipalName); + public UserImpl define(String name) { + return wrapModel(name); } @Override @@ -59,7 +65,35 @@ protected UserImpl wrapModel(UserInner userInner) { } @Override - public UserImpl getByName(String upnOrId) throws CloudException, IOException { - return new UserImpl(innerCollection.get(upnOrId).getBody(), innerCollection); + public UserImpl getByObjectId(String objectId) throws GraphErrorException, IOException { + return new UserImpl(innerCollection.get(objectId), innerCollection); + } + + @Override + public UserImpl getByUserPrincipalName(String upn) throws GraphErrorException, IOException { + return new UserImpl(innerCollection.get(upn), innerCollection); + } + + @Override + public ServiceCall getByUserPrincipalNameAsync(String upn, final ServiceCallback callback) { + return ServiceCall.create( + getByUserPrincipalNameAsync(upn).map(new Func1>() { + @Override + public ServiceResponse call(User fluentModelT) { + return new ServiceResponse<>(fluentModelT, null); + } + }), callback + ); + } + + @Override + public Observable getByUserPrincipalNameAsync(String upn) { + return innerCollection.getAsync(upn) + .map(new Func1() { + @Override + public User call(UserInner userInnerServiceResponse) { + return new UserImpl(userInnerServiceResponse, innerCollection); + } + }); } } diff --git a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/UsersInner.java b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/UsersInner.java index d9a3e5da72c71..91499376d8cdd 100644 --- a/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/UsersInner.java +++ b/azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/UsersInner.java @@ -8,34 +8,35 @@ package com.microsoft.azure.management.graphrbac.implementation; +import retrofit2.Retrofit; import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceCall; import com.microsoft.azure.AzureServiceResponseBuilder; -import com.microsoft.azure.CloudException; import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.management.graphrbac.GraphErrorException; +import com.microsoft.azure.management.graphrbac.UserGetMemberGroupsParameters; import com.microsoft.azure.Page; import com.microsoft.azure.PagedList; -import com.microsoft.azure.management.graphrbac.UserGetMemberGroupsParameters; +import com.microsoft.rest.RestException; import com.microsoft.rest.ServiceCall; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceResponse; -import com.microsoft.rest.ServiceResponseCallback; import com.microsoft.rest.Validator; +import java.io.IOException; +import java.util.List; import okhttp3.ResponseBody; -import retrofit2.Call; -import retrofit2.Response; -import retrofit2.Retrofit; import retrofit2.http.Body; import retrofit2.http.GET; -import retrofit2.http.HTTP; import retrofit2.http.Header; import retrofit2.http.Headers; +import retrofit2.http.HTTP; import retrofit2.http.PATCH; -import retrofit2.http.POST; import retrofit2.http.Path; +import retrofit2.http.POST; import retrofit2.http.Query; - -import java.io.IOException; -import java.util.List; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; /** * An instance of this class provides access to all the operations defined @@ -65,31 +66,31 @@ public UsersInner(Retrofit retrofit, GraphRbacManagementClientImpl client) { interface UsersService { @Headers("Content-Type: application/json; charset=utf-8") @POST("{tenantID}/users") - Call create(@Path("tenantID") String tenantID, @Body UserCreateParametersInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> create(@Path("tenantID") String tenantID, @Body UserCreateParametersInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("{tenantID}/users") - Call list(@Path("tenantID") String tenantID, @Query("$filter") String filter, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> list(@Path("tenantID") String tenantID, @Query("$filter") String filter, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("{tenantID}/users/{upnOrObjectId}") - Call get(@Path(value = "upnOrObjectId", encoded = true) String upnOrObjectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> get(@Path(value = "upnOrObjectId", encoded = true) String upnOrObjectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @PATCH("{tenantID}/users/{upnOrObjectId}") - Call update(@Path(value = "upnOrObjectId", encoded = true) String upnOrObjectId, @Path("tenantID") String tenantID, @Body UserUpdateParametersInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> update(@Path(value = "upnOrObjectId", encoded = true) String upnOrObjectId, @Path("tenantID") String tenantID, @Body UserUpdateParametersInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @HTTP(path = "{tenantID}/users/{upnOrObjectId}", method = "DELETE", hasBody = true) - Call delete(@Path(value = "upnOrObjectId", encoded = true) String upnOrObjectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> delete(@Path(value = "upnOrObjectId", encoded = true) String upnOrObjectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @POST("{tenantID}/users/{objectId}/getMemberGroups") - Call getMemberGroups(@Path(value = "objectId", encoded = true) String objectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body UserGetMemberGroupsParameters parameters, @Header("User-Agent") String userAgent); + Observable> getMemberGroups(@Path(value = "objectId", encoded = true) String objectId, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body UserGetMemberGroupsParameters parameters, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("{tenantID}/{nextLink}") - Call listNext(@Path(value = "nextLink", encoded = true) String nextLink, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> listNext(@Path(value = "nextLink", encoded = true) String nextLink, @Path("tenantID") String tenantID, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); } @@ -97,24 +98,13 @@ interface UsersService { * Create a new user. Reference: https://msdn.microsoft.com/library/azure/ad/graph/api/users-operations#CreateUser. * * @param parameters Parameters to create a user. - * @throws CloudException exception thrown from REST call + * @throws GraphErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the UserInner object wrapped in {@link ServiceResponse} if successful. + * @return the UserInner object if successful. */ - public ServiceResponse create(UserCreateParametersInner parameters) throws CloudException, IOException, IllegalArgumentException { - if (this.client.tenantID() == null) { - throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); - } - if (parameters == null) { - throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - Validator.validate(parameters); - Call call = service.create(this.client.tenantID(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - return createDelegate(call.execute()); + public UserInner create(UserCreateParametersInner parameters) throws GraphErrorException, IOException, IllegalArgumentException { + return createWithServiceResponseAsync(parameters).toBlocking().single().getBody(); } /** @@ -122,142 +112,179 @@ public ServiceResponse create(UserCreateParametersInner parameters) t * * @param parameters Parameters to create a user. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall createAsync(UserCreateParametersInner parameters, final ServiceCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall createAsync(UserCreateParametersInner parameters, final ServiceCallback serviceCallback) { + return ServiceCall.create(createWithServiceResponseAsync(parameters), serviceCallback); + } + + /** + * Create a new user. Reference: https://msdn.microsoft.com/library/azure/ad/graph/api/users-operations#CreateUser. + * + * @param parameters Parameters to create a user. + * @return the observable to the UserInner object + */ + public Observable createAsync(UserCreateParametersInner parameters) { + return createWithServiceResponseAsync(parameters).map(new Func1, UserInner>() { + @Override + public UserInner call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Create a new user. Reference: https://msdn.microsoft.com/library/azure/ad/graph/api/users-operations#CreateUser. + * + * @param parameters Parameters to create a user. + * @return the observable to the UserInner object + */ + public Observable> createWithServiceResponseAsync(UserCreateParametersInner parameters) { if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (parameters == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter parameters is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Validator.validate(parameters, serviceCallback); - Call call = service.create(this.client.tenantID(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - serviceCallback.success(createDelegate(response)); - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); + Validator.validate(parameters); + return service.create(this.client.tenantID(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = createDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } } - } - }); - return serviceCall; + }); } - private ServiceResponse createDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return new AzureServiceResponseBuilder(this.client.mapperAdapter()) + private ServiceResponse createDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder(this.client.mapperAdapter()) .register(201, new TypeToken() { }.getType()) - .registerError(CloudException.class) + .registerError(GraphErrorException.class) .build(response); } /** * Gets list of users for the current tenant. Reference https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/users-operations#GetUsers. * - * @throws CloudException exception thrown from REST call + * @throws GraphErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<UserInner> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<UserInner> object if successful. */ - public ServiceResponse> list() throws CloudException, IOException, IllegalArgumentException { - if (this.client.tenantID() == null) { - throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - final String filter = null; - Call call = service.list(this.client.tenantID(), filter, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - ServiceResponse> response = listDelegate(call.execute()); - PagedList result = new PagedList(response.getBody()) { + public PagedList list() throws GraphErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = listSinglePageAsync().toBlocking().single(); + return new PagedList(response.getBody()) { @Override - public Page nextPage(String nextLink) throws CloudException, IOException { - return listNext(nextLink).getBody(); + public Page nextPage(String nextLink) throws RestException, IOException { + return listNextSinglePageAsync(nextLink).toBlocking().single().getBody(); } }; - return new ServiceResponse<>(result, response.getResponse()); } /** * Gets list of users for the current tenant. Reference https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/users-operations#GetUsers. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall listAsync(final ListOperationCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall> listAsync(final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + listSinglePageAsync(), + new Func1>>>() { + @Override + public Observable>> call(String nextLink) { + return listNextSinglePageAsync(nextLink); + } + }, + serviceCallback); + } + + /** + * Gets list of users for the current tenant. Reference https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/users-operations#GetUsers. + * + * @return the observable to the PagedList<UserInner> object + */ + public Observable> listAsync() { + return listWithServiceResponseAsync() + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * Gets list of users for the current tenant. Reference https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/users-operations#GetUsers. + * + * @return the observable to the PagedList<UserInner> object + */ + public Observable>> listWithServiceResponseAsync() { + return listSinglePageAsync() + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextLink = page.getBody().getNextPageLink(); + if (nextLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextLink)); + } + }); + } + + /** + * Gets list of users for the current tenant. Reference https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/users-operations#GetUsers. + * + * @return the PagedList<UserInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync() { if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } final String filter = null; - Call call = service.list(this.client.tenantID(), filter, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = listDelegate(response); - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - listNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); + return service.list(this.client.tenantID(), filter, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); } - } - }); - return serviceCall; + }); } /** * Gets list of users for the current tenant. Reference https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/users-operations#GetUsers. * * @param filter The filter to apply on the operation. - * @throws CloudException exception thrown from REST call + * @throws GraphErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<UserInner> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<UserInner> object if successful. */ - public ServiceResponse> list(final String filter) throws CloudException, IOException, IllegalArgumentException { - if (this.client.tenantID() == null) { - throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - Call call = service.list(this.client.tenantID(), filter, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - ServiceResponse> response = listDelegate(call.execute()); - PagedList result = new PagedList(response.getBody()) { + public PagedList list(final String filter) throws GraphErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = listSinglePageAsync(filter).toBlocking().single(); + return new PagedList(response.getBody()) { @Override - public Page nextPage(String nextLink) throws CloudException, IOException { - return listNext(nextLink).getBody(); + public Page nextPage(String nextLink) throws RestException, IOException { + return listNextSinglePageAsync(nextLink).toBlocking().single().getBody(); } }; - return new ServiceResponse<>(result, response.getResponse()); } /** @@ -265,47 +292,87 @@ public Page nextPage(String nextLink) throws CloudException, IOExcept * * @param filter The filter to apply on the operation. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall listAsync(final String filter, final ListOperationCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall> listAsync(final String filter, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + listSinglePageAsync(filter), + new Func1>>>() { + @Override + public Observable>> call(String nextLink) { + return listNextSinglePageAsync(nextLink); + } + }, + serviceCallback); + } + + /** + * Gets list of users for the current tenant. Reference https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/users-operations#GetUsers. + * + * @param filter The filter to apply on the operation. + * @return the observable to the PagedList<UserInner> object + */ + public Observable> listAsync(final String filter) { + return listWithServiceResponseAsync(filter) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * Gets list of users for the current tenant. Reference https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/users-operations#GetUsers. + * + * @param filter The filter to apply on the operation. + * @return the observable to the PagedList<UserInner> object + */ + public Observable>> listWithServiceResponseAsync(final String filter) { + return listSinglePageAsync(filter) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextLink = page.getBody().getNextPageLink(); + if (nextLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextLink)); + } + }); + } + + /** + * Gets list of users for the current tenant. Reference https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/users-operations#GetUsers. + * + ServiceResponse> * @param filter The filter to apply on the operation. + * @return the PagedList<UserInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync(final String filter) { if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Call call = service.list(this.client.tenantID(), filter, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = listDelegate(response); - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - listNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); + return service.list(this.client.tenantID(), filter, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); } - } - }); - return serviceCall; + }); } - private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return new AzureServiceResponseBuilder, CloudException>(this.client.mapperAdapter()) + private ServiceResponse> listDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder, GraphErrorException>(this.client.mapperAdapter()) .register(200, new TypeToken>() { }.getType()) - .registerError(CloudException.class) + .registerError(GraphErrorException.class) .build(response); } @@ -313,23 +380,13 @@ private ServiceResponse> listDelegate(Response get(String upnOrObjectId) throws CloudException, IOException, IllegalArgumentException { - if (upnOrObjectId == null) { - throw new IllegalArgumentException("Parameter upnOrObjectId is required and cannot be null."); - } - if (this.client.tenantID() == null) { - throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - Call call = service.get(upnOrObjectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - return getDelegate(call.execute()); + public UserInner get(String upnOrObjectId) throws GraphErrorException, IOException, IllegalArgumentException { + return getWithServiceResponseAsync(upnOrObjectId).toBlocking().single().getBody(); } /** @@ -337,44 +394,61 @@ public ServiceResponse get(String upnOrObjectId) throws CloudExceptio * * @param upnOrObjectId User object Id or user principal name to get user information. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall getAsync(String upnOrObjectId, final ServiceCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall getAsync(String upnOrObjectId, final ServiceCallback serviceCallback) { + return ServiceCall.create(getWithServiceResponseAsync(upnOrObjectId), serviceCallback); + } + + /** + * Gets user information from the directory. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/users-operations#GetAUser. + * + * @param upnOrObjectId User object Id or user principal name to get user information. + * @return the observable to the UserInner object + */ + public Observable getAsync(String upnOrObjectId) { + return getWithServiceResponseAsync(upnOrObjectId).map(new Func1, UserInner>() { + @Override + public UserInner call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Gets user information from the directory. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/users-operations#GetAUser. + * + * @param upnOrObjectId User object Id or user principal name to get user information. + * @return the observable to the UserInner object + */ + public Observable> getWithServiceResponseAsync(String upnOrObjectId) { if (upnOrObjectId == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter upnOrObjectId is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter upnOrObjectId is required and cannot be null."); } if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Call call = service.get(upnOrObjectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - serviceCallback.success(getDelegate(response)); - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); + return service.get(upnOrObjectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } } - } - }); - return serviceCall; + }); } - private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return new AzureServiceResponseBuilder(this.client.mapperAdapter()) + private ServiceResponse getDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder(this.client.mapperAdapter()) .register(200, new TypeToken() { }.getType()) - .registerError(CloudException.class) + .registerError(GraphErrorException.class) .build(response); } @@ -383,27 +457,12 @@ private ServiceResponse getDelegate(Response response) * * @param upnOrObjectId User object Id or user principal name to get user information. * @param parameters Parameters to update an exisitng user. - * @throws CloudException exception thrown from REST call + * @throws GraphErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the {@link ServiceResponse} object if successful. */ - public ServiceResponse update(String upnOrObjectId, UserUpdateParametersInner parameters) throws CloudException, IOException, IllegalArgumentException { - if (upnOrObjectId == null) { - throw new IllegalArgumentException("Parameter upnOrObjectId is required and cannot be null."); - } - if (this.client.tenantID() == null) { - throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); - } - if (parameters == null) { - throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - Validator.validate(parameters); - Call call = service.update(upnOrObjectId, this.client.tenantID(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - return updateDelegate(call.execute()); + public void update(String upnOrObjectId, UserUpdateParametersInner parameters) throws GraphErrorException, IOException, IllegalArgumentException { + updateWithServiceResponseAsync(upnOrObjectId, parameters).toBlocking().single().getBody(); } /** @@ -412,48 +471,67 @@ public ServiceResponse update(String upnOrObjectId, UserUpdateParametersIn * @param upnOrObjectId User object Id or user principal name to get user information. * @param parameters Parameters to update an exisitng user. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall updateAsync(String upnOrObjectId, UserUpdateParametersInner parameters, final ServiceCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall updateAsync(String upnOrObjectId, UserUpdateParametersInner parameters, final ServiceCallback serviceCallback) { + return ServiceCall.create(updateWithServiceResponseAsync(upnOrObjectId, parameters), serviceCallback); + } + + /** + * Updates an exisitng user. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/users-operations#UpdateUser. + * + * @param upnOrObjectId User object Id or user principal name to get user information. + * @param parameters Parameters to update an exisitng user. + * @return the {@link ServiceResponse} object if successful. + */ + public Observable updateAsync(String upnOrObjectId, UserUpdateParametersInner parameters) { + return updateWithServiceResponseAsync(upnOrObjectId, parameters).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Updates an exisitng user. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/users-operations#UpdateUser. + * + * @param upnOrObjectId User object Id or user principal name to get user information. + * @param parameters Parameters to update an exisitng user. + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> updateWithServiceResponseAsync(String upnOrObjectId, UserUpdateParametersInner parameters) { if (upnOrObjectId == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter upnOrObjectId is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter upnOrObjectId is required and cannot be null."); } if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (parameters == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter parameters is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Validator.validate(parameters, serviceCallback); - Call call = service.update(upnOrObjectId, this.client.tenantID(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - serviceCallback.success(updateDelegate(response)); - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); + Validator.validate(parameters); + return service.update(upnOrObjectId, this.client.tenantID(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = updateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } } - } - }); - return serviceCall; + }); } - private ServiceResponse updateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return new AzureServiceResponseBuilder(this.client.mapperAdapter()) + private ServiceResponse updateDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder(this.client.mapperAdapter()) .register(204, new TypeToken() { }.getType()) + .registerError(GraphErrorException.class) .build(response); } @@ -461,23 +539,12 @@ private ServiceResponse updateDelegate(Response response) th * Delete a user. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/users-operations#DeleteUser. * * @param upnOrObjectId user object id or user principal name (upn) - * @throws CloudException exception thrown from REST call + * @throws GraphErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the {@link ServiceResponse} object if successful. */ - public ServiceResponse delete(String upnOrObjectId) throws CloudException, IOException, IllegalArgumentException { - if (upnOrObjectId == null) { - throw new IllegalArgumentException("Parameter upnOrObjectId is required and cannot be null."); - } - if (this.client.tenantID() == null) { - throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - Call call = service.delete(upnOrObjectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - return deleteDelegate(call.execute()); + public void delete(String upnOrObjectId) throws GraphErrorException, IOException, IllegalArgumentException { + deleteWithServiceResponseAsync(upnOrObjectId).toBlocking().single().getBody(); } /** @@ -485,43 +552,61 @@ public ServiceResponse delete(String upnOrObjectId) throws CloudException, * * @param upnOrObjectId user object id or user principal name (upn) * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall deleteAsync(String upnOrObjectId, final ServiceCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall deleteAsync(String upnOrObjectId, final ServiceCallback serviceCallback) { + return ServiceCall.create(deleteWithServiceResponseAsync(upnOrObjectId), serviceCallback); + } + + /** + * Delete a user. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/users-operations#DeleteUser. + * + * @param upnOrObjectId user object id or user principal name (upn) + * @return the {@link ServiceResponse} object if successful. + */ + public Observable deleteAsync(String upnOrObjectId) { + return deleteWithServiceResponseAsync(upnOrObjectId).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Delete a user. Reference: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/users-operations#DeleteUser. + * + * @param upnOrObjectId user object id or user principal name (upn) + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> deleteWithServiceResponseAsync(String upnOrObjectId) { if (upnOrObjectId == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter upnOrObjectId is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter upnOrObjectId is required and cannot be null."); } if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Call call = service.delete(upnOrObjectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - serviceCallback.success(deleteDelegate(response)); - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); + return service.delete(upnOrObjectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = deleteDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } } - } - }); - return serviceCall; + }); } - private ServiceResponse deleteDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return new AzureServiceResponseBuilder(this.client.mapperAdapter()) + private ServiceResponse deleteDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder(this.client.mapperAdapter()) .register(204, new TypeToken() { }.getType()) + .registerError(GraphErrorException.class) .build(response); } @@ -530,27 +615,13 @@ private ServiceResponse deleteDelegate(Response response) th * * @param objectId User filtering parameters. * @param securityEnabledOnly If true only membership in security enabled groups should be checked. Otherwise membership in all groups should be checked - * @throws CloudException exception thrown from REST call + * @throws GraphErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<String> object wrapped in {@link ServiceResponse} if successful. + * @return the List<String> object if successful. */ - public ServiceResponse> getMemberGroups(String objectId, boolean securityEnabledOnly) throws CloudException, IOException, IllegalArgumentException { - if (objectId == null) { - throw new IllegalArgumentException("Parameter objectId is required and cannot be null."); - } - if (this.client.tenantID() == null) { - throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - UserGetMemberGroupsParameters parameters = new UserGetMemberGroupsParameters(); - parameters.withSecurityEnabledOnly(securityEnabledOnly); - Call call = service.getMemberGroups(objectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()); - ServiceResponse> response = getMemberGroupsDelegate(call.execute()); - List result = response.getBody().getItems(); - return new ServiceResponse<>(result, response.getResponse()); + public List getMemberGroups(String objectId, boolean securityEnabledOnly) throws GraphErrorException, IOException, IllegalArgumentException { + return getMemberGroupsWithServiceResponseAsync(objectId, securityEnabledOnly).toBlocking().single().getBody(); } /** @@ -559,47 +630,66 @@ public ServiceResponse> getMemberGroups(String objectId, boolean se * @param objectId User filtering parameters. * @param securityEnabledOnly If true only membership in security enabled groups should be checked. Otherwise membership in all groups should be checked * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall getMemberGroupsAsync(String objectId, boolean securityEnabledOnly, final ServiceCallback> serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall> getMemberGroupsAsync(String objectId, boolean securityEnabledOnly, final ServiceCallback> serviceCallback) { + return ServiceCall.create(getMemberGroupsWithServiceResponseAsync(objectId, securityEnabledOnly), serviceCallback); + } + + /** + * Gets a collection that contains the Object IDs of the groups of which the user is a member. + * + * @param objectId User filtering parameters. + * @param securityEnabledOnly If true only membership in security enabled groups should be checked. Otherwise membership in all groups should be checked + * @return the observable to the List<String> object + */ + public Observable> getMemberGroupsAsync(String objectId, boolean securityEnabledOnly) { + return getMemberGroupsWithServiceResponseAsync(objectId, securityEnabledOnly).map(new Func1>, List>() { + @Override + public List call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * Gets a collection that contains the Object IDs of the groups of which the user is a member. + * + * @param objectId User filtering parameters. + * @param securityEnabledOnly If true only membership in security enabled groups should be checked. Otherwise membership in all groups should be checked + * @return the observable to the List<String> object + */ + public Observable>> getMemberGroupsWithServiceResponseAsync(String objectId, boolean securityEnabledOnly) { if (objectId == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter objectId is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter objectId is required and cannot be null."); } if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } UserGetMemberGroupsParameters parameters = new UserGetMemberGroupsParameters(); parameters.withSecurityEnabledOnly(securityEnabledOnly); - Call call = service.getMemberGroups(objectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = getMemberGroupsDelegate(response); - serviceCallback.success(new ServiceResponse<>(result.getBody().getItems(), result.getResponse())); - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); + return service.getMemberGroups(objectId, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = getMemberGroupsDelegate(response); + ServiceResponse> clientResponse = new ServiceResponse>(result.getBody().getItems(), result.getResponse()); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } } - } - }); - return serviceCall; + }); } - private ServiceResponse> getMemberGroupsDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return new AzureServiceResponseBuilder, CloudException>(this.client.mapperAdapter()) + private ServiceResponse> getMemberGroupsDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder, GraphErrorException>(this.client.mapperAdapter()) .register(200, new TypeToken>() { }.getType()) - .registerError(CloudException.class) + .registerError(GraphErrorException.class) .build(response); } @@ -607,23 +697,19 @@ private ServiceResponse> getMemberGroupsDelegate(Response> listNext(final String nextLink) throws CloudException, IOException, IllegalArgumentException { - if (nextLink == null) { - throw new IllegalArgumentException("Parameter nextLink is required and cannot be null."); - } - if (this.client.tenantID() == null) { - throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - Call call = service.listNext(nextLink, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - return listNextDelegate(call.execute()); + public PagedList listNext(final String nextLink) throws GraphErrorException, IOException, IllegalArgumentException { + ServiceResponse> response = listNextSinglePageAsync(nextLink).toBlocking().single(); + return new PagedList(response.getBody()) { + @Override + public Page nextPage(String nextLink) throws RestException, IOException { + return listNextSinglePageAsync(nextLink).toBlocking().single().getBody(); + } + }; } /** @@ -632,51 +718,90 @@ public ServiceResponse> listNext(final String nextLink) thr * @param nextLink Next link for list operation. * @param serviceCall the ServiceCall object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall listNextAsync(final String nextLink, final ServiceCall serviceCall, final ListOperationCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall> listNextAsync(final String nextLink, final ServiceCall> serviceCall, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + listNextSinglePageAsync(nextLink), + new Func1>>>() { + @Override + public Observable>> call(String nextLink) { + return listNextSinglePageAsync(nextLink); + } + }, + serviceCallback); + } + + /** + * Gets list of users for the current tenant. + * + * @param nextLink Next link for list operation. + * @return the observable to the PagedList<UserInner> object + */ + public Observable> listNextAsync(final String nextLink) { + return listNextWithServiceResponseAsync(nextLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * Gets list of users for the current tenant. + * + * @param nextLink Next link for list operation. + * @return the observable to the PagedList<UserInner> object + */ + public Observable>> listNextWithServiceResponseAsync(final String nextLink) { + return listNextSinglePageAsync(nextLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextLink = page.getBody().getNextPageLink(); + if (nextLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextLink)); + } + }); + } + + /** + * Gets list of users for the current tenant. + * + ServiceResponse> * @param nextLink Next link for list operation. + * @return the PagedList<UserInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listNextSinglePageAsync(final String nextLink) { if (nextLink == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter nextLink is required and cannot be null."); } if (this.client.tenantID() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.tenantID() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Call call = service.listNext(nextLink, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - serviceCall.newCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = listNextDelegate(response); - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - listNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); + return service.listNext(nextLink, this.client.tenantID(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listNextDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); } - } - }); - return serviceCall; + }); } - private ServiceResponse> listNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { - return new AzureServiceResponseBuilder, CloudException>(this.client.mapperAdapter()) + private ServiceResponse> listNextDelegate(Response response) throws GraphErrorException, IOException, IllegalArgumentException { + return new AzureServiceResponseBuilder, GraphErrorException>(this.client.mapperAdapter()) .register(200, new TypeToken>() { }.getType()) - .registerError(CloudException.class) + .registerError(GraphErrorException.class) .build(response); } diff --git a/azure-mgmt-graph-rbac/src/main/test/com/microsoft/azure/management/graphrbac/GraphRbacManagementTestBase.java b/azure-mgmt-graph-rbac/src/main/test/java/com/microsoft/azure/management/graphrbac/GraphRbacManagementTestBase.java similarity index 50% rename from azure-mgmt-graph-rbac/src/main/test/com/microsoft/azure/management/graphrbac/GraphRbacManagementTestBase.java rename to azure-mgmt-graph-rbac/src/main/test/java/com/microsoft/azure/management/graphrbac/GraphRbacManagementTestBase.java index 88f0a8b9d6392..dcf676ac78300 100644 --- a/azure-mgmt-graph-rbac/src/main/test/com/microsoft/azure/management/graphrbac/GraphRbacManagementTestBase.java +++ b/azure-mgmt-graph-rbac/src/main/test/java/com/microsoft/azure/management/graphrbac/GraphRbacManagementTestBase.java @@ -6,7 +6,8 @@ package com.microsoft.azure.management.graphrbac; -import com.microsoft.azure.credentials.ApplicationTokenCredentials; +import com.microsoft.azure.AzureEnvironment; +import com.microsoft.azure.credentials.UserTokenCredentials; import com.microsoft.azure.management.graphrbac.implementation.GraphRbacManager; import okhttp3.logging.HttpLoggingInterceptor; @@ -17,16 +18,25 @@ public abstract class GraphRbacManagementTestBase { protected static GraphRbacManager graphRbacManager; protected static void createClients() { - ApplicationTokenCredentials credentials = new ApplicationTokenCredentials( - System.getenv("client-id"), +// ApplicationTokenCredentials credentials = new ApplicationTokenCredentials( +// System.getenv("client-id"), +// System.getenv("domain"), +// System.getenv("secret"), +// "https://graph.windows.net", +// null); + UserTokenCredentials credentials = new UserTokenCredentials( + "1950a258-227b-4e31-a9cf-717495945fc2", System.getenv("domain"), - System.getenv("secret"), + System.getenv("username"), + System.getenv("password"), "https://graph.windows.net", - null); + "https://graph.windows.net", + AzureEnvironment.AZURE + ); graphRbacManager = GraphRbacManager .configure() .withLogLevel(HttpLoggingInterceptor.Level.BODY) - .authenticate(credentials, credentials.getDomain()); + .authenticate(credentials, "myorganization"); } } diff --git a/azure-mgmt-graph-rbac/src/main/test/java/com/microsoft/azure/management/graphrbac/GroupsTests.java b/azure-mgmt-graph-rbac/src/main/test/java/com/microsoft/azure/management/graphrbac/GroupsTests.java new file mode 100644 index 0000000000000..37d0f0df6792b --- /dev/null +++ b/azure-mgmt-graph-rbac/src/main/test/java/com/microsoft/azure/management/graphrbac/GroupsTests.java @@ -0,0 +1,35 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + */ + +package com.microsoft.azure.management.graphrbac; + +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.List; + +public class GroupsTests extends GraphRbacManagementTestBase { + private static final String RG_NAME = "javacsmrg350"; + private static final String APP_NAME = "app-javacsm350"; + + @BeforeClass + public static void setup() throws Exception { + createClients(); + } + + @AfterClass + public static void cleanup() throws Exception { + } + + @Test + public void getServicePrincipal() throws Exception { + List servicePrincipals = graphRbacManager.servicePrincipals().list(); + Assert.assertNotNull(servicePrincipals); + } + +} diff --git a/azure-mgmt-graph-rbac/src/main/test/com/microsoft/azure/management/graphrbac/ServicePrincipalsTests.java b/azure-mgmt-graph-rbac/src/main/test/java/com/microsoft/azure/management/graphrbac/ServicePrincipalsTests.java similarity index 100% rename from azure-mgmt-graph-rbac/src/main/test/com/microsoft/azure/management/graphrbac/ServicePrincipalsTests.java rename to azure-mgmt-graph-rbac/src/main/test/java/com/microsoft/azure/management/graphrbac/ServicePrincipalsTests.java diff --git a/azure-mgmt-graph-rbac/src/main/test/java/com/microsoft/azure/management/graphrbac/UsersTests.java b/azure-mgmt-graph-rbac/src/main/test/java/com/microsoft/azure/management/graphrbac/UsersTests.java new file mode 100644 index 0000000000000..19eb9a0eb3f09 --- /dev/null +++ b/azure-mgmt-graph-rbac/src/main/test/java/com/microsoft/azure/management/graphrbac/UsersTests.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + */ + +package com.microsoft.azure.management.graphrbac; + +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.List; + +public class UsersTests extends GraphRbacManagementTestBase { + private static final String RG_NAME = "javacsmrg350"; + private static final String APP_NAME = "app-javacsm350"; + + @BeforeClass + public static void setup() throws Exception { + createClients(); + } + + @AfterClass + public static void cleanup() throws Exception { + } + + @Test + public void canCRUDUser() throws Exception { + //LIST + List userList = graphRbacManager.users().list(); + Assert.assertNotNull(userList); + User user = graphRbacManager.users().define("jeffrolfnlu@hotmail.com") + .withDisplayName("Test User 309") + .withPassword("Pa$$w0rd") + .withMailNickname("") + .create(); + } + +} diff --git a/azure-mgmt-keyvault/pom.xml b/azure-mgmt-keyvault/pom.xml index 0b99f6b535626..6b7471bc35ff9 100644 --- a/azure-mgmt-keyvault/pom.xml +++ b/azure-mgmt-keyvault/pom.xml @@ -58,12 +58,7 @@ com.microsoft.azure - azure-mgmt-storage - 1.0.0-SNAPSHOT - - - com.microsoft.azure - azure-mgmt-network + azure-mgmt-graph-rbac 1.0.0-SNAPSHOT diff --git a/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/AccessPolicy.java b/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/AccessPolicy.java new file mode 100644 index 0000000000000..7e09d5331f9f0 --- /dev/null +++ b/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/AccessPolicy.java @@ -0,0 +1,442 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + */ + +package com.microsoft.azure.management.keyvault; + +import com.microsoft.azure.management.graphrbac.ActiveDirectoryGroup; +import com.microsoft.azure.management.graphrbac.ServicePrincipal; +import com.microsoft.azure.management.graphrbac.User; +import com.microsoft.azure.management.resources.fluentcore.arm.models.ChildResource; +import com.microsoft.azure.management.resources.fluentcore.model.Attachable; +import com.microsoft.azure.management.resources.fluentcore.model.Settable; +import com.microsoft.azure.management.resources.fluentcore.model.Wrapper; + +import java.util.List; +import java.util.UUID; + +/** + * An immutable client-side representation of a key vault access policy. + */ +public interface AccessPolicy extends + ChildResource, + Wrapper { + /** + * @return The Azure Active Directory tenant ID that should be used for + * authenticating requests to the key vault. + */ + String tenantId(); + + /** + * @return The object ID of a user or service principal in the Azure Active + * Directory tenant for the vault. + */ + String objectId(); + + /** + * @return Application ID of the client making request on behalf of a principal. + */ + String applicationId(); + + /** + * @return Permissions the identity has for keys and secrets. + */ + Permissions permissions(); + + /************************************************************** + * Fluent interfaces to attach an access policy + **************************************************************/ + + /** + * The entirety of an access policy definition. + * @param the return type of the final {@link Attachable#attach()} + */ + interface Definition extends + DefinitionStages.Blank, + DefinitionStages.WithAttach { + } + + /** + * Grouping of access policy definition stages applicable as part of a key vault creation. + */ + interface DefinitionStages { + /** + * The first stage of an access policy definition. + * + * @param the return type of the final {@link WithAttach#attach()} + */ + interface Blank extends WithIdentity { + } + + /** + * The access policy definition stage allowing the Active Directory identity to be specified. + * @param the return type of the final {@link WithAttach#attach()} + */ + interface WithIdentity { + /** + * Specifies the object ID of the Active Directory identity this access policy is for. + * + * @param objectId the object ID of the AD identity + * @return the next stage of access policy definition + */ + WithAttach forObjectId(UUID objectId); + + /** + * Specifies the Active Directory user this access policy is for. + * + * @param user the AD user object + * @return the next stage of access policy definition + */ + WithAttach forUser(User user); + + /** + * Specifies the Active Directory user this access policy is for. + * + * @param userPrincipalName the user principal name of the AD user + * @return the next stage of access policy definition + */ + WithAttach forUser(String userPrincipalName); + + /** + * Specifies the Active Directory group this access policy is for. + * + * @param group the AD group object + * @return the next stage of access policy definition + */ + WithAttach forGroup(ActiveDirectoryGroup group); + + /** + * Specifies the Active Directory service principal this access policy is for. + * + * @param servicePrincipal the AD service principal object + * @return the next stage of access policy definition + */ + WithAttach forServicePrincipal(ServicePrincipal servicePrincipal); + + /** + * Specifies the Active Directory service principal this access policy is for. + * + * @param servicePrincipalName the service principal name of the AD user + * @return the next stage of access policy definition + */ + WithAttach forServicePrincipal(String servicePrincipalName); + } + + /** + * The access policy definition stage allowing permissions to be added. + * @param the return type of the final {@link WithAttach#attach()} + */ + interface WithPermissions { + /** + * Allow all permissions for the AD identity to access keys. + * + * @return the next stage of access policy definition + */ + WithAttach allowKeyAllPermissions(); + + /** + * Allow a list of permissions for the AD identity to access keys. + * + * @param permissions the list of permissions allowed + * @return the next stage of access policy definition + */ + WithAttach allowKeyPermissions(KeyPermissions... permissions); + + /** + * Allow a list of permissions for the AD identity to access keys. + * + * @param permissions the list of permissions allowed + * @return the next stage of access policy definition + */ + WithAttach allowKeyPermissions(List permissions); + + /** + * Allow all permissions for the AD identity to access secrets. + * + * @return the next stage of access policy definition + */ + WithAttach allowSecretAllPermissions(); + + /** + * Allow a list of permissions for the AD identity to access secrets. + * + * @param permissions the list of permissions allowed + * @return the next stage of access policy definition + */ + WithAttach allowSecretPermissions(SecretPermissions... permissions); + + /** + * Allow a list of permissions for the AD identity to access secrets. + * + * @param permissions the list of permissions allowed + * @return the next stage of access policy definition + */ + WithAttach allowSecretPermissions(List permissions); + } + + /** The final stage of the access policy definition. + *

+ * At this stage, more permissions can be added or application ID can be specified, + * or the access policy definition can be attached to the parent key vault definition + * using {@link WithAttach#attach()}. + * @param the return type of {@link WithAttach#attach()} + */ + interface WithAttach extends + Attachable.InUpdate, + WithPermissions { + } + } + + /** + * The entirety of an access policy definition as part of a key vault update. + * @param the return type of the final {@link UpdateDefinitionStages.WithAttach#attach()} + */ + interface UpdateDefinition extends + UpdateDefinitionStages.Blank, + UpdateDefinitionStages.WithAttach { + } + + /** + * Grouping of access policy definition stages applicable as part of a key vault update. + */ + interface UpdateDefinitionStages { + /** + * The first stage of an access policy definition. + * + * @param the return type of the final {@link WithAttach#attach()} + */ + interface Blank extends WithIdentity { + } + + /** + * The access policy definition stage allowing the Active Directory identity to be specified. + * @param the return type of the final {@link WithAttach#attach()} + */ + interface WithIdentity { + /** + * Specifies the object ID of the Active Directory identity this access policy is for. + * + * @param objectId the object ID of the AD identity + * @return the next stage of access policy definition + */ + WithAttach forObjectId(UUID objectId); + + /** + * Specifies the Active Directory user this access policy is for. + * + * @param user the AD user object + * @return the next stage of access policy definition + */ + WithAttach forUser(User user); + + /** + * Specifies the Active Directory user this access policy is for. + * + * @param userPrincipalName the user principal name of the AD user + * @return the next stage of access policy definition + */ + WithAttach forUser(String userPrincipalName); + + /** + * Specifies the Active Directory group this access policy is for. + * + * @param group the AD group object + * @return the next stage of access policy definition + */ + WithAttach forGroup(ActiveDirectoryGroup group); + + /** + * Specifies the Active Directory service principal this access policy is for. + * + * @param servicePrincipal the AD service principal object + * @return the next stage of access policy definition + */ + WithAttach forServicePrincipal(ServicePrincipal servicePrincipal); + + /** + * Specifies the Active Directory service principal this access policy is for. + * + * @param servicePrincipalName the service principal name of the AD user + * @return the next stage of access policy definition + */ + WithAttach forServicePrincipal(String servicePrincipalName); + } + + /** + * The access policy definition stage allowing permissions to be added. + * @param the return type of the final {@link WithAttach#attach()} + */ + interface WithPermissions { + /** + * Allow all permissions for the AD identity to access keys. + * + * @return the next stage of access policy definition + */ + WithAttach allowKeyAllPermissions(); + + /** + * Allow a list of permissions for the AD identity to access keys. + * + * @param permissions the list of permissions allowed + * @return the next stage of access policy definition + */ + WithAttach allowKeyPermissions(KeyPermissions... permissions); + + /** + * Allow a list of permissions for the AD identity to access keys. + * + * @param permissions the list of permissions allowed + * @return the next stage of access policy definition + */ + WithAttach allowKeyPermissions(List permissions); + + /** + * Allow all permissions for the AD identity to access secrets. + * + * @return the next stage of access policy definition + */ + WithAttach allowSecretAllPermissions(); + + /** + * Allow a list of permissions for the AD identity to access secrets. + * + * @param permissions the list of permissions allowed + * @return the next stage of access policy definition + */ + WithAttach allowSecretPermissions(SecretPermissions... permissions); + + /** + * Allow a list of permissions for the AD identity to access secrets. + * + * @param permissions the list of permissions allowed + * @return the next stage of access policy definition + */ + WithAttach allowSecretPermissions(List permissions); + } + + /** The final stage of the access policy definition. + *

+ * At this stage, more permissions can be added or application ID can be specified, + * or the access policy definition can be attached to the parent key vault update + * using {@link WithAttach#attach()}. + * @param the return type of {@link WithAttach#attach()} + */ + interface WithAttach extends + Attachable.InDefinition, + WithPermissions { + } + } + + /** + * Grouping of all the key vault update stages. + */ + interface UpdateStages { + /** + * The access policy update stage allowing permissions to be added or removed. + */ + interface WithPermissions { + /** + * Allow all permissions for the AD identity to access keys. + * + * @return the next stage of access policy update + */ + Update allowKeyAllPermissions(); + + /** + * Allow a list of permissions for the AD identity to access keys. + * + * @param permissions the list of permissions allowed + * @return the next stage of access policy update + */ + Update allowKeyPermissions(KeyPermissions... permissions); + + /** + * Allow a list of permissions for the AD identity to access keys. + * + * @param permissions the list of permissions allowed + * @return the next stage of access policy update + */ + Update allowKeyPermissions(List permissions); + + /** + * Revoke all permissions for the AD identity to access keys. + * + * @return the next stage of access policy update + */ + Update disallowKeyAllPermissions(); + + /** + * Revoke a list of permissions for the AD identity to access keys. + * + * @param permissions the list of permissions to revoke + * @return the next stage of access policy update + */ + Update disallowKeyPermissions(KeyPermissions... permissions); + + /** + * Revoke a list of permissions for the AD identity to access keys. + * + * @param permissions the list of permissions to revoke + * @return the next stage of access policy update + */ + Update disallowKeyPermissions(List permissions); + + /** + * Allow all permissions for the AD identity to access secrets. + * + * @return the next stage of access policy definition + */ + Update allowSecretAllPermissions(); + + /** + * Allow a list of permissions for the AD identity to access secrets. + * + * @param permissions the list of permissions allowed + * @return the next stage of access policy definition + */ + Update allowSecretPermissions(SecretPermissions... permissions); + + /** + * Allow a list of permissions for the AD identity to access secrets. + * + * @param permissions the list of permissions allowed + * @return the next stage of access policy definition + */ + Update allowSecretPermissions(List permissions); + + /** + * Revoke all permissions for the AD identity to access secrets. + * + * @return the next stage of access policy update + */ + Update disallowSecretAllPermissions(); + + /** + * Revoke a list of permissions for the AD identity to access secrets. + * + * @param permissions the list of permissions to revoke + * @return the next stage of access policy update + */ + Update disallowSecretPermissions(SecretPermissions... permissions); + + /** + * Revoke a list of permissions for the AD identity to access secrets. + * + * @param permissions the list of permissions to revoke + * @return the next stage of access policy update + */ + Update disallowSecretPermissions(List permissions); + } + } + + /** + * The entirety of an access policy update as part of a key vault update. + */ + interface Update extends + UpdateStages.WithPermissions, + Settable { + } +} + diff --git a/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/AccessPolicyEntry.java b/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/AccessPolicyEntry.java index 1bc9de5052af4..65c9e483215bc 100644 --- a/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/AccessPolicyEntry.java +++ b/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/AccessPolicyEntry.java @@ -9,6 +9,7 @@ package com.microsoft.azure.management.keyvault; import java.util.UUID; +import com.fasterxml.jackson.annotation.JsonProperty; /** * An array of 0 to 16 identities that have access to the key vault. All @@ -20,12 +21,15 @@ public class AccessPolicyEntry { * The Azure Active Directory tenant ID that should be used for * authenticating requests to the key vault. */ + @JsonProperty(required = true) private UUID tenantId; /** * The object ID of a user or service principal in the Azure Active - * Directory tenant for the vault. + * Directory tenant for the vault. The object ID must be unique for the + * list of access policies. */ + @JsonProperty(required = true) private UUID objectId; /** @@ -36,6 +40,7 @@ public class AccessPolicyEntry { /** * Permissions the identity has for keys and secrets. */ + @JsonProperty(required = true) private Permissions permissions; /** diff --git a/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/KeyPermissions.java b/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/KeyPermissions.java new file mode 100644 index 0000000000000..1e9996897691c --- /dev/null +++ b/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/KeyPermissions.java @@ -0,0 +1,98 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.keyvault; + +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Defines values for KeyPermissions. + */ +public final class KeyPermissions { + /** Static value all for KeyPermissions. */ + public static final KeyPermissions ALL = new KeyPermissions("all"); + + /** Static value encrypt for KeyPermissions. */ + public static final KeyPermissions ENCRYPT = new KeyPermissions("encrypt"); + + /** Static value decrypt for KeyPermissions. */ + public static final KeyPermissions DECRYPT = new KeyPermissions("decrypt"); + + /** Static value wrapkey for KeyPermissions. */ + public static final KeyPermissions WRAPKEY = new KeyPermissions("wrapkey"); + + /** Static value unwrapkey for KeyPermissions. */ + public static final KeyPermissions UNWRAPKEY = new KeyPermissions("unwrapkey"); + + /** Static value sign for KeyPermissions. */ + public static final KeyPermissions SIGN = new KeyPermissions("sign"); + + /** Static value verify for KeyPermissions. */ + public static final KeyPermissions VERIFY = new KeyPermissions("verify"); + + /** Static value get for KeyPermissions. */ + public static final KeyPermissions GET = new KeyPermissions("get"); + + /** Static value list for KeyPermissions. */ + public static final KeyPermissions LIST = new KeyPermissions("list"); + + /** Static value create for KeyPermissions. */ + public static final KeyPermissions CREATE = new KeyPermissions("create"); + + /** Static value update for KeyPermissions. */ + public static final KeyPermissions UPDATE = new KeyPermissions("update"); + + /** Static value import for KeyPermissions. */ + public static final KeyPermissions IMPORT = new KeyPermissions("import"); + + /** Static value delete for KeyPermissions. */ + public static final KeyPermissions DELETE = new KeyPermissions("delete"); + + /** Static value backup for KeyPermissions. */ + public static final KeyPermissions BACKUP = new KeyPermissions("backup"); + + /** Static value restore for KeyPermissions. */ + public static final KeyPermissions RESTORE = new KeyPermissions("restore"); + + private String value; + + /** + * Creates a custom value for KeyPermissions. + * @param value the custom value + */ + public KeyPermissions(String value) { + this.value = value; + } + + @JsonValue + @Override + public String toString() { + return value; + } + + @Override + public int hashCode() { + return value.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof KeyPermissions)) { + return false; + } + if (obj == this) { + return true; + } + KeyPermissions rhs = (KeyPermissions) obj; + if (value == null) { + return rhs.value == null; + } else { + return value.equals(rhs.value); + } + } +} diff --git a/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/Permissions.java b/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/Permissions.java index 1db622fd6ac45..b6ef1c6dadda1 100644 --- a/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/Permissions.java +++ b/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/Permissions.java @@ -17,19 +17,19 @@ public class Permissions { /** * Permissions to keys. */ - private List keys; + private List keys; /** * Permissions to secrets. */ - private List secrets; + private List secrets; /** * Get the keys value. * * @return the keys value */ - public List keys() { + public List keys() { return this.keys; } @@ -39,7 +39,7 @@ public List keys() { * @param keys the keys value to set * @return the Permissions object itself. */ - public Permissions withKeys(List keys) { + public Permissions withKeys(List keys) { this.keys = keys; return this; } @@ -49,7 +49,7 @@ public Permissions withKeys(List keys) { * * @return the secrets value */ - public List secrets() { + public List secrets() { return this.secrets; } @@ -59,7 +59,7 @@ public List secrets() { * @param secrets the secrets value to set * @return the Permissions object itself. */ - public Permissions withSecrets(List secrets) { + public Permissions withSecrets(List secrets) { this.secrets = secrets; return this; } diff --git a/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/SecretPermissions.java b/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/SecretPermissions.java new file mode 100644 index 0000000000000..4891a939903df --- /dev/null +++ b/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/SecretPermissions.java @@ -0,0 +1,68 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.keyvault; + +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Defines values for SecretPermissions. + */ +public final class SecretPermissions { + /** Static value all for SecretPermissions. */ + public static final SecretPermissions ALL = new SecretPermissions("all"); + + /** Static value get for SecretPermissions. */ + public static final SecretPermissions GET = new SecretPermissions("get"); + + /** Static value list for SecretPermissions. */ + public static final SecretPermissions LIST = new SecretPermissions("list"); + + /** Static value set for SecretPermissions. */ + public static final SecretPermissions SET = new SecretPermissions("set"); + + /** Static value delete for SecretPermissions. */ + public static final SecretPermissions DELETE = new SecretPermissions("delete"); + + private String value; + + /** + * Creates a custom value for SecretPermissions. + * @param value the custom value + */ + public SecretPermissions(String value) { + this.value = value; + } + + @JsonValue + @Override + public String toString() { + return value; + } + + @Override + public int hashCode() { + return value.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof SecretPermissions)) { + return false; + } + if (obj == this) { + return true; + } + SecretPermissions rhs = (SecretPermissions) obj; + if (value == null) { + return rhs.value == null; + } else { + return value.equals(rhs.value); + } + } +} diff --git a/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/Sku.java b/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/Sku.java index 7403d947e9c4a..79b8ab8b0e29f 100644 --- a/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/Sku.java +++ b/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/Sku.java @@ -15,8 +15,9 @@ */ public class Sku { /** - * SKU family name. Possible values include: 'A'. + * SKU family name. */ + @JsonProperty(required = true) private String family; /** @@ -26,6 +27,13 @@ public class Sku { @JsonProperty(required = true) private SkuName name; + /** + * Creates an instance of Sku class. + */ + public Sku() { + family = "A"; + } + /** * Get the family value. * diff --git a/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/SkuFamily.java b/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/SkuFamily.java deleted file mode 100644 index 3b170cc4be9df..0000000000000 --- a/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/SkuFamily.java +++ /dev/null @@ -1,20 +0,0 @@ -/** - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. - * - * Code generated by Microsoft (R) AutoRest Code Generator. - */ - -package com.microsoft.azure.management.keyvault; - -/** - * Defines values for SkuFamily. - */ -public final class SkuFamily { - /** Static value A for SkuFamily. */ - public static final String A = "A"; - - private SkuFamily() { - } -} diff --git a/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/Vault.java b/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/Vault.java new file mode 100644 index 0000000000000..eafee197a2603 --- /dev/null +++ b/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/Vault.java @@ -0,0 +1,296 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + */ + +package com.microsoft.azure.management.keyvault; + +import com.microsoft.azure.management.keyvault.implementation.VaultInner; +import com.microsoft.azure.management.resources.fluentcore.arm.models.GroupableResource; +import com.microsoft.azure.management.resources.fluentcore.model.Appliable; +import com.microsoft.azure.management.resources.fluentcore.model.Creatable; +import com.microsoft.azure.management.resources.fluentcore.model.Refreshable; +import com.microsoft.azure.management.resources.fluentcore.model.Updatable; +import com.microsoft.azure.management.resources.fluentcore.model.Wrapper; + +import java.util.List; + +/** + * An immutable client-side representation of an Azure Key Vault. + */ +public interface Vault extends + GroupableResource, + Refreshable, + Updatable, + Wrapper { + /** + * @return the URI of the vault for performing operations on keys and secrets. + */ + String vaultUri(); + + /** + * @return the Azure Active Directory tenant ID that should be used for + * authenticating requests to the key vault. + */ + String tenantId(); + + /** + * @return SKU details. + */ + Sku sku(); + + /** + * @return an array of 0 to 16 identities that have access to the key vault. All + * identities in the array must use the same tenant ID as the key vault's + * tenant ID. + */ + List accessPolicies(); + + /** + * @return whether Azure Virtual Machines are permitted to + * retrieve certificates stored as secrets from the key vault. + */ + boolean enabledForDeployment(); + + /** + * @return whether Azure Disk Encryption is permitted to + * retrieve secrets from the vault and unwrap keys. + */ + boolean enabledForDiskEncryption(); + + /** + * @return whether Azure Resource Manager is permitted to + * retrieve secrets from the key vault. + */ + boolean enabledForTemplateDeployment(); + + /************************************************************** + * Fluent interfaces to provision a Vault + **************************************************************/ + + /** + * Container interface for all the definitions that need to be implemented. + */ + interface Definition extends + DefinitionStages.Blank, + DefinitionStages.WithGroup, + DefinitionStages.WithAccessPolicy, + DefinitionStages.WithCreate { + } + + /** + * Grouping of all the key vault definition stages. + */ + interface DefinitionStages { + /** + * The first stage of the key vault definition. + */ + interface Blank extends DefinitionWithRegion { + } + + /** + * A key vault definition allowing resource group to be set. + */ + interface WithGroup extends GroupableResource.DefinitionStages.WithGroup { + } + + /** + * A key vault definition allowing the sku to be set. + */ + interface WithSku { + /** + * Specifies the sku of the key vault. + * + * @param skuName the sku + * @return the next stage of key vault definition + */ + WithCreate withSku(SkuName skuName); + } + + /** + * A key vault definition allowing access policies to be attached. + */ + interface WithAccessPolicy { + /** + * Attach no access policy. + * + * @return the next stage of key vault definition + */ + WithCreate withEmptyAccessPolicy(); + + /** + * Attach an existing access policy. + * + * @param accessPolicy the existing access policy + * @return the next stage of key vault definition + */ + WithCreate withAccessPolicy(AccessPolicy accessPolicy); + + /** + * Begins the definition of a new access policy to be added to this key vault. + * + * @return the first stage of the access policy definition + */ + AccessPolicy.DefinitionStages.Blank defineAccessPolicy(); + } + + /** + * A key vault definition allowing various configurations to be set. + */ + interface WithConfigurations { + /** + * Enable Azure Virtual Machines to retrieve certificates stored as secrets from the key vault. + * + * @return the next stage of key vault definition + */ + WithCreate withDeploymentEnabled(); + + /** + * Enable Azure Disk Encryption to retrieve secrets from the vault and unwrap keys. + * + * @return the next stage of key vault definition + */ + WithCreate withDiskEncryptionEnabled(); + + /** + * Enable Azure Resource Manager to retrieve secrets from the key vault. + * + * @return the next stage of key vault definition + */ + WithCreate withTemplateDeploymentEnabled(); + + /** + * Disable Azure Virtual Machines to retrieve certificates stored as secrets from the key vault. + * + * @return the next stage of key vault definition + */ + WithCreate withDeploymentDisabled(); + + /** + * Disable Azure Disk Encryption to retrieve secrets from the vault and unwrap keys. + * + * @return the next stage of key vault definition + */ + WithCreate withDiskEncryptionDisabled(); + + /** + * Disable Azure Resource Manager to retrieve secrets from the key vault. + * + * @return the next stage of key vault definition + */ + WithCreate withTemplateDeploymentDisabled(); + } + + /** + * A key vault definition with sufficient inputs to create a new + * storage account in the cloud, but exposing additional optional inputs to + * specify. + */ + interface WithCreate extends + Creatable, + GroupableResource.DefinitionWithTags, + DefinitionStages.WithSku, + DefinitionStages.WithConfigurations, + DefinitionStages.WithAccessPolicy { + } + } + + /** + * Grouping of all the key vault update stages. + */ + interface UpdateStages { + /** + * A key vault update allowing access policies to be modified, attached, or removed. + */ + interface WithAccessPolicy { + /** + * Remove an access policy from the access policy list. + * + * @param objectId the object ID of the Active Directory identity the access policy is for + * @return the key vault update stage + */ + Update withoutAccessPolicy(String objectId); + + /** + * Attach an existing access policy. + * + * @param accessPolicy the existing access policy + * @return the key vault update stage + */ + Update withAccessPolicy(AccessPolicy accessPolicy); + + /** + * Begins the definition of a new access policy to be added to this key vault. + * + * @return the first stage of the access policy definition + */ + AccessPolicy.UpdateDefinitionStages.Blank defineAccessPolicy(); + + /** + * Begins the update of an existing access policy attached to this key vault. + * + * @param objectId the object ID of the Active Directory identity the access policy is for + * @return the update stage of the access policy definition + */ + AccessPolicy.Update updateAccessPolicy(String objectId); + } + + /** + * A key vault update allowing various configurations to be set. + */ + interface WithConfigurations { + /** + * Enable Azure Virtual Machines to retrieve certificates stored as secrets from the key vault. + * + * @return the key vault update stage + */ + Update withDeploymentEnabled(); + + /** + * Enable Azure Disk Encryption to retrieve secrets from the vault and unwrap keys. + * + * @return the key vault update stage + */ + Update withDiskEncryptionEnabled(); + + /** + * Enable Azure Resource Manager to retrieve secrets from the key vault. + * + * @return the key vault update stage + */ + Update withTemplateDeploymentEnabled(); + + /** + * Disable Azure Virtual Machines to retrieve certificates stored as secrets from the key vault. + * + * @return the key vault update stage + */ + Update withDeploymentDisabled(); + + /** + * Disable Azure Disk Encryption to retrieve secrets from the vault and unwrap keys. + * + * @return the next stage of key vault definition + */ + Update withDiskEncryptionDisabled(); + + /** + * Disable Azure Resource Manager to retrieve secrets from the key vault. + * + * @return the key vault update stage + */ + Update withTemplateDeploymentDisabled(); + } + } + + /** + * The template for a key vault update operation, containing all the settings that can be modified. + */ + interface Update extends + Appliable, + UpdateStages.WithAccessPolicy, + UpdateStages.WithConfigurations { + } +} + diff --git a/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/Vaults.java b/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/Vaults.java new file mode 100644 index 0000000000000..adb45ae990864 --- /dev/null +++ b/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/Vaults.java @@ -0,0 +1,28 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + */ + +package com.microsoft.azure.management.keyvault; + +import com.microsoft.azure.management.resources.fluentcore.arm.collection.SupportsDeletingByGroup; +import com.microsoft.azure.management.resources.fluentcore.arm.collection.SupportsGettingByGroup; +import com.microsoft.azure.management.resources.fluentcore.arm.collection.SupportsGettingById; +import com.microsoft.azure.management.resources.fluentcore.arm.collection.SupportsListingByGroup; +import com.microsoft.azure.management.resources.fluentcore.collection.SupportsCreating; +import com.microsoft.azure.management.resources.fluentcore.collection.SupportsDeleting; +import com.microsoft.azure.management.resources.fluentcore.collection.SupportsListing; + +/** + * Entry point for key vaults management API. + */ +public interface Vaults extends + SupportsListing, + SupportsCreating, + SupportsDeleting, + SupportsListingByGroup, + SupportsGettingByGroup, + SupportsGettingById, + SupportsDeletingByGroup { +} diff --git a/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/implementation/AccessPolicyImpl.java b/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/implementation/AccessPolicyImpl.java new file mode 100644 index 0000000000000..62a6397fe7f9b --- /dev/null +++ b/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/implementation/AccessPolicyImpl.java @@ -0,0 +1,226 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + */ + +package com.microsoft.azure.management.keyvault.implementation; + +import com.microsoft.azure.management.graphrbac.ActiveDirectoryGroup; +import com.microsoft.azure.management.graphrbac.ServicePrincipal; +import com.microsoft.azure.management.graphrbac.User; +import com.microsoft.azure.management.keyvault.AccessPolicy; +import com.microsoft.azure.management.keyvault.AccessPolicyEntry; +import com.microsoft.azure.management.keyvault.KeyPermissions; +import com.microsoft.azure.management.keyvault.Permissions; +import com.microsoft.azure.management.keyvault.SecretPermissions; +import com.microsoft.azure.management.keyvault.Vault; +import com.microsoft.azure.management.resources.fluentcore.arm.models.implementation.ChildResourceImpl; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; + +/** + * Implementation for AccessPolicy and its parent interfaces. + */ +class AccessPolicyImpl + extends ChildResourceImpl< + AccessPolicyEntry, + VaultImpl> + implements + AccessPolicy, + AccessPolicy.Definition, + AccessPolicy.UpdateDefinition, + AccessPolicy.Update { + private String userPrincipalName; + private String servicePrincipalName; + + AccessPolicyImpl(AccessPolicyEntry innerObject, VaultImpl parent) { + super(innerObject, parent); + inner().withTenantId(UUID.fromString(parent.tenantId())); + } + + String userPrincipalName() { + return userPrincipalName; + } + + String servicePrincipalName() { + return servicePrincipalName; + } + + @Override + public String tenantId() { + if (inner().tenantId() == null) { + return null; + } + return inner().tenantId().toString(); + } + + @Override + public String objectId() { + if (inner().objectId() == null) { + return null; + } + return inner().objectId().toString(); + } + + @Override + public String applicationId() { + if (inner().applicationId() == null) { + return null; + } + return inner().applicationId().toString(); + } + + @Override + public Permissions permissions() { + return inner().permissions(); + } + + @Override + public String name() { + return inner().objectId().toString(); + } + + private void initializeKeyPermissions() { + if (inner().permissions() == null) { + inner().withPermissions(new Permissions()); + } + if (inner().permissions().keys() == null) { + inner().permissions().withKeys(new ArrayList()); + } + } + + private void initializeSecretPermissions() { + if (inner().permissions() == null) { + inner().withPermissions(new Permissions()); + } + if (inner().permissions().secrets() == null) { + inner().permissions().withSecrets(new ArrayList()); + } + } + + @Override + public AccessPolicyImpl allowKeyPermissions(KeyPermissions... permissions) { + initializeKeyPermissions(); + inner().permissions().keys().addAll(Arrays.asList(permissions)); + return this; + } + + @Override + public AccessPolicyImpl allowKeyPermissions(List permissions) { + initializeKeyPermissions(); + inner().permissions().keys().addAll(permissions); + return this; + } + + @Override + public AccessPolicyImpl allowSecretPermissions(SecretPermissions... permissions) { + initializeSecretPermissions(); + inner().permissions().secrets().addAll(Arrays.asList(permissions)); + return this; + } + + @Override + public AccessPolicyImpl allowSecretPermissions(List permissions) { + initializeSecretPermissions(); + inner().permissions().secrets().addAll(permissions); + return this; + } + + @Override + public VaultImpl attach() { + parent().withAccessPolicy(this); + return parent(); + } + + @Override + public AccessPolicyImpl forObjectId(UUID objectId) { + inner().withObjectId(objectId); + return this; + } + + @Override + public AccessPolicyImpl forUser(User user) { + inner().withObjectId(UUID.fromString(user.objectId())); + return this; + } + + @Override + public AccessPolicyImpl forUser(String userPrincipalName) { + this.userPrincipalName = userPrincipalName; + return this; + } + + @Override + public AccessPolicyImpl forGroup(ActiveDirectoryGroup group) { + inner().withObjectId(UUID.fromString(group.objectId())); + return this; + } + + @Override + public AccessPolicyImpl forServicePrincipal(ServicePrincipal servicePrincipal) { + inner().withObjectId(UUID.fromString(servicePrincipal.objectId())); + return this; + } + + @Override + public AccessPolicyImpl forServicePrincipal(String servicePrincipalName) { + this.servicePrincipalName = servicePrincipalName; + return this; + } + + @Override + public AccessPolicyImpl allowKeyAllPermissions() { + return allowKeyPermissions(KeyPermissions.ALL); + } + + @Override + public AccessPolicyImpl disallowKeyAllPermissions() { + initializeKeyPermissions(); + inner().permissions().keys().clear(); + return this; + } + + @Override + public AccessPolicyImpl disallowKeyPermissions(KeyPermissions... permissions) { + initializeSecretPermissions(); + inner().permissions().keys().removeAll(Arrays.asList(permissions)); + return this; + } + + @Override + public AccessPolicyImpl disallowKeyPermissions(List permissions) { + initializeSecretPermissions(); + inner().permissions().keys().removeAll(permissions); + return this; + } + + @Override + public AccessPolicyImpl allowSecretAllPermissions() { + return allowSecretPermissions(SecretPermissions.ALL); + } + + @Override + public AccessPolicyImpl disallowSecretAllPermissions() { + initializeSecretPermissions(); + inner().permissions().secrets().clear(); + return this; + } + + @Override + public AccessPolicyImpl disallowSecretPermissions(SecretPermissions... permissions) { + initializeSecretPermissions(); + inner().permissions().secrets().removeAll(Arrays.asList(permissions)); + return this; + } + + @Override + public AccessPolicyImpl disallowSecretPermissions(List permissions) { + initializeSecretPermissions(); + inner().permissions().secrets().removeAll(permissions); + return this; + } +} diff --git a/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/implementation/KeyVaultManager.java b/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/implementation/KeyVaultManager.java new file mode 100644 index 0000000000000..d482876a88e36 --- /dev/null +++ b/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/implementation/KeyVaultManager.java @@ -0,0 +1,115 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + */ + +package com.microsoft.azure.management.keyvault.implementation; + +import com.microsoft.azure.AzureEnvironment; +import com.microsoft.azure.RequestIdHeaderInterceptor; +import com.microsoft.azure.RestClient; +import com.microsoft.azure.management.graphrbac.implementation.GraphRbacManager; +import com.microsoft.azure.management.keyvault.Vaults; +import com.microsoft.azure.management.resources.fluentcore.arm.AzureConfigurable; +import com.microsoft.azure.management.resources.fluentcore.arm.implementation.AzureConfigurableImpl; +import com.microsoft.azure.management.resources.fluentcore.arm.implementation.Manager; +import com.microsoft.rest.credentials.ServiceClientCredentials; + +/** + * Entry point to Azure storage resource management. + */ +public final class KeyVaultManager extends Manager { + // Service managers + private GraphRbacManager graphRbacManager; + // Collections + private Vaults vaults; + // Variables + private final String tenantId; + + /** + * Get a Configurable instance that can be used to create StorageManager with optional configuration. + * + * @return the instance allowing configurations + */ + public static Configurable configure() { + return new KeyVaultManager.ConfigurableImpl(); + } + + /** + * Creates an instance of StorageManager that exposes storage resource management API entry points. + * + * @param credentials the credentials to use + * @param tenantId the tenant UUID + * @param subscriptionId the subscription UUID + * @return the StorageManager + */ + public static KeyVaultManager authenticate(ServiceClientCredentials credentials, String tenantId, String subscriptionId) { + return new KeyVaultManager(AzureEnvironment.AZURE.newRestClientBuilder() + .withCredentials(credentials) + .build(), tenantId, subscriptionId); + } + + /** + * Creates an instance of StorageManager that exposes storage resource management API entry points. + * + * @param restClient the RestClient to be used for API calls + * @param tenantId the tenant UUID + * @param subscriptionId the subscription UUID + * @return the StorageManager + */ + public static KeyVaultManager authenticate(RestClient restClient, String tenantId, String subscriptionId) { + return new KeyVaultManager(restClient, tenantId, subscriptionId); + } + + /** + * The interface allowing configurations to be set. + */ + public interface Configurable extends AzureConfigurable { + /** + * Creates an instance of StorageManager that exposes storage management API entry points. + * + * @param credentials the credentials to use + * @param tenantId the tenant UUID + * @param subscriptionId the subscription UUID + * @return the interface exposing storage management API entry points that work across subscriptions + */ + KeyVaultManager authenticate(ServiceClientCredentials credentials, String tenantId, String subscriptionId); + } + + /** + * The implementation for Configurable interface. + */ + private static final class ConfigurableImpl extends AzureConfigurableImpl implements Configurable { + public KeyVaultManager authenticate(ServiceClientCredentials credentials, String tenantId, String subscriptionId) { + return KeyVaultManager.authenticate(buildRestClient(credentials), tenantId, subscriptionId); + } + } + + private KeyVaultManager(RestClient restClient, String tenantId, String subscriptionId) { + super( + restClient, + subscriptionId, + new KeyVaultManagementClientImpl(restClient).withSubscriptionId(subscriptionId)); + graphRbacManager = GraphRbacManager.authenticate(new RestClient.Builder() + .withBaseUrl("https://graph.windows.net") + .withInterceptor(new RequestIdHeaderInterceptor()) + .withCredentials(restClient.credentials()) + .build(), tenantId); + this.tenantId = tenantId; + } + + /** + * @return the storage account management API entry point + */ + public Vaults vaults() { + if (vaults == null) { + vaults = new VaultsImpl( + super.innerManagementClient.vaults(), + this, + graphRbacManager, + tenantId); + } + return vaults; + } +} diff --git a/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/implementation/VaultImpl.java b/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/implementation/VaultImpl.java new file mode 100644 index 0000000000000..bfb4d8b762837 --- /dev/null +++ b/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/implementation/VaultImpl.java @@ -0,0 +1,269 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + */ + +package com.microsoft.azure.management.keyvault.implementation; + +import com.microsoft.azure.management.graphrbac.ServicePrincipal; +import com.microsoft.azure.management.graphrbac.User; +import com.microsoft.azure.management.graphrbac.implementation.GraphRbacManager; +import com.microsoft.azure.management.keyvault.AccessPolicy; +import com.microsoft.azure.management.keyvault.AccessPolicyEntry; +import com.microsoft.azure.management.keyvault.Sku; +import com.microsoft.azure.management.keyvault.SkuName; +import com.microsoft.azure.management.keyvault.Vault; +import com.microsoft.azure.management.keyvault.VaultProperties; +import com.microsoft.azure.management.resources.fluentcore.arm.models.implementation.GroupableResourceImpl; +import rx.Observable; +import rx.functions.Action1; +import rx.functions.Func1; +import rx.functions.FuncN; +import rx.schedulers.Schedulers; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.UUID; + +/** + * Implementation for Vault and its parent interfaces. + */ +class VaultImpl + extends GroupableResourceImpl< + Vault, + VaultInner, + VaultImpl, + KeyVaultManager> + implements + Vault, + Vault.Definition, + Vault.Update { + private VaultsInner client; + private GraphRbacManager graphRbacManager; + private List accessPolicies; + + VaultImpl(String key, VaultInner innerObject, VaultsInner client, KeyVaultManager manager, GraphRbacManager graphRbacManager) { + super(key, innerObject, manager); + this.client = client; + this.graphRbacManager = graphRbacManager; + this.accessPolicies = new ArrayList<>(); + if (innerObject != null && innerObject.properties() != null && innerObject.properties().accessPolicies() != null) { + for (AccessPolicyEntry entry : innerObject.properties().accessPolicies()) { + this.accessPolicies.add(new AccessPolicyImpl(entry, this)); + } + } + } + + @Override + public String vaultUri() { + if (inner().properties() == null) { + return null; + } + return inner().properties().vaultUri(); + } + + @Override + public String tenantId() { + if (inner().properties() == null) { + return null; + } + if (inner().properties().tenantId() == null) { + return null; + } + return inner().properties().tenantId().toString(); + } + + @Override + public Sku sku() { + if (inner().properties() == null) { + return null; + } + return inner().properties().sku(); + } + + @Override + public List accessPolicies() { + AccessPolicy[] array = new AccessPolicy[accessPolicies.size()]; + return Arrays.asList(accessPolicies.toArray(array)); + } + + @Override + public boolean enabledForDeployment() { + if (inner().properties() == null || inner().properties().enabledForDeployment() == null) { + return false; + } + return inner().properties().enabledForDeployment(); + } + + @Override + public boolean enabledForDiskEncryption() { + if (inner().properties() == null || inner().properties().enabledForDiskEncryption() == null) { + return false; + } + return inner().properties().enabledForDiskEncryption(); + } + + @Override + public boolean enabledForTemplateDeployment() { + if (inner().properties() == null || inner().properties().enabledForTemplateDeployment()) { + return false; + } + return inner().properties().enabledForTemplateDeployment(); + } + + @Override + public VaultImpl withEmptyAccessPolicy() { + this.accessPolicies = new ArrayList<>(); + return this; + } + + @Override + public VaultImpl withoutAccessPolicy(String objectId) { + for (AccessPolicyImpl entry : this.accessPolicies) { + if (entry.objectId().equals(objectId)) { + accessPolicies.remove(entry); + break; + } + } + return this; + } + + @Override + public VaultImpl withAccessPolicy(AccessPolicy accessPolicy) { + accessPolicies.add((AccessPolicyImpl) accessPolicy); + return this; + } + + @Override + public AccessPolicyImpl defineAccessPolicy() { + return new AccessPolicyImpl(new AccessPolicyEntry(), this); + } + + @Override + public AccessPolicyImpl updateAccessPolicy(String objectId) { + for (AccessPolicyImpl entry : this.accessPolicies) { + if (entry.objectId().equals(objectId)) { + return entry; + } + } + throw new NoSuchElementException(String.format("Identity %s not found in the access policies.", objectId)); + } + + @Override + public VaultImpl withDeploymentEnabled() { + inner().properties().withEnabledForDeployment(true); + return this; + } + + @Override + public VaultImpl withDiskEncryptionEnabled() { + inner().properties().withEnabledForDiskEncryption(true); + return this; + } + + @Override + public VaultImpl withTemplateDeploymentEnabled() { + inner().properties().withEnabledForTemplateDeployment(true); + return this; + } + + @Override + public VaultImpl withDeploymentDisabled() { + inner().properties().withEnabledForDeployment(false); + return this; + } + + @Override + public VaultImpl withDiskEncryptionDisabled() { + inner().properties().withEnabledForDiskEncryption(false); + return this; + } + + @Override + public VaultImpl withTemplateDeploymentDisabled() { + inner().properties().withEnabledForTemplateDeployment(false); + return this; + } + + @Override + public VaultImpl withSku(SkuName skuName) { + if (inner().properties() == null) { + inner().withProperties(new VaultProperties()); + } + inner().properties().withSku(new Sku().withName(skuName)); + return this; + } + + private Observable> populateAccessPolicies() { + List>observables = new ArrayList<>(); + for (final AccessPolicyImpl accessPolicy : accessPolicies) { + if (accessPolicy.objectId() == null) { + if (accessPolicy.userPrincipalName() != null) { + observables.add(graphRbacManager.users().getByUserPrincipalNameAsync(accessPolicy.userPrincipalName()) + .subscribeOn(Schedulers.io()) + .doOnNext(new Action1() { + @Override + public void call(User user) { + accessPolicy.forObjectId(UUID.fromString(user.objectId())); + } + })); + } else if (accessPolicy.servicePrincipalName() != null) { + observables.add(graphRbacManager.servicePrincipals().getByServicePrincipalNameAsync(accessPolicy.servicePrincipalName()) + .subscribeOn(Schedulers.io()) + .doOnNext(new Action1() { + @Override + public void call(ServicePrincipal sp) { + accessPolicy.forObjectId(UUID.fromString(sp.objectId())); + } + })); + } else { + throw new IllegalArgumentException("Access policy must specify object ID."); + } + } + } + if (observables.isEmpty()) { + return Observable.just(accessPolicies()); + } else { + return Observable.zip(observables, new FuncN>() { + @Override + public List call(Object... args) { + return accessPolicies(); + } + }); + } + } + + @Override + public Observable createResourceAsync() { + return populateAccessPolicies() + .flatMap(new Func1>() { + @Override + public Observable call(Object o) { + VaultCreateOrUpdateParametersInner parameters = new VaultCreateOrUpdateParametersInner(); + parameters.withLocation(regionName()); + parameters.withProperties(inner().properties()); + parameters.withTags(inner().getTags()); + parameters.properties().withAccessPolicies(new ArrayList()); + for (AccessPolicy accessPolicy : accessPolicies) { + parameters.properties().accessPolicies().add(accessPolicy.inner()); + } + return client.createOrUpdateAsync(resourceGroupName(), name(), parameters); + } + }) + .map(innerToFluentMap(this)); + } + + @Override + public VaultImpl refresh() throws Exception { + setInner(client.get(resourceGroupName(), name())); + return this; + } + + @Override + public Observable applyAsync() { + return createAsync(); + } +} diff --git a/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/implementation/VaultInner.java b/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/implementation/VaultInner.java index 7f85bfedae227..89d9902415de9 100644 --- a/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/implementation/VaultInner.java +++ b/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/implementation/VaultInner.java @@ -11,7 +11,6 @@ import com.microsoft.azure.management.keyvault.VaultProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.microsoft.azure.Resource; -import com.microsoft.azure.Resource; /** * Resource information with extended details. diff --git a/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/implementation/VaultsImpl.java b/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/implementation/VaultsImpl.java new file mode 100644 index 0000000000000..be66f6aa2336e --- /dev/null +++ b/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/implementation/VaultsImpl.java @@ -0,0 +1,100 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + */ + +package com.microsoft.azure.management.keyvault.implementation; + +import com.microsoft.azure.CloudException; +import com.microsoft.azure.PagedList; +import com.microsoft.azure.management.graphrbac.implementation.GraphRbacManager; +import com.microsoft.azure.management.keyvault.SkuName; +import com.microsoft.azure.management.keyvault.Vault; +import com.microsoft.azure.management.keyvault.VaultProperties; +import com.microsoft.azure.management.keyvault.Vaults; +import com.microsoft.azure.management.resources.fluentcore.arm.ResourceUtils; +import com.microsoft.azure.management.resources.fluentcore.arm.collection.implementation.GroupableResourcesImpl; +import com.microsoft.rest.RestException; + +import java.io.IOException; +import java.util.UUID; + +/** + * The implementation of Vaults and its parent interfaces. + */ +class VaultsImpl + extends GroupableResourcesImpl< + Vault, + VaultImpl, + VaultInner, + VaultsInner, + KeyVaultManager> + implements Vaults { + private final GraphRbacManager graphRbacManager; + private final String tenantId; + + VaultsImpl( + final VaultsInner client, + final KeyVaultManager keyVaultManager, + final GraphRbacManager graphRbacManager, + final String tenantId) { + super(client, keyVaultManager); + this.graphRbacManager = graphRbacManager; + this.tenantId = tenantId; + } + + @Override + public PagedList list() throws RestException, IOException { + return wrapList(this.innerCollection.list()); + } + + @Override + public PagedList listByGroup(String groupName) throws CloudException, IOException { + return wrapList(this.innerCollection.listByResourceGroup(groupName)); + } + + @Override + public Vault getByGroup(String groupName, String name) throws CloudException, IOException { + return wrapModel(this.innerCollection.get(groupName, name)); + } + + @Override + public void delete(String id) throws Exception { + delete(ResourceUtils.groupFromResourceId(id), ResourceUtils.nameFromResourceId(id)); + } + + @Override + public void delete(String groupName, String name) throws Exception { + this.innerCollection.delete(groupName, name); + } + + @Override + public VaultImpl define(String name) { + return wrapModel(name) + .withSku(SkuName.STANDARD) + .withEmptyAccessPolicy(); + } + + @Override + protected VaultImpl wrapModel(String name) { + VaultInner inner = new VaultInner().withProperties(new VaultProperties()); + inner.properties().withTenantId(UUID.fromString(tenantId)); + return new VaultImpl( + name, + inner, + this.innerCollection, + super.myManager, + graphRbacManager); + } + + @Override + protected VaultImpl wrapModel(VaultInner vaultInner) { + return new VaultImpl( + vaultInner.name(), + vaultInner, + this.innerCollection, + super.myManager, + graphRbacManager); + } +} diff --git a/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/implementation/VaultsInner.java b/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/implementation/VaultsInner.java index 68d2d771e5ee5..33bc29b7c4892 100644 --- a/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/implementation/VaultsInner.java +++ b/azure-mgmt-keyvault/src/main/java/com/microsoft/azure/management/keyvault/implementation/VaultsInner.java @@ -8,32 +8,35 @@ package com.microsoft.azure.management.keyvault.implementation; -import retrofit2.Retrofit; import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceCall; import com.microsoft.azure.AzureServiceResponseBuilder; import com.microsoft.azure.CloudException; import com.microsoft.azure.ListOperationCallback; import com.microsoft.azure.Page; import com.microsoft.azure.PagedList; +import com.microsoft.rest.RestException; import com.microsoft.rest.ServiceCall; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceResponse; -import com.microsoft.rest.ServiceResponseCallback; import com.microsoft.rest.Validator; -import java.io.IOException; -import java.util.List; import okhttp3.ResponseBody; -import retrofit2.Call; +import retrofit2.Response; +import retrofit2.Retrofit; import retrofit2.http.Body; import retrofit2.http.GET; +import retrofit2.http.HTTP; import retrofit2.http.Header; import retrofit2.http.Headers; -import retrofit2.http.HTTP; -import retrofit2.http.Path; import retrofit2.http.PUT; +import retrofit2.http.Path; import retrofit2.http.Query; import retrofit2.http.Url; -import retrofit2.Response; +import rx.Observable; +import rx.functions.Func1; + +import java.io.IOException; +import java.util.List; /** * An instance of this class provides access to all the operations defined @@ -63,31 +66,31 @@ public VaultsInner(Retrofit retrofit, KeyVaultManagementClientImpl client) { interface VaultsService { @Headers("Content-Type: application/json; charset=utf-8") @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}") - Call createOrUpdate(@Path("resourceGroupName") String resourceGroupName, @Path("vaultName") String vaultName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Body VaultCreateOrUpdateParametersInner parameters, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> createOrUpdate(@Path("resourceGroupName") String resourceGroupName, @Path("vaultName") String vaultName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Body VaultCreateOrUpdateParametersInner parameters, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}", method = "DELETE", hasBody = true) - Call delete(@Path("resourceGroupName") String resourceGroupName, @Path("vaultName") String vaultName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> delete(@Path("resourceGroupName") String resourceGroupName, @Path("vaultName") String vaultName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}") - Call get(@Path("resourceGroupName") String resourceGroupName, @Path("vaultName") String vaultName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> get(@Path("resourceGroupName") String resourceGroupName, @Path("vaultName") String vaultName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults") - Call listByResourceGroup(@Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("$top") Integer top, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> listByResourceGroup(@Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("$top") Integer top, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET("subscriptions/{subscriptionId}/resources") - Call list(@Path("subscriptionId") String subscriptionId, @Query("$filter") String filter, @Query("$top") Integer top, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> list(@Path("subscriptionId") String subscriptionId, @Query("$filter") String filter, @Query("$top") Integer top, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET - Call listByResourceGroupNext(@Url String nextPageLink, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> listByResourceGroupNext(@Url String nextPageLink, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers("Content-Type: application/json; charset=utf-8") @GET - Call listNext(@Url String nextPageLink, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + Observable> listNext(@Url String nextPageLink, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); } @@ -100,27 +103,10 @@ interface VaultsService { * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the VaultInner object wrapped in {@link ServiceResponse} if successful. + * @return the VaultInner object if successful. */ - public ServiceResponse createOrUpdate(String resourceGroupName, String vaultName, VaultCreateOrUpdateParametersInner parameters) throws CloudException, IOException, IllegalArgumentException { - if (resourceGroupName == null) { - throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); - } - if (vaultName == null) { - throw new IllegalArgumentException("Parameter vaultName is required and cannot be null."); - } - if (this.client.subscriptionId() == null) { - throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - if (parameters == null) { - throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); - } - Validator.validate(parameters); - Call call = service.createOrUpdate(resourceGroupName, vaultName, this.client.subscriptionId(), this.client.apiVersion(), parameters, this.client.acceptLanguage(), this.client.userAgent()); - return createOrUpdateDelegate(call.execute()); + public VaultInner createOrUpdate(String resourceGroupName, String vaultName, VaultCreateOrUpdateParametersInner parameters) throws CloudException, IOException, IllegalArgumentException { + return createOrUpdateWithServiceResponseAsync(resourceGroupName, vaultName, parameters).toBlocking().single().getBody(); } /** @@ -130,47 +116,66 @@ public ServiceResponse createOrUpdate(String resourceGroupName, Stri * @param vaultName Name of the vault * @param parameters Parameters to create or update the vault * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall createOrUpdateAsync(String resourceGroupName, String vaultName, VaultCreateOrUpdateParametersInner parameters, final ServiceCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall createOrUpdateAsync(String resourceGroupName, String vaultName, VaultCreateOrUpdateParametersInner parameters, final ServiceCallback serviceCallback) { + return ServiceCall.create(createOrUpdateWithServiceResponseAsync(resourceGroupName, vaultName, parameters), serviceCallback); + } + + /** + * Create or update a key vault in the specified subscription. + * + * @param resourceGroupName The name of the Resource Group to which the server belongs. + * @param vaultName Name of the vault + * @param parameters Parameters to create or update the vault + * @return the observable to the VaultInner object + */ + public Observable createOrUpdateAsync(String resourceGroupName, String vaultName, VaultCreateOrUpdateParametersInner parameters) { + return createOrUpdateWithServiceResponseAsync(resourceGroupName, vaultName, parameters).map(new Func1, VaultInner>() { + @Override + public VaultInner call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Create or update a key vault in the specified subscription. + * + * @param resourceGroupName The name of the Resource Group to which the server belongs. + * @param vaultName Name of the vault + * @param parameters Parameters to create or update the vault + * @return the observable to the VaultInner object + */ + public Observable> createOrUpdateWithServiceResponseAsync(String resourceGroupName, String vaultName, VaultCreateOrUpdateParametersInner parameters) { if (resourceGroupName == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (vaultName == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter vaultName is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter vaultName is required and cannot be null."); } if (this.client.subscriptionId() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } if (parameters == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter parameters is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); } - Validator.validate(parameters, serviceCallback); - Call call = service.createOrUpdate(resourceGroupName, vaultName, this.client.subscriptionId(), this.client.apiVersion(), parameters, this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - serviceCallback.success(createOrUpdateDelegate(response)); - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); + Validator.validate(parameters); + return service.createOrUpdate(resourceGroupName, vaultName, this.client.subscriptionId(), this.client.apiVersion(), parameters, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = createOrUpdateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } } - } - }); - return serviceCall; + }); } private ServiceResponse createOrUpdateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { @@ -189,23 +194,9 @@ private ServiceResponse createOrUpdateDelegate(Response delete(String resourceGroupName, String vaultName) throws CloudException, IOException, IllegalArgumentException { - if (resourceGroupName == null) { - throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); - } - if (vaultName == null) { - throw new IllegalArgumentException("Parameter vaultName is required and cannot be null."); - } - if (this.client.subscriptionId() == null) { - throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - Call call = service.delete(resourceGroupName, vaultName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - return deleteDelegate(call.execute()); + public void delete(String resourceGroupName, String vaultName) throws CloudException, IOException, IllegalArgumentException { + deleteWithServiceResponseAsync(resourceGroupName, vaultName).toBlocking().single().getBody(); } /** @@ -214,42 +205,60 @@ public ServiceResponse delete(String resourceGroupName, String vaultName) * @param resourceGroupName The name of the Resource Group to which the vault belongs. * @param vaultName The name of the vault to delete * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall deleteAsync(String resourceGroupName, String vaultName, final ServiceCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall deleteAsync(String resourceGroupName, String vaultName, final ServiceCallback serviceCallback) { + return ServiceCall.create(deleteWithServiceResponseAsync(resourceGroupName, vaultName), serviceCallback); + } + + /** + * Deletes the specified Azure key vault. + * + * @param resourceGroupName The name of the Resource Group to which the vault belongs. + * @param vaultName The name of the vault to delete + * @return the {@link ServiceResponse} object if successful. + */ + public Observable deleteAsync(String resourceGroupName, String vaultName) { + return deleteWithServiceResponseAsync(resourceGroupName, vaultName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Deletes the specified Azure key vault. + * + * @param resourceGroupName The name of the Resource Group to which the vault belongs. + * @param vaultName The name of the vault to delete + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> deleteWithServiceResponseAsync(String resourceGroupName, String vaultName) { if (resourceGroupName == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (vaultName == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter vaultName is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter vaultName is required and cannot be null."); } if (this.client.subscriptionId() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Call call = service.delete(resourceGroupName, vaultName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - serviceCallback.success(deleteDelegate(response)); - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); + return service.delete(resourceGroupName, vaultName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = deleteDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } } - } - }); - return serviceCall; + }); } private ServiceResponse deleteDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { @@ -266,23 +275,10 @@ private ServiceResponse deleteDelegate(Response response) th * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the VaultInner object wrapped in {@link ServiceResponse} if successful. + * @return the VaultInner object if successful. */ - public ServiceResponse get(String resourceGroupName, String vaultName) throws CloudException, IOException, IllegalArgumentException { - if (resourceGroupName == null) { - throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); - } - if (vaultName == null) { - throw new IllegalArgumentException("Parameter vaultName is required and cannot be null."); - } - if (this.client.subscriptionId() == null) { - throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - Call call = service.get(resourceGroupName, vaultName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - return getDelegate(call.execute()); + public VaultInner get(String resourceGroupName, String vaultName) throws CloudException, IOException, IllegalArgumentException { + return getWithServiceResponseAsync(resourceGroupName, vaultName).toBlocking().single().getBody(); } /** @@ -291,42 +287,60 @@ public ServiceResponse get(String resourceGroupName, String vaultNam * @param resourceGroupName The name of the Resource Group to which the vault belongs. * @param vaultName The name of the vault. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall getAsync(String resourceGroupName, String vaultName, final ServiceCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall getAsync(String resourceGroupName, String vaultName, final ServiceCallback serviceCallback) { + return ServiceCall.create(getWithServiceResponseAsync(resourceGroupName, vaultName), serviceCallback); + } + + /** + * Gets the specified Azure key vault. + * + * @param resourceGroupName The name of the Resource Group to which the vault belongs. + * @param vaultName The name of the vault. + * @return the observable to the VaultInner object + */ + public Observable getAsync(String resourceGroupName, String vaultName) { + return getWithServiceResponseAsync(resourceGroupName, vaultName).map(new Func1, VaultInner>() { + @Override + public VaultInner call(ServiceResponse response) { + return response.getBody(); + } + }); + } + + /** + * Gets the specified Azure key vault. + * + * @param resourceGroupName The name of the Resource Group to which the vault belongs. + * @param vaultName The name of the vault. + * @return the observable to the VaultInner object + */ + public Observable> getWithServiceResponseAsync(String resourceGroupName, String vaultName) { if (resourceGroupName == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (vaultName == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter vaultName is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter vaultName is required and cannot be null."); } if (this.client.subscriptionId() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Call call = service.get(resourceGroupName, vaultName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - serviceCallback.success(getDelegate(response)); - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); + return service.get(resourceGroupName, vaultName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } } - } - }); - return serviceCall; + }); } private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { @@ -343,28 +357,16 @@ private ServiceResponse getDelegate(Response response) * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<VaultInner> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<VaultInner> object if successful. */ - public ServiceResponse> listByResourceGroup(final String resourceGroupName) throws CloudException, IOException, IllegalArgumentException { - if (resourceGroupName == null) { - throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); - } - if (this.client.subscriptionId() == null) { - throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - final Integer top = null; - Call call = service.listByResourceGroup(resourceGroupName, this.client.subscriptionId(), top, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - ServiceResponse> response = listByResourceGroupDelegate(call.execute()); - PagedList result = new PagedList(response.getBody()) { + public PagedList listByResourceGroup(final String resourceGroupName) throws CloudException, IOException, IllegalArgumentException { + ServiceResponse> response = listByResourceGroupSinglePageAsync(resourceGroupName).toBlocking().single(); + return new PagedList(response.getBody()) { @Override - public Page nextPage(String nextPageLink) throws CloudException, IOException { - return listByResourceGroupNext(nextPageLink).getBody(); + public Page nextPage(String nextPageLink) throws RestException, IOException { + return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse<>(result, response.getResponse()); } /** @@ -372,46 +374,85 @@ public Page nextPage(String nextPageLink) throws CloudException, IOE * * @param resourceGroupName The name of the Resource Group to which the vault belongs. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall listByResourceGroupAsync(final String resourceGroupName, final ListOperationCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall> listByResourceGroupAsync(final String resourceGroupName, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + listByResourceGroupSinglePageAsync(resourceGroupName), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByResourceGroupNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * The List operation gets information about the vaults associated with the subscription and within the specified resource group. + * + * @param resourceGroupName The name of the Resource Group to which the vault belongs. + * @return the observable to the PagedList<VaultInner> object + */ + public Observable> listByResourceGroupAsync(final String resourceGroupName) { + return listByResourceGroupWithServiceResponseAsync(resourceGroupName) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * The List operation gets information about the vaults associated with the subscription and within the specified resource group. + * + * @param resourceGroupName The name of the Resource Group to which the vault belongs. + * @return the observable to the PagedList<VaultInner> object + */ + public Observable>> listByResourceGroupWithServiceResponseAsync(final String resourceGroupName) { + return listByResourceGroupSinglePageAsync(resourceGroupName) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * The List operation gets information about the vaults associated with the subscription and within the specified resource group. + * + * @param resourceGroupName The name of the Resource Group to which the vault belongs. + * @return the PagedList<VaultInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByResourceGroupSinglePageAsync(final String resourceGroupName) { if (resourceGroupName == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (this.client.subscriptionId() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } final Integer top = null; - Call call = service.listByResourceGroup(resourceGroupName, this.client.subscriptionId(), top, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = listByResourceGroupDelegate(response); - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - listByResourceGroupNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); + return service.listByResourceGroup(resourceGroupName, this.client.subscriptionId(), top, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByResourceGroupDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); } - } - }); - return serviceCall; + }); } /** @@ -422,27 +463,16 @@ public void onResponse(Call call, Response response) * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<VaultInner> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<VaultInner> object if successful. */ - public ServiceResponse> listByResourceGroup(final String resourceGroupName, final Integer top) throws CloudException, IOException, IllegalArgumentException { - if (resourceGroupName == null) { - throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); - } - if (this.client.subscriptionId() == null) { - throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); - } - if (this.client.apiVersion() == null) { - throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); - } - Call call = service.listByResourceGroup(resourceGroupName, this.client.subscriptionId(), top, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - ServiceResponse> response = listByResourceGroupDelegate(call.execute()); - PagedList result = new PagedList(response.getBody()) { + public PagedList listByResourceGroup(final String resourceGroupName, final Integer top) throws CloudException, IOException, IllegalArgumentException { + ServiceResponse> response = listByResourceGroupSinglePageAsync(resourceGroupName, top).toBlocking().single(); + return new PagedList(response.getBody()) { @Override - public Page nextPage(String nextPageLink) throws CloudException, IOException { - return listByResourceGroupNext(nextPageLink).getBody(); + public Page nextPage(String nextPageLink) throws RestException, IOException { + return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse<>(result, response.getResponse()); } /** @@ -451,45 +481,87 @@ public Page nextPage(String nextPageLink) throws CloudException, IOE * @param resourceGroupName The name of the Resource Group to which the vault belongs. * @param top Maximum number of results to return. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall listByResourceGroupAsync(final String resourceGroupName, final Integer top, final ListOperationCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall> listByResourceGroupAsync(final String resourceGroupName, final Integer top, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + listByResourceGroupSinglePageAsync(resourceGroupName, top), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByResourceGroupNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * The List operation gets information about the vaults associated with the subscription and within the specified resource group. + * + * @param resourceGroupName The name of the Resource Group to which the vault belongs. + * @param top Maximum number of results to return. + * @return the observable to the PagedList<VaultInner> object + */ + public Observable> listByResourceGroupAsync(final String resourceGroupName, final Integer top) { + return listByResourceGroupWithServiceResponseAsync(resourceGroupName, top) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * The List operation gets information about the vaults associated with the subscription and within the specified resource group. + * + * @param resourceGroupName The name of the Resource Group to which the vault belongs. + * @param top Maximum number of results to return. + * @return the observable to the PagedList<VaultInner> object + */ + public Observable>> listByResourceGroupWithServiceResponseAsync(final String resourceGroupName, final Integer top) { + return listByResourceGroupSinglePageAsync(resourceGroupName, top) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * The List operation gets information about the vaults associated with the subscription and within the specified resource group. + * + ServiceResponse> * @param resourceGroupName The name of the Resource Group to which the vault belongs. + ServiceResponse> * @param top Maximum number of results to return. + * @return the PagedList<VaultInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByResourceGroupSinglePageAsync(final String resourceGroupName, final Integer top) { if (resourceGroupName == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (this.client.subscriptionId() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (this.client.apiVersion() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } - Call call = service.listByResourceGroup(resourceGroupName, this.client.subscriptionId(), top, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = listByResourceGroupDelegate(response); - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - listByResourceGroupNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); + return service.listByResourceGroup(resourceGroupName, this.client.subscriptionId(), top, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByResourceGroupDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse> listByResourceGroupDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { @@ -505,64 +577,94 @@ private ServiceResponse> listByResourceGroupDelegate(Respon * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<VaultInner> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<VaultInner> object if successful. */ - public ServiceResponse> list() throws CloudException, IOException, IllegalArgumentException { - if (this.client.subscriptionId() == null) { - throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); - } - final String filter = "resourceType eq 'Microsoft.KeyVault/vaults'"; - final String apiVersion = "2015-11-01"; - final Integer top = null; - Call call = service.list(this.client.subscriptionId(), filter, top, apiVersion, this.client.acceptLanguage(), this.client.userAgent()); - ServiceResponse> response = listDelegate(call.execute()); - PagedList result = new PagedList(response.getBody()) { + public PagedList list() throws CloudException, IOException, IllegalArgumentException { + ServiceResponse> response = listSinglePageAsync().toBlocking().single(); + return new PagedList(response.getBody()) { @Override - public Page nextPage(String nextPageLink) throws CloudException, IOException { - return listNext(nextPageLink).getBody(); + public Page nextPage(String nextPageLink) throws RestException, IOException { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse<>(result, response.getResponse()); } /** * The List operation gets information about the vaults associated with the subscription. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall listAsync(final ListOperationCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall> listAsync(final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + listSinglePageAsync(), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * The List operation gets information about the vaults associated with the subscription. + * + * @return the observable to the PagedList<VaultInner> object + */ + public Observable> listAsync() { + return listWithServiceResponseAsync() + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * The List operation gets information about the vaults associated with the subscription. + * + * @return the observable to the PagedList<VaultInner> object + */ + public Observable>> listWithServiceResponseAsync() { + return listSinglePageAsync() + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * The List operation gets information about the vaults associated with the subscription. + * + * @return the PagedList<VaultInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync() { if (this.client.subscriptionId() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } final String filter = "resourceType eq 'Microsoft.KeyVault/vaults'"; final String apiVersion = "2015-11-01"; final Integer top = null; - Call call = service.list(this.client.subscriptionId(), filter, top, apiVersion, this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = listDelegate(response); - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - listNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); + return service.list(this.client.subscriptionId(), filter, top, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); } - } - }); - return serviceCall; + }); } /** @@ -572,23 +674,16 @@ public void onResponse(Call call, Response response) * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<VaultInner> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<VaultInner> object if successful. */ - public ServiceResponse> list(final Integer top) throws CloudException, IOException, IllegalArgumentException { - if (this.client.subscriptionId() == null) { - throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); - } - final String filter = "resourceType eq 'Microsoft.KeyVault/vaults'"; - final String apiVersion = "2015-11-01"; - Call call = service.list(this.client.subscriptionId(), filter, top, apiVersion, this.client.acceptLanguage(), this.client.userAgent()); - ServiceResponse> response = listDelegate(call.execute()); - PagedList result = new PagedList(response.getBody()) { + public PagedList list(final Integer top) throws CloudException, IOException, IllegalArgumentException { + ServiceResponse> response = listSinglePageAsync(top).toBlocking().single(); + return new PagedList(response.getBody()) { @Override - public Page nextPage(String nextPageLink) throws CloudException, IOException { - return listNext(nextPageLink).getBody(); + public Page nextPage(String nextPageLink) throws RestException, IOException { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); } }; - return new ServiceResponse<>(result, response.getResponse()); } /** @@ -596,39 +691,80 @@ public Page nextPage(String nextPageLink) throws CloudException, IOE * * @param top Maximum number of results to return. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall listAsync(final Integer top, final ListOperationCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall> listAsync(final Integer top, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + listSinglePageAsync(top), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * The List operation gets information about the vaults associated with the subscription. + * + * @param top Maximum number of results to return. + * @return the observable to the PagedList<VaultInner> object + */ + public Observable> listAsync(final Integer top) { + return listWithServiceResponseAsync(top) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * The List operation gets information about the vaults associated with the subscription. + * + * @param top Maximum number of results to return. + * @return the observable to the PagedList<VaultInner> object + */ + public Observable>> listWithServiceResponseAsync(final Integer top) { + return listSinglePageAsync(top) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * The List operation gets information about the vaults associated with the subscription. + * + ServiceResponse> * @param top Maximum number of results to return. + * @return the PagedList<VaultInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync(final Integer top) { if (this.client.subscriptionId() == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } final String filter = "resourceType eq 'Microsoft.KeyVault/vaults'"; final String apiVersion = "2015-11-01"; - Call call = service.list(this.client.subscriptionId(), filter, top, apiVersion, this.client.acceptLanguage(), this.client.userAgent()); - final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = listDelegate(response); - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - listNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); + return service.list(this.client.subscriptionId(), filter, top, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { @@ -645,14 +781,16 @@ private ServiceResponse> listDelegate(Response> listByResourceGroupNext(final String nextPageLink) throws CloudException, IOException, IllegalArgumentException { - if (nextPageLink == null) { - throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); - } - Call call = service.listByResourceGroupNext(nextPageLink, this.client.acceptLanguage(), this.client.userAgent()); - return listByResourceGroupNextDelegate(call.execute()); + public PagedList listByResourceGroupNext(final String nextPageLink) throws CloudException, IOException, IllegalArgumentException { + ServiceResponse> response = listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.getBody()) { + @Override + public Page nextPage(String nextPageLink) throws RestException, IOException { + return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); + } + }; } /** @@ -661,37 +799,78 @@ public ServiceResponse> listByResourceGroupNext(final Strin * @param nextPageLink The NextLink from the previous successful call to List operation. * @param serviceCall the ServiceCall object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall listByResourceGroupNextAsync(final String nextPageLink, final ServiceCall serviceCall, final ListOperationCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall> listByResourceGroupNextAsync(final String nextPageLink, final ServiceCall> serviceCall, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + listByResourceGroupNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByResourceGroupNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * The List operation gets information about the vaults associated with the subscription and within the specified resource group. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the observable to the PagedList<VaultInner> object + */ + public Observable> listByResourceGroupNextAsync(final String nextPageLink) { + return listByResourceGroupNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * The List operation gets information about the vaults associated with the subscription and within the specified resource group. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the observable to the PagedList<VaultInner> object + */ + public Observable>> listByResourceGroupNextWithServiceResponseAsync(final String nextPageLink) { + return listByResourceGroupNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * The List operation gets information about the vaults associated with the subscription and within the specified resource group. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the PagedList<VaultInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByResourceGroupNextSinglePageAsync(final String nextPageLink) { if (nextPageLink == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); } - Call call = service.listByResourceGroupNext(nextPageLink, this.client.acceptLanguage(), this.client.userAgent()); - serviceCall.newCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = listByResourceGroupNextDelegate(response); - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - listByResourceGroupNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); + return service.listByResourceGroupNext(nextPageLink, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByResourceGroupNextDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse> listByResourceGroupNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { @@ -708,14 +887,16 @@ private ServiceResponse> listByResourceGroupNextDelegate(Re * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters - * @return the List<VaultInner> object wrapped in {@link ServiceResponse} if successful. + * @return the PagedList<VaultInner> object if successful. */ - public ServiceResponse> listNext(final String nextPageLink) throws CloudException, IOException, IllegalArgumentException { - if (nextPageLink == null) { - throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); - } - Call call = service.listNext(nextPageLink, this.client.acceptLanguage(), this.client.userAgent()); - return listNextDelegate(call.execute()); + public PagedList listNext(final String nextPageLink) throws CloudException, IOException, IllegalArgumentException { + ServiceResponse> response = listNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.getBody()) { + @Override + public Page nextPage(String nextPageLink) throws RestException, IOException { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().getBody(); + } + }; } /** @@ -724,37 +905,78 @@ public ServiceResponse> listNext(final String nextPageLink) * @param nextPageLink The NextLink from the previous successful call to List operation. * @param serviceCall the ServiceCall object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. - * @throws IllegalArgumentException thrown if callback is null - * @return the {@link Call} object + * @return the {@link ServiceCall} object */ - public ServiceCall listNextAsync(final String nextPageLink, final ServiceCall serviceCall, final ListOperationCallback serviceCallback) throws IllegalArgumentException { - if (serviceCallback == null) { - throw new IllegalArgumentException("ServiceCallback is required for async calls."); - } + public ServiceCall> listNextAsync(final String nextPageLink, final ServiceCall> serviceCall, final ListOperationCallback serviceCallback) { + return AzureServiceCall.create( + listNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * The List operation gets information about the vaults associated with the subscription. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the observable to the PagedList<VaultInner> object + */ + public Observable> listNextAsync(final String nextPageLink) { + return listNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.getBody(); + } + }); + } + + /** + * The List operation gets information about the vaults associated with the subscription. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the observable to the PagedList<VaultInner> object + */ + public Observable>> listNextWithServiceResponseAsync(final String nextPageLink) { + return listNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.getBody().getNextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * The List operation gets information about the vaults associated with the subscription. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @return the PagedList<VaultInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listNextSinglePageAsync(final String nextPageLink) { if (nextPageLink == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.")); - return null; + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); } - Call call = service.listNext(nextPageLink, this.client.acceptLanguage(), this.client.userAgent()); - serviceCall.newCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCallback) { - @Override - public void onResponse(Call call, Response response) { - try { - ServiceResponse> result = listNextDelegate(response); - serviceCallback.load(result.getBody().getItems()); - if (result.getBody().getNextPageLink() != null - && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - listNextAsync(result.getBody().getNextPageLink(), serviceCall, serviceCallback); - } else { - serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); + return service.listNext(nextPageLink, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listNextDelegate(response); + return Observable.just(new ServiceResponse>(result.getBody(), result.getResponse())); + } catch (Throwable t) { + return Observable.error(t); } - } catch (CloudException | IOException exception) { - serviceCallback.failure(exception); } - } - }); - return serviceCall; + }); } private ServiceResponse> listNextDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { diff --git a/azure-mgmt-keyvault/src/test/java/com/microsoft/azure/management/keyvault/KeyVaultManagementTestBase.java b/azure-mgmt-keyvault/src/test/java/com/microsoft/azure/management/keyvault/KeyVaultManagementTestBase.java new file mode 100644 index 0000000000000..a55f9c6e85061 --- /dev/null +++ b/azure-mgmt-keyvault/src/test/java/com/microsoft/azure/management/keyvault/KeyVaultManagementTestBase.java @@ -0,0 +1,42 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + */ + +package com.microsoft.azure.management.keyvault; + +import com.microsoft.azure.AzureEnvironment; +import com.microsoft.azure.RestClient; +import com.microsoft.azure.credentials.ApplicationTokenCredentials; +import com.microsoft.azure.management.keyvault.implementation.KeyVaultManager; +import com.microsoft.azure.management.resources.implementation.ResourceManager; +import okhttp3.logging.HttpLoggingInterceptor; + +/** + * The base for storage manager tests. + */ +public abstract class KeyVaultManagementTestBase { + protected static ResourceManager resourceManager; + protected static KeyVaultManager keyVaultManager; + + protected static void createClients() { + ApplicationTokenCredentials credentials = new ApplicationTokenCredentials( + System.getenv("client-id"), + System.getenv("domain"), + System.getenv("secret"), + AzureEnvironment.AZURE); + + RestClient restClient = AzureEnvironment.AZURE.newRestClientBuilder() + .withCredentials(credentials) + .withLogLevel(HttpLoggingInterceptor.Level.BODY) + .build(); + + resourceManager = ResourceManager + .authenticate(restClient) + .withSubscription(System.getenv("subscription-id")); + + keyVaultManager = KeyVaultManager + .authenticate(restClient, System.getenv("domain"), System.getenv("subscription-id")); + } +} diff --git a/azure-mgmt-keyvault/src/test/java/com/microsoft/azure/management/keyvault/VaultTests.java b/azure-mgmt-keyvault/src/test/java/com/microsoft/azure/management/keyvault/VaultTests.java new file mode 100644 index 0000000000000..eb647251cae63 --- /dev/null +++ b/azure-mgmt-keyvault/src/test/java/com/microsoft/azure/management/keyvault/VaultTests.java @@ -0,0 +1,91 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + */ + +package com.microsoft.azure.management.keyvault; + +import com.microsoft.azure.management.resources.fluentcore.arm.Region; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.List; + +public class VaultTests extends KeyVaultManagementTestBase { + private static final String RG_NAME = "javacsmrg905"; + private static final String VAULT_NAME = "java-keyvault-905"; + + @BeforeClass + public static void setup() throws Exception { + createClients(); + } + + @AfterClass + public static void cleanup() throws Exception { + //resourceManager.resourceGroups().delete(RG_NAME); + } + + @Test + public void canCRUDVault() throws Exception { + // CREATE + Vault vault = keyVaultManager.vaults().define(VAULT_NAME) + .withRegion(Region.US_WEST) + .withNewResourceGroup(RG_NAME) + .defineAccessPolicy() + .forServicePrincipal("http://nativeapp") + .allowKeyPermissions(KeyPermissions.LIST) + .allowSecretAllPermissions() + .attach() + .defineAccessPolicy() + .forUser("admin2@azuresdkteam.onmicrosoft.com") + .allowKeyAllPermissions() + .allowSecretAllPermissions() + .attach() + .create(); + Assert.assertNotNull(vault); + // GET + vault = keyVaultManager.vaults().getByGroup(RG_NAME, VAULT_NAME); + Assert.assertNotNull(vault); + for (AccessPolicy policy : vault.accessPolicies()) { + if (policy.objectId().equals("8188d1e8-3090-4e3c-aa76-38cf2b5c7b3a")) { + Assert.assertArrayEquals(new KeyPermissions[] { KeyPermissions.LIST }, policy.permissions().keys().toArray()); + Assert.assertArrayEquals(new SecretPermissions[] { SecretPermissions.ALL }, policy.permissions().secrets().toArray()); + } + if (policy.objectId().equals("5963f50c-7c43-405c-af7e-53294de76abd")) { + Assert.assertArrayEquals(new KeyPermissions[] { KeyPermissions.ALL }, policy.permissions().keys().toArray()); + Assert.assertArrayEquals(new SecretPermissions[] { SecretPermissions.ALL }, policy.permissions().secrets().toArray()); + } + } + // LIST + List vaults = keyVaultManager.vaults().listByGroup(RG_NAME); + for (Vault v : vaults) { + if (VAULT_NAME.equals(v.name())) { + vault = v; + break; + } + } + Assert.assertNotNull(vault); + // UPDATE + vault.update() + .updateAccessPolicy(vault.accessPolicies().get(0).objectId()) + .allowKeyAllPermissions() + .disallowSecretAllPermissions() + .parent() + .apply(); + for (AccessPolicy policy : vault.accessPolicies()) { + if (policy.objectId().equals("8188d1e8-3090-4e3c-aa76-38cf2b5c7b3a")) { + Assert.assertArrayEquals(new KeyPermissions[] { KeyPermissions.LIST, KeyPermissions.ALL }, policy.permissions().keys().toArray()); + Assert.assertArrayEquals(new SecretPermissions[] { }, policy.permissions().secrets().toArray()); + } + } + vault.update() + .defineAccessPolicy() + .forServicePrincipal("https://graphapp") + .allowKeyAllPermissions() + .attach() + .apply(); + } +} diff --git a/azure-mgmt-network/src/main/java/com/microsoft/azure/management/network/implementation/LoadBalancerImpl.java b/azure-mgmt-network/src/main/java/com/microsoft/azure/management/network/implementation/LoadBalancerImpl.java index 108c9d94a7a24..e47cce47525ff 100644 --- a/azure-mgmt-network/src/main/java/com/microsoft/azure/management/network/implementation/LoadBalancerImpl.java +++ b/azure-mgmt-network/src/main/java/com/microsoft/azure/management/network/implementation/LoadBalancerImpl.java @@ -20,9 +20,9 @@ import com.microsoft.azure.management.network.ProbeProtocol; import com.microsoft.azure.management.network.PublicIpAddress; import com.microsoft.azure.management.network.PublicIpAddress.DefinitionStages.WithGroup; -import com.microsoft.azure.management.network.model.HasNetworkInterfaces; import com.microsoft.azure.management.network.TcpProbe; import com.microsoft.azure.management.network.TransportProtocol; +import com.microsoft.azure.management.network.model.HasNetworkInterfaces; import com.microsoft.azure.management.resources.fluentcore.arm.ResourceUtils; import com.microsoft.azure.management.resources.fluentcore.arm.models.implementation.GroupableParentResourceImpl; import com.microsoft.azure.management.resources.fluentcore.model.Creatable; diff --git a/azure-mgmt-network/src/main/java/com/microsoft/azure/management/network/implementation/NetworkInterfacesImpl.java b/azure-mgmt-network/src/main/java/com/microsoft/azure/management/network/implementation/NetworkInterfacesImpl.java index 45ff125bd78c4..4778bba77079d 100644 --- a/azure-mgmt-network/src/main/java/com/microsoft/azure/management/network/implementation/NetworkInterfacesImpl.java +++ b/azure-mgmt-network/src/main/java/com/microsoft/azure/management/network/implementation/NetworkInterfacesImpl.java @@ -3,8 +3,8 @@ import com.microsoft.azure.CloudException; import com.microsoft.azure.PagedList; import com.microsoft.azure.management.network.NetworkInterface; -import com.microsoft.azure.management.network.NetworkInterfaces; import com.microsoft.azure.management.network.NetworkInterfaceDnsSettings; +import com.microsoft.azure.management.network.NetworkInterfaces; import com.microsoft.azure.management.resources.fluentcore.arm.ResourceUtils; import com.microsoft.azure.management.resources.fluentcore.arm.collection.implementation.GroupableResourcesImpl; diff --git a/azure-mgmt-network/src/main/java/com/microsoft/azure/management/network/implementation/NetworksImpl.java b/azure-mgmt-network/src/main/java/com/microsoft/azure/management/network/implementation/NetworksImpl.java index b3cc00ca49087..6e9038a5eb901 100644 --- a/azure-mgmt-network/src/main/java/com/microsoft/azure/management/network/implementation/NetworksImpl.java +++ b/azure-mgmt-network/src/main/java/com/microsoft/azure/management/network/implementation/NetworksImpl.java @@ -7,10 +7,10 @@ import com.microsoft.azure.CloudException; import com.microsoft.azure.PagedList; -import com.microsoft.azure.management.network.Network; -import com.microsoft.azure.management.network.Networks; import com.microsoft.azure.management.network.AddressSpace; import com.microsoft.azure.management.network.DhcpOptions; +import com.microsoft.azure.management.network.Network; +import com.microsoft.azure.management.network.Networks; import com.microsoft.azure.management.resources.fluentcore.arm.ResourceUtils; import com.microsoft.azure.management.resources.fluentcore.arm.collection.implementation.GroupableResourcesImpl; diff --git a/azure-mgmt-redis/src/main/java/com/microsoft/azure/management/redis/SkuFamily.java b/azure-mgmt-redis/src/main/java/com/microsoft/azure/management/redis/SkuFamily.java index 4027ed51be408..0c37984ddee56 100644 --- a/azure-mgmt-redis/src/main/java/com/microsoft/azure/management/redis/SkuFamily.java +++ b/azure-mgmt-redis/src/main/java/com/microsoft/azure/management/redis/SkuFamily.java @@ -56,4 +56,4 @@ public boolean equals(Object obj) { return value.equals(rhs.value); } } -} +} \ No newline at end of file diff --git a/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/fluentcore/arm/models/implementation/GroupPagedList.java b/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/fluentcore/arm/models/implementation/GroupPagedList.java index bc8e194337765..2ad8436c50398 100644 --- a/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/fluentcore/arm/models/implementation/GroupPagedList.java +++ b/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/fluentcore/arm/models/implementation/GroupPagedList.java @@ -13,9 +13,9 @@ import com.microsoft.rest.RestException; import java.io.IOException; -import java.util.LinkedList; +import java.util.ArrayList; +import java.util.Iterator; import java.util.List; -import java.util.Queue; /** * Defines a list of resources paginated across resource groups. @@ -23,9 +23,7 @@ * @param the item type */ public abstract class GroupPagedList extends PagedList { - private PagedList resourceGroupList; - private Page currentPage; - private Queue queue; + private Iterator resourceGroupItr; /** * Creates an instance from a list of resource groups. @@ -33,27 +31,28 @@ public abstract class GroupPagedList extends PagedList { * @param resourceGroupList the list of resource groups */ public GroupPagedList(PagedList resourceGroupList) { - this.resourceGroupList = resourceGroupList; - this.currentPage = resourceGroupList.currentPage(); - this.queue = new LinkedList<>(currentPage.getItems()); - } - - @Override - public boolean hasNextPage() { - return !queue.isEmpty() || this.currentPage.getNextPageLink() != null; + this.resourceGroupItr = resourceGroupList.iterator(); + try { + setCurrentPage(nextPage("dummy")); + } catch (IOException e) { + throw new RuntimeException(e); + } } @Override public Page nextPage(String s) throws RestException, IOException { - if (queue.isEmpty()) { - this.currentPage = resourceGroupList.nextPage(this.currentPage.getNextPageLink()); - queue.addAll(this.currentPage.getItems()); + if (resourceGroupItr.hasNext()) { + ResourceGroup resourceGroup = resourceGroupItr.next(); + PageImpl page = new PageImpl<>(); + page.setItems(listNextGroup(resourceGroup.name())); + page.setNextPageLink(s); + return page; + } else { + // return an empty page without next link so that iteration will terminate + PageImpl page = new PageImpl<>(); + page.setItems(new ArrayList()); + return page; } - - ResourceGroup resourceGroup = queue.poll(); - PageImpl page = new PageImpl<>(); - page.setItems(listNextGroup(resourceGroup.name())); - return page; } /** diff --git a/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/fluentcore/collection/SupportsListing.java b/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/fluentcore/collection/SupportsListing.java index f89bf32a552d6..bb9156b0bd92f 100644 --- a/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/fluentcore/collection/SupportsListing.java +++ b/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/fluentcore/collection/SupportsListing.java @@ -6,8 +6,8 @@ package com.microsoft.azure.management.resources.fluentcore.collection; -import com.microsoft.azure.CloudException; import com.microsoft.azure.PagedList; +import com.microsoft.rest.RestException; import java.io.IOException; @@ -23,8 +23,8 @@ public interface SupportsListing { * Lists all the resources of the specified type in the currently selected subscription. * * @return list of resources - * @throws CloudException exceptions thrown from the cloud. + * @throws RestException exceptions thrown from the cloud. * @throws IOException exceptions thrown from serialization/deserialization. */ - PagedList list() throws CloudException, IOException; + PagedList list() throws RestException, IOException; } diff --git a/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/fluentcore/model/Creatable.java b/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/fluentcore/model/Creatable.java index 0533b0a2ba2ef..a967126723574 100644 --- a/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/fluentcore/model/Creatable.java +++ b/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/fluentcore/model/Creatable.java @@ -42,7 +42,7 @@ public interface Creatable extends Indexable { * Puts the request into the queue and allow the HTTP client to execute * it when system resources are available. * - * @return a handle to cancel the request + * @return an observable of the request */ Observable createAsync(); } \ No newline at end of file diff --git a/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/fluentcore/model/implementation/IndexableImpl.java b/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/fluentcore/model/implementation/IndexableImpl.java index 7530de3432448..43ca1e3f9c42e 100644 --- a/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/fluentcore/model/implementation/IndexableImpl.java +++ b/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/fluentcore/model/implementation/IndexableImpl.java @@ -13,7 +13,7 @@ /** * The base implementation for {@link Indexable}. */ -public abstract class IndexableImpl implements Indexable { +abstract class IndexableImpl implements Indexable { protected String key; protected IndexableImpl() { diff --git a/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/DeploymentOperationsImpl.java b/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/DeploymentOperationsImpl.java index 73f3185ceaec5..0dba4a4aa4c6c 100644 --- a/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/DeploymentOperationsImpl.java +++ b/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/DeploymentOperationsImpl.java @@ -12,6 +12,7 @@ import com.microsoft.azure.management.resources.DeploymentOperation; import com.microsoft.azure.management.resources.DeploymentOperations; import com.microsoft.azure.management.resources.fluentcore.arm.collection.implementation.ReadableWrappersImpl; + import java.io.IOException; /** diff --git a/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/DeploymentsImpl.java b/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/DeploymentsImpl.java index 4214b34988e86..ed2ca9d51b2b8 100644 --- a/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/DeploymentsImpl.java +++ b/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/DeploymentsImpl.java @@ -45,7 +45,7 @@ public Deployment typeConvert(DeploymentExtendedInner deploymentInner) { } @Override - public PagedList list() throws CloudException, IOException { + public PagedList list() throws RestException, IOException { return new GroupPagedList(this.resourceManager.resourceGroups().list()) { @Override public List listNextGroup(String resourceGroupName) throws RestException, IOException { @@ -62,13 +62,9 @@ public PagedList listByGroup(String groupName) throws CloudException @Override public Deployment getByName(String name) throws IOException, CloudException { for (ResourceGroup group : this.resourceManager.resourceGroups().list()) { - try { - DeploymentExtendedInner inner = client.get(group.name(), name); - if (inner != null) { - return createFluentModel(inner); - } - } catch (CloudException ex) { - // Do nothing + DeploymentExtendedInner inner = client.get(group.name(), name); + if (inner != null) { + return createFluentModel(inner); } } return null; diff --git a/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/FeaturesImpl.java b/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/FeaturesImpl.java index 40be00ce6c410..34ade7e2cfcbe 100644 --- a/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/FeaturesImpl.java +++ b/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/FeaturesImpl.java @@ -8,9 +8,10 @@ import com.microsoft.azure.CloudException; import com.microsoft.azure.PagedList; +import com.microsoft.azure.management.resources.Feature; import com.microsoft.azure.management.resources.Features; import com.microsoft.azure.management.resources.fluentcore.arm.collection.implementation.ReadableWrappersImpl; -import com.microsoft.azure.management.resources.Feature; + import java.io.IOException; /** diff --git a/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/FeaturesInResourceProviderImpl.java b/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/FeaturesInResourceProviderImpl.java index 325cd951c4abb..c1be1b5bbdf0b 100644 --- a/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/FeaturesInResourceProviderImpl.java +++ b/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/FeaturesInResourceProviderImpl.java @@ -11,6 +11,7 @@ import com.microsoft.azure.management.resources.Feature; import com.microsoft.azure.management.resources.Features; import com.microsoft.azure.management.resources.fluentcore.utils.PagedListConverter; +import com.microsoft.rest.RestException; import java.io.IOException; @@ -28,7 +29,7 @@ final class FeaturesInResourceProviderImpl } @Override - public PagedList list() throws CloudException, IOException { + public PagedList list() throws RestException, IOException { PagedListConverter converter = new PagedListConverter() { @Override public Feature typeConvert(FeatureResultInner tenantInner) { diff --git a/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/ResourceGroupsImpl.java b/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/ResourceGroupsImpl.java index c2d3edb1564cf..f609c088d3095 100644 --- a/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/ResourceGroupsImpl.java +++ b/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/ResourceGroupsImpl.java @@ -8,9 +8,9 @@ import com.microsoft.azure.CloudException; import com.microsoft.azure.PagedList; +import com.microsoft.azure.management.resources.ResourceGroup; import com.microsoft.azure.management.resources.ResourceGroups; import com.microsoft.azure.management.resources.fluentcore.arm.collection.implementation.CreatableResourcesImpl; -import com.microsoft.azure.management.resources.ResourceGroup; import java.io.IOException; diff --git a/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/SubscriptionsImpl.java b/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/SubscriptionsImpl.java index 9e06529b67a09..948704d62b419 100644 --- a/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/SubscriptionsImpl.java +++ b/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/SubscriptionsImpl.java @@ -11,6 +11,7 @@ import com.microsoft.azure.management.resources.Subscription; import com.microsoft.azure.management.resources.Subscriptions; import com.microsoft.azure.management.resources.fluentcore.utils.PagedListConverter; +import com.microsoft.rest.RestException; import java.io.IOException; @@ -26,7 +27,7 @@ final class SubscriptionsImpl } @Override - public PagedList list() throws CloudException, IOException { + public PagedList list() throws RestException, IOException { PagedListConverter converter = new PagedListConverter() { @Override public Subscription typeConvert(SubscriptionInner subscriptionInner) { diff --git a/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/TenantsImpl.java b/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/TenantsImpl.java index 92fc559b1f7aa..4d760e5b6f0c9 100644 --- a/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/TenantsImpl.java +++ b/azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/TenantsImpl.java @@ -6,11 +6,11 @@ package com.microsoft.azure.management.resources.implementation; -import com.microsoft.azure.CloudException; import com.microsoft.azure.PagedList; import com.microsoft.azure.management.resources.Tenant; import com.microsoft.azure.management.resources.Tenants; import com.microsoft.azure.management.resources.fluentcore.utils.PagedListConverter; +import com.microsoft.rest.RestException; import java.io.IOException; @@ -26,7 +26,7 @@ final class TenantsImpl } @Override - public PagedList list() throws CloudException, IOException { + public PagedList list() throws RestException, IOException { PagedListConverter converter = new PagedListConverter() { @Override public Tenant typeConvert(TenantIdDescriptionInner tenantInner) { diff --git a/azure-mgmt-resources/src/test/java/com/microsoft/azure/management/resources/GroupPagedListTests.java b/azure-mgmt-resources/src/test/java/com/microsoft/azure/management/resources/GroupPagedListTests.java index a501edd19a71b..31e258ae08a11 100644 --- a/azure-mgmt-resources/src/test/java/com/microsoft/azure/management/resources/GroupPagedListTests.java +++ b/azure-mgmt-resources/src/test/java/com/microsoft/azure/management/resources/GroupPagedListTests.java @@ -57,24 +57,24 @@ public void isResourceLoadedLazily() { pages.get(3).setNextPageLink(null); List expected = Arrays.asList( + "1", "RG1Vm1", "RG1Vm2", "RG2Vm1", "RG2Vm2", "RG3Vm1", "RG3Vm2", "RG4Vm1", "RG4Vm2", "RG5Vm1", "RG5Vm2", - "1", + "2", "RG6Vm1", "RG6Vm2", "RG7AVm1", "RG7Vm2", "RG8AVm1", "RG8Vm2", "RG9AVm1", "RG9Vm2", "RG10AVm1", "RG10Vm2", - "2", + "3", "RG11Vm1", "RG11Vm2", "RG12Vm1", "RG12Vm2", "RG13Vm1", "RG13Vm2", "RG14Vm1", "RG14Vm2", "RG15Vm1", "RG15Vm2", - "3", "RG16Vm1", "RG16Vm2", "RG17Vm1", "RG17Vm2", "RG18Vm1", "RG18Vm2", diff --git a/azure-mgmt-storage/src/main/java/com/microsoft/azure/management/storage/implementation/StorageAccountsImpl.java b/azure-mgmt-storage/src/main/java/com/microsoft/azure/management/storage/implementation/StorageAccountsImpl.java index dcaa33b5a81d9..42394d94ea0bb 100644 --- a/azure-mgmt-storage/src/main/java/com/microsoft/azure/management/storage/implementation/StorageAccountsImpl.java +++ b/azure-mgmt-storage/src/main/java/com/microsoft/azure/management/storage/implementation/StorageAccountsImpl.java @@ -11,9 +11,9 @@ import com.microsoft.azure.management.resources.fluentcore.arm.ResourceUtils; import com.microsoft.azure.management.resources.fluentcore.arm.collection.implementation.GroupableResourcesImpl; import com.microsoft.azure.management.storage.CheckNameAvailabilityResult; +import com.microsoft.azure.management.storage.SkuName; import com.microsoft.azure.management.storage.StorageAccount; import com.microsoft.azure.management.storage.StorageAccounts; -import com.microsoft.azure.management.storage.SkuName; import java.io.IOException; diff --git a/azure-mgmt-storage/src/main/java/com/microsoft/azure/management/storage/implementation/UsagesImpl.java b/azure-mgmt-storage/src/main/java/com/microsoft/azure/management/storage/implementation/UsagesImpl.java index 7497a4ea5ed4c..55ccef9406e6e 100644 --- a/azure-mgmt-storage/src/main/java/com/microsoft/azure/management/storage/implementation/UsagesImpl.java +++ b/azure-mgmt-storage/src/main/java/com/microsoft/azure/management/storage/implementation/UsagesImpl.java @@ -5,6 +5,7 @@ import com.microsoft.azure.management.resources.fluentcore.arm.collection.implementation.ReadableWrappersImpl; import com.microsoft.azure.management.storage.StorageUsage; import com.microsoft.azure.management.storage.Usages; + import java.io.IOException; /** diff --git a/azure-samples/src/main/java/com/microsoft/azure/management/keyvault/samples/ManageKeyVault.java b/azure-samples/src/main/java/com/microsoft/azure/management/keyvault/samples/ManageKeyVault.java new file mode 100644 index 0000000000000..39a2722b3ef3d --- /dev/null +++ b/azure-samples/src/main/java/com/microsoft/azure/management/keyvault/samples/ManageKeyVault.java @@ -0,0 +1,170 @@ +/** + * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + * + */ + +package com.microsoft.azure.management.keyvault.samples; + +import com.microsoft.azure.Azure; +import com.microsoft.azure.credentials.ApplicationTokenCredentials; +import com.microsoft.azure.management.keyvault.KeyPermissions; +import com.microsoft.azure.management.keyvault.SecretPermissions; +import com.microsoft.azure.management.keyvault.Vault; +import com.microsoft.azure.management.resources.fluentcore.arm.Region; +import com.microsoft.azure.management.resources.fluentcore.utils.ResourceNamer; +import com.microsoft.azure.management.samples.Utils; +import okhttp3.logging.HttpLoggingInterceptor; + +import java.io.File; + +/** + * Azure Key Vault sample for managing key vaults - + * - Create a key vault + * - Authorize an application + * - Update a key vault + * - alter configurations + * - change permissions + * - Create another key vault + * - List key vaults + * - Delete a key vault. + */ +public final class ManageKeyVault { + + /** + * Main entry point. + * @param args the parameters + */ + public static void main(String[] args) { + final String vaultName1 = ResourceNamer.randomResourceName("vault1", 20); + final String vaultName2 = ResourceNamer.randomResourceName("vault2", 20); + final String rgName = ResourceNamer.randomResourceName("rgNEMV", 24); + + try { + + //============================================================= + // Authenticate + + final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION")); + + Azure azure = Azure + .configure() + .withLogLevel(HttpLoggingInterceptor.Level.BODY) + .authenticate(credFile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azure.subscriptionId()); + try { + + + //============================================================ + // Create a key vault with empty access policy + + System.out.println("Creating a key vault..."); + + Vault vault1 = azure.vaults() + .define(vaultName1) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withEmptyAccessPolicy() + .create(); + + System.out.println("Created key vault"); + Utils.print(vault1); + + //============================================================ + // Authorize an application + + System.out.println("Authorizing the application associated with the current service principal..."); + + vault1 = vault1.update() + .defineAccessPolicy() + .forServicePrincipal(ApplicationTokenCredentials.fromFile(credFile).getClientId()) + .allowKeyAllPermissions() + .allowSecretPermissions(SecretPermissions.GET) + .allowSecretPermissions(SecretPermissions.LIST) + .attach() + .apply(); + + System.out.println("Updated key vault"); + Utils.print(vault1); + + //============================================================ + // Update a key vault + + System.out.println("Update a key vault to enable deployments and add permissions to the application..."); + + vault1 = vault1.update() + .withDeploymentEnabled() + .withTemplateDeploymentEnabled() + .updateAccessPolicy(vault1.accessPolicies().get(0).objectId()) + .allowSecretAllPermissions() + .parent() + .apply(); + + System.out.println("Updated key vault"); + // Print the network security group + Utils.print(vault1); + + + //============================================================ + // Create another key vault + + Vault vault2 = azure.vaults() + .define(vaultName2) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .defineAccessPolicy() + .forServicePrincipal(ApplicationTokenCredentials.fromFile(credFile).getClientId()) + .allowKeyPermissions(KeyPermissions.LIST) + .allowKeyPermissions(KeyPermissions.GET) + .allowKeyPermissions(KeyPermissions.DECRYPT) + .allowSecretPermissions(SecretPermissions.GET) + .attach() + .create(); + + System.out.println("Created key vault"); + // Print the network security group + Utils.print(vault2); + + + //============================================================ + // List key vaults + + System.out.println("Listing key vaults..."); + + for (Vault vault : azure.vaults().listByGroup(rgName)) { + Utils.print(vault); + } + + //============================================================ + // Delete key vaults + System.out.println("Deleting the key vaults"); + azure.vaults().delete(vault1.id()); + azure.vaults().delete(vault2.id()); + System.out.println("Deleted the key vaults"); + } catch (Exception e) { + System.err.println(e.getMessage()); + } finally { + try { + System.out.println("Deleting Resource Group: " + rgName); + azure.resourceGroups().delete(rgName); + System.out.println("Deleted Resource Group: " + rgName); + } catch (NullPointerException npe) { + System.out.println("Did not create any resources in Azure. No clean up is necessary"); + } catch (Exception g) { + g.printStackTrace(); + } + } + + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } + + private ManageKeyVault() { + } +} diff --git a/azure-samples/src/main/java/com/microsoft/azure/management/keyvault/samples/package-info.java b/azure-samples/src/main/java/com/microsoft/azure/management/keyvault/samples/package-info.java new file mode 100644 index 0000000000000..21b27292f58a2 --- /dev/null +++ b/azure-samples/src/main/java/com/microsoft/azure/management/keyvault/samples/package-info.java @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. + +/** + * This package contains the classes for key vault samples. + */ +package com.microsoft.azure.management.keyvault.samples; diff --git a/azure-samples/src/main/java/com/microsoft/azure/management/samples/Utils.java b/azure-samples/src/main/java/com/microsoft/azure/management/samples/Utils.java index b1881647ca9b3..191bfd0611ff1 100644 --- a/azure-samples/src/main/java/com/microsoft/azure/management/samples/Utils.java +++ b/azure-samples/src/main/java/com/microsoft/azure/management/samples/Utils.java @@ -7,17 +7,20 @@ package com.microsoft.azure.management.samples; +import com.google.common.base.Joiner; import com.microsoft.azure.CloudException; import com.microsoft.azure.management.compute.AvailabilitySet; -import com.microsoft.azure.management.compute.VirtualMachine; import com.microsoft.azure.management.compute.DataDisk; +import com.microsoft.azure.management.compute.VirtualMachine; import com.microsoft.azure.management.compute.VirtualMachineExtension; +import com.microsoft.azure.management.keyvault.AccessPolicy; +import com.microsoft.azure.management.keyvault.Vault; import com.microsoft.azure.management.network.Network; import com.microsoft.azure.management.network.NetworkInterface; import com.microsoft.azure.management.network.NetworkSecurityGroup; import com.microsoft.azure.management.network.NetworkSecurityRule; -import com.microsoft.azure.management.network.Subnet; import com.microsoft.azure.management.network.PublicIpAddress; +import com.microsoft.azure.management.network.Subnet; import com.microsoft.azure.management.storage.StorageAccount; import com.microsoft.azure.management.storage.StorageAccountKey; @@ -271,6 +274,26 @@ public static void print(PublicIpAddress resource) { .toString()); } + /** + * Print a key vault. + * @param vault the key vault resource + */ + public static void print(Vault vault) { + StringBuilder info = new StringBuilder().append("Key Vault: ").append(vault.id()) + .append("Name: ").append(vault.name()) + .append("\n\tResource group: ").append(vault.resourceGroupName()) + .append("\n\tRegion: ").append(vault.region()) + .append("\n\tSku: ").append(vault.sku().name()).append(" - ").append(vault.sku().family()) + .append("\n\tVault URI: ").append(vault.vaultUri()) + .append("\n\tAccess policies: "); + for (AccessPolicy accessPolicy: vault.accessPolicies()) { + info.append("\n\t\tIdentity:").append(accessPolicy.objectId()) + .append("\n\t\tKey permissions: ").append(Joiner.on(", ").join(accessPolicy.permissions().keys())) + .append("\n\t\tSecret permissions: ").append(Joiner.on(", ").join(accessPolicy.permissions().secrets())); + } + System.out.println(info.toString()); + } + /** * Print storage account. diff --git a/azure/pom.xml b/azure/pom.xml index 3695262170a56..43a027b79e7c0 100644 --- a/azure/pom.xml +++ b/azure/pom.xml @@ -76,6 +76,11 @@ azure-mgmt-compute 1.0.0-SNAPSHOT + + com.microsoft.azure + azure-mgmt-keyvault + 1.0.0-SNAPSHOT + junit junit diff --git a/azure/src/main/java/com/microsoft/azure/Azure.java b/azure/src/main/java/com/microsoft/azure/Azure.java index 6fa39a6061ac5..b926f4da8fd8c 100644 --- a/azure/src/main/java/com/microsoft/azure/Azure.java +++ b/azure/src/main/java/com/microsoft/azure/Azure.java @@ -7,10 +7,13 @@ package com.microsoft.azure; import com.microsoft.azure.credentials.ApplicationTokenCredentials; +import com.microsoft.azure.credentials.AzureTokenCredentials; import com.microsoft.azure.management.compute.AvailabilitySets; import com.microsoft.azure.management.compute.VirtualMachineImages; import com.microsoft.azure.management.compute.VirtualMachines; import com.microsoft.azure.management.compute.implementation.ComputeManager; +import com.microsoft.azure.management.keyvault.Vaults; +import com.microsoft.azure.management.keyvault.implementation.KeyVaultManager; import com.microsoft.azure.management.network.LoadBalancers; import com.microsoft.azure.management.network.NetworkInterfaces; import com.microsoft.azure.management.network.NetworkSecurityGroups; @@ -27,8 +30,8 @@ import com.microsoft.azure.management.resources.Tenants; import com.microsoft.azure.management.resources.fluentcore.arm.AzureConfigurable; import com.microsoft.azure.management.resources.fluentcore.arm.implementation.AzureConfigurableImpl; -import com.microsoft.azure.management.resources.implementation.ResourceManager; import com.microsoft.azure.management.resources.implementation.ResourceManagementClientImpl; +import com.microsoft.azure.management.resources.implementation.ResourceManager; import com.microsoft.azure.management.storage.StorageAccounts; import com.microsoft.azure.management.storage.Usages; import com.microsoft.azure.management.storage.implementation.StorageManager; @@ -45,19 +48,34 @@ public final class Azure { private final StorageManager storageManager; private final ComputeManager computeManager; private final NetworkManager networkManager; + private final KeyVaultManager keyVaultManager; private final String subscriptionId; /** * Authenticate to Azure using a credentials object. * * @param credentials the credentials object + * @param tenantId the tenantId in Active Directory * @return the authenticated Azure client */ - public static Authenticated authenticate(ServiceClientCredentials credentials) { + public static Authenticated authenticate(ServiceClientCredentials credentials, String tenantId) { return new AuthenticatedImpl( AzureEnvironment.AZURE.newRestClientBuilder() - .withCredentials(credentials) - .build()); + .withCredentials(credentials) + .build(), tenantId); + } + + /** + * Authenticate to Azure using an Azure credentials object. + * + * @param credentials the credentials object + * @return the authenticated Azure client + */ + public static Authenticated authenticate(AzureTokenCredentials credentials) { + return new AuthenticatedImpl( + AzureEnvironment.AZURE.newRestClientBuilder() + .withCredentials(credentials) + .build(), credentials.getDomain()); } /** @@ -80,20 +98,21 @@ public static Authenticated authenticate(File credentialsFile) throws IOExceptio ApplicationTokenCredentials credentials = ApplicationTokenCredentials.fromFile(credentialsFile); return new AuthenticatedImpl(AzureEnvironment.AZURE.newRestClientBuilder() .withCredentials(credentials) - .build()).withDefaultSubscription(credentials.defaultSubscriptionId()); + .build(), credentials.getDomain()).withDefaultSubscription(credentials.defaultSubscriptionId()); } /** * Authenticates API access using a {@link RestClient} instance. * @param restClient the {@link RestClient} configured with Azure authentication credentials + * @param tenantId the tenantId in Active Directory * @return authenticated Azure client */ - public static Authenticated authenticate(RestClient restClient) { - return new AuthenticatedImpl(restClient); + public static Authenticated authenticate(RestClient restClient, String tenantId) { + return new AuthenticatedImpl(restClient, tenantId); } - private static Authenticated authenticate(RestClient restClient, String subscriptionId) throws IOException { - return new AuthenticatedImpl(restClient).withDefaultSubscription(subscriptionId); + private static Authenticated authenticate(RestClient restClient, String tenantId, String subscriptionId) throws IOException { + return new AuthenticatedImpl(restClient, tenantId).withDefaultSubscription(subscriptionId); } /** @@ -107,13 +126,22 @@ public static Configurable configure() { * The interface allowing configurations to be made on the client. */ public interface Configurable extends AzureConfigurable { + /** + * Authenticates API access based on the provided credentials. + * + * @param credentials The credentials to authenticate API access with + * @param tenantId the tenantId in Active Directory + * @return the authenticated Azure client + */ + Authenticated authenticate(ServiceClientCredentials credentials, String tenantId); + /** * Authenticates API access based on the provided credentials. * * @param credentials The credentials to authenticate API access with * @return the authenticated Azure client */ - Authenticated authenticate(ServiceClientCredentials credentials); + Authenticated authenticate(AzureTokenCredentials credentials); /** * Authenticates API access using a properties file containing the required credentials. @@ -131,14 +159,19 @@ public interface Configurable extends AzureConfigurable { */ private static final class ConfigurableImpl extends AzureConfigurableImpl implements Configurable { @Override - public Authenticated authenticate(ServiceClientCredentials credentials) { - return Azure.authenticate(buildRestClient(credentials)); + public Authenticated authenticate(ServiceClientCredentials credentials, String tenantId) { + return Azure.authenticate(buildRestClient(credentials), tenantId); + } + + @Override + public Authenticated authenticate(AzureTokenCredentials credentials) { + return Azure.authenticate(buildRestClient(credentials), credentials.getDomain()); } @Override public Authenticated authenticate(File credentialsFile) throws IOException { ApplicationTokenCredentials credentials = ApplicationTokenCredentials.fromFile(credentialsFile); - return Azure.authenticate(buildRestClient(credentials), credentials.defaultSubscriptionId()); + return Azure.authenticate(buildRestClient(credentials), credentials.getDomain(), credentials.defaultSubscriptionId()); } } @@ -194,10 +227,12 @@ private static final class AuthenticatedImpl implements Authenticated { private final RestClient restClient; private final ResourceManager.Authenticated resourceManagerAuthenticated; private String defaultSubscription; + private String tenantId; - private AuthenticatedImpl(RestClient restClient) { + private AuthenticatedImpl(RestClient restClient, String tenantId) { this.resourceManagerAuthenticated = ResourceManager.authenticate(restClient); this.restClient = restClient; + this.tenantId = tenantId; } private AuthenticatedImpl withDefaultSubscription(String subscriptionId) throws IOException { @@ -217,7 +252,7 @@ public Tenants tenants() { @Override public Azure withSubscription(String subscriptionId) { - return new Azure(restClient, subscriptionId); + return new Azure(restClient, subscriptionId, tenantId); } @Override @@ -235,13 +270,14 @@ public Azure withDefaultSubscription() throws CloudException, IOException { } } - private Azure(RestClient restClient, String subscriptionId) { + private Azure(RestClient restClient, String subscriptionId, String tenantId) { ResourceManagementClientImpl resourceManagementClient = new ResourceManagementClientImpl(restClient); resourceManagementClient.withSubscriptionId(subscriptionId); this.resourceManager = ResourceManager.authenticate(restClient).withSubscription(subscriptionId); this.storageManager = StorageManager.authenticate(restClient, subscriptionId); this.computeManager = ComputeManager.authenticate(restClient, subscriptionId); this.networkManager = NetworkManager.authenticate(restClient, subscriptionId); + this.keyVaultManager = KeyVaultManager.authenticate(restClient, tenantId, subscriptionId); this.subscriptionId = subscriptionId; } @@ -356,4 +392,11 @@ public PublicIpAddresses publicIpAddresses() { public NetworkInterfaces networkInterfaces() { return this.networkManager.networkInterfaces(); } + + /** + * @return entry point to managing key vaults + */ + public Vaults vaults() { + return this.keyVaultManager.vaults(); + } } diff --git a/azure/src/test/java/com/microsoft/azure/AzureTests.java b/azure/src/test/java/com/microsoft/azure/AzureTests.java index 44ea550030117..03fa1e8b36d2e 100644 --- a/azure/src/test/java/com/microsoft/azure/AzureTests.java +++ b/azure/src/test/java/com/microsoft/azure/AzureTests.java @@ -6,9 +6,9 @@ package com.microsoft.azure; import com.microsoft.azure.credentials.ApplicationTokenCredentials; +import com.microsoft.azure.management.compute.VirtualMachineImage; import com.microsoft.azure.management.compute.VirtualMachineOffer; import com.microsoft.azure.management.compute.VirtualMachinePublisher; -import com.microsoft.azure.management.compute.VirtualMachineImage; import com.microsoft.azure.management.compute.VirtualMachineSku; import com.microsoft.azure.management.resources.Deployment; import com.microsoft.azure.management.resources.DeploymentMode; @@ -17,7 +17,6 @@ import com.microsoft.azure.management.resources.fluentcore.arm.Region; import com.microsoft.azure.management.storage.SkuName; import com.microsoft.azure.management.storage.StorageAccount; -import com.microsoft.rest.credentials.ServiceClientCredentials; import okhttp3.logging.HttpLoggingInterceptor.Level; import org.junit.Assert; import org.junit.Before; @@ -28,7 +27,7 @@ import java.util.List; public class AzureTests { - private static final ServiceClientCredentials CREDENTIALS = new ApplicationTokenCredentials( + private static final ApplicationTokenCredentials CREDENTIALS = new ApplicationTokenCredentials( System.getenv("client-id"), System.getenv("domain"), System.getenv("secret"), @@ -41,23 +40,35 @@ public static void main(String[] args) throws IOException, CloudException { final File credFile = new File("my.azureauth"); Azure azure = Azure.authenticate(credFile).withDefaultSubscription(); - System.out.println(String.valueOf(azure.resourceGroups().list().size())); + try { + System.out.println(String.valueOf(azure.resourceGroups().list().size())); + } catch (com.microsoft.rest.RestException e) { + e.printStackTrace(); + } Azure.configure().withLogLevel(Level.BASIC).authenticate(credFile); System.out.println("Selected subscription: " + azure.subscriptionId()); - System.out.println(String.valueOf(azure.resourceGroups().list().size())); + try { + System.out.println(String.valueOf(azure.resourceGroups().list().size())); + } catch (com.microsoft.rest.RestException e) { + e.printStackTrace(); + } final File authFileNoSubscription = new File("nosub.azureauth"); azure = Azure.authenticate(authFileNoSubscription).withDefaultSubscription(); System.out.println("Selected subscription: " + azure.subscriptionId()); - System.out.println(String.valueOf(azure.resourceGroups().list().size())); + try { + System.out.println(String.valueOf(azure.resourceGroups().list().size())); + } catch (com.microsoft.rest.RestException e) { + e.printStackTrace(); + } } @Before public void setup() throws Exception { // Authenticate based on credentials instance Azure.Authenticated azureAuthed = Azure.configure() - .withLogLevel(Level.BODY) + .withLogLevel(Level.NONE) .withUserAgent("AzureTests") .authenticate(CREDENTIALS); @@ -125,11 +136,19 @@ public void setup() throws Exception { Assert.assertTrue(publishers.size() > 0); for (VirtualMachinePublisher p : publishers) { System.out.println(String.format("Publisher name: %s, region: %s", p.name(), p.region())); - for (VirtualMachineOffer o : p.offers().list()) { - System.out.println(String.format("\tOffer name: %s", o.name())); - for (VirtualMachineSku s : o.skus().list()) { - System.out.println(String.format("\t\tSku name: %s", s.name())); + try { + for (VirtualMachineOffer o : p.offers().list()) { + System.out.println(String.format("\tOffer name: %s", o.name())); + try { + for (VirtualMachineSku s : o.skus().list()) { + System.out.println(String.format("\t\tSku name: %s", s.name())); + } + } catch (com.microsoft.rest.RestException e) { + e.printStackTrace(); + } } + } catch (com.microsoft.rest.RestException e) { + e.printStackTrace(); } } List images = azure.virtualMachineImages().listByRegion(Region.US_WEST); diff --git a/gulpfile.js b/gulpfile.js index 387f37e2594ab..c24bfbba123dd 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -11,13 +11,13 @@ var mappings = { 'package': 'com.microsoft.azure.management.compute', 'args': '-FT 1' }, - 'graph': { + 'graphrbac': { 'dir': 'azure-mgmt-graph-rbac', 'source': 'arm-graphrbac/1.6/swagger/graphrbac.json', 'package': 'com.microsoft.azure.management.graphrbac', 'args': '-FT 1' }, - 'keyvault': { + 'arm-keyvault': { 'dir': 'azure-mgmt-keyvault', 'source': 'arm-keyvault/2015-06-01/swagger/keyvault.json', 'package': 'com.microsoft.azure.management.keyvault', diff --git a/runtimes/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/ApplicationTokenCredentials.java b/runtimes/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/ApplicationTokenCredentials.java index abe3a65c9bdd8..48b4a061018e8 100644 --- a/runtimes/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/ApplicationTokenCredentials.java +++ b/runtimes/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/ApplicationTokenCredentials.java @@ -12,10 +12,14 @@ import com.microsoft.aad.adal4j.ClientCredential; import com.microsoft.azure.AzureEnvironment; import com.microsoft.rest.credentials.TokenCredentials; +import okhttp3.OkHttpClient; import java.io.File; import java.io.FileInputStream; import java.io.IOException; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -23,19 +27,17 @@ /** * Token based credentials for use with a REST Service Client. */ -public class ApplicationTokenCredentials extends TokenCredentials { - /** The endpoint of the target resource. */ - private String resourceEndpoint; +public class ApplicationTokenCredentials extends TokenCredentials implements AzureTokenCredentials { + /** A mapping from resource endpoint to its cached access token. */ + private Map tokens; + /** The Azure environment to authenticate with. */ + private AzureEnvironment environment; /** The active directory application client id. */ private String clientId; /** The tenant or domain the containing the application. */ private String domain; /** The authentication secret for the application. */ private String secret; - /** The Azure environment to authenticate with. */ - private AzureEnvironment environment; - /** The current authentication result. */ - private AuthenticationResult authenticationResult; /** The default subscription to use, if any. */ private String defaultSubscription; @@ -50,38 +52,11 @@ public class ApplicationTokenCredentials extends TokenCredentials { */ public ApplicationTokenCredentials(String clientId, String domain, String secret, AzureEnvironment environment) { super(null, null); // defer token acquisition + this.environment = environment; this.clientId = clientId; this.domain = domain; this.secret = secret; - if (environment == null) { - this.environment = AzureEnvironment.AZURE; - } else { - this.environment = environment; - } - this.resourceEndpoint = this.environment.getTokenAudience(); - } - - /** - * Initializes a new instance of the UserTokenCredentials. - * - * @param clientId the active directory application client id. - * @param domain the domain or tenant id containing this application. - * @param secret the authentication secret for the application. - * @param resourceEndpoint the endpoint of the target resource. - * @param environment the Azure environment to authenticate with. - * If null is provided, AzureEnvironment.AZURE will be used. - */ - public ApplicationTokenCredentials(String clientId, String domain, String secret, String resourceEndpoint, AzureEnvironment environment) { - super(null, null); // defer token acquisition - this.clientId = clientId; - this.domain = domain; - this.secret = secret; - this.resourceEndpoint = resourceEndpoint; - if (environment == null) { - this.environment = AzureEnvironment.AZURE; - } else { - this.environment = environment; - } + this.tokens = new HashMap<>(); } /** @@ -155,7 +130,7 @@ public static ApplicationTokenCredentials fromFile(File credentialsFile) throws Properties authSettings = new Properties(); authSettings.put(CredentialSettings.AUTH_URL.toString(), AzureEnvironment.AZURE.getAuthenticationEndpoint()); authSettings.put(CredentialSettings.BASE_URL.toString(), AzureEnvironment.AZURE.getBaseUrl()); - authSettings.put(CredentialSettings.MANAGEMENT_URI.toString(), AzureEnvironment.AZURE.getTokenAudience()); + authSettings.put(CredentialSettings.MANAGEMENT_URI.toString(), AzureEnvironment.AZURE.getManagementEndpoint()); // Load the credentials from the file FileInputStream credentialsFileStream = new FileInputStream(credentialsFile); @@ -177,8 +152,8 @@ public static ApplicationTokenCredentials fromFile(File credentialsFile) throws new AzureEnvironment( authUrl, mgmtUri, - true, - baseUrl) + baseUrl, + "https://graph.windows.net/") // TODO: cred file should contain GRAPH endpoint ).withDefaultSubscriptionId(defaultSubscriptionId); } @@ -196,6 +171,7 @@ public String getClientId() { * * @return the tenant or domain the containing the application. */ + @Override public String getDomain() { return domain; } @@ -209,42 +185,40 @@ public String getSecret() { return secret; } - /** - * Gets the Azure environment to authenticate with. - * - * @return the Azure environment to authenticate with. - */ - public AzureEnvironment getEnvironment() { - return environment; - } - @Override - public String getToken() throws IOException { - if (authenticationResult == null - || authenticationResult.getAccessToken() == null) { - acquireAccessToken(); + public String getToken(String resource) throws IOException { + AuthenticationResult authenticationResult = tokens.get(resource); + if (authenticationResult == null || authenticationResult.getExpiresOnDate().before(new Date())) { + authenticationResult = acquireAccessToken(resource); } return authenticationResult.getAccessToken(); } @Override - public void refreshToken() throws IOException { - acquireAccessToken(); + public AzureEnvironment getEnvironment() { + return this.environment; } - private void acquireAccessToken() throws IOException { + private AuthenticationResult acquireAccessToken(String resource) throws IOException { String authorityUrl = this.getEnvironment().getAuthenticationEndpoint() + this.getDomain(); ExecutorService executor = Executors.newSingleThreadExecutor(); AuthenticationContext context = new AuthenticationContext(authorityUrl, this.getEnvironment().isValidateAuthority(), executor); try { - authenticationResult = context.acquireToken( - this.resourceEndpoint, + AuthenticationResult result = context.acquireToken( + resource, new ClientCredential(this.getClientId(), this.getSecret()), null).get(); + tokens.put(resource, result); + return result; } catch (Exception e) { throw new IOException(e.getMessage(), e); } finally { executor.shutdown(); } } + + @Override + public void applyCredentialsFilter(OkHttpClient.Builder clientBuilder) { + clientBuilder.interceptors().add(new AzureTokenCredentialsInterceptor(this)); + } } diff --git a/runtimes/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/UserTokenCredentials.java b/runtimes/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/UserTokenCredentials.java index c37479771a9b9..9da95726b11a2 100644 --- a/runtimes/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/UserTokenCredentials.java +++ b/runtimes/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/UserTokenCredentials.java @@ -11,18 +11,21 @@ import com.microsoft.aad.adal4j.AuthenticationResult; import com.microsoft.azure.AzureEnvironment; import com.microsoft.rest.credentials.TokenCredentials; +import okhttp3.OkHttpClient; import java.io.IOException; import java.util.Date; +import java.util.HashMap; +import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Token based credentials for use with a REST Service Client. */ -public class UserTokenCredentials extends TokenCredentials { - /** The endpoint of the target resource. */ - private String resourceEndpoint; +public class UserTokenCredentials extends TokenCredentials implements AzureTokenCredentials { + /** A mapping from resource endpoint to its cached access token. */ + private Map tokens; /** The Active Directory application client id. */ private String clientId; /** The domain or tenant id containing this application. */ @@ -31,12 +34,8 @@ public class UserTokenCredentials extends TokenCredentials { private String username; /** The password for the Organization Id account. */ private String password; - /** The Uri where the user will be redirected after authenticating with AD. */ - private String clientRedirectUri; /** The Azure environment to authenticate with. */ private AzureEnvironment environment; - /** The current authentication result. */ - private AuthenticationResult authenticationResult; /** * Initializes a new instance of the UserTokenCredentials. @@ -45,50 +44,17 @@ public class UserTokenCredentials extends TokenCredentials { * @param domain the domain or tenant id containing this application. * @param username the user name for the Organization Id account. * @param password the password for the Organization Id account. - * @param clientRedirectUri the Uri where the user will be redirected after authenticating with AD. * @param environment the Azure environment to authenticate with. * If null is provided, AzureEnvironment.AZURE will be used. */ - public UserTokenCredentials(String clientId, String domain, String username, String password, String clientRedirectUri, AzureEnvironment environment) { + public UserTokenCredentials(String clientId, String domain, String username, String password, AzureEnvironment environment) { super(null, null); // defer token acquisition this.clientId = clientId; this.domain = domain; this.username = username; this.password = password; - this.clientRedirectUri = clientRedirectUri; - if (environment == null) { - this.environment = AzureEnvironment.AZURE; - } else { - this.environment = environment; - } - this.resourceEndpoint = this.environment.getTokenAudience(); - } - - /** - * Initializes a new instance of the UserTokenCredentials. - * - * @param clientId the active directory application client id. - * @param domain the domain or tenant id containing this application. - * @param username the user name for the Organization Id account. - * @param password the password for the Organization Id account. - * @param clientRedirectUri the Uri where the user will be redirected after authenticating with AD. - * @param resourceEndpoint the endpoint of the target resource. - * @param environment the Azure environment to authenticate with. - * If null is provided, AzureEnvironment.AZURE will be used. - */ - public UserTokenCredentials(String clientId, String domain, String username, String password, String clientRedirectUri, String resourceEndpoint, AzureEnvironment environment) { - super(null, null); // defer token acquisition - this.clientId = clientId; - this.domain = domain; - this.username = username; - this.password = password; - this.clientRedirectUri = clientRedirectUri; - this.resourceEndpoint = resourceEndpoint; - if (environment == null) { - this.environment = AzureEnvironment.AZURE; - } else { - this.environment = environment; - } + this.environment = environment; + this.tokens = new HashMap<>(); } /** @@ -105,6 +71,7 @@ public String getClientId() { * * @return the tenant or domain the containing the application. */ + @Override public String getDomain() { return domain; } @@ -127,13 +94,13 @@ public String getPassword() { return password; } - /** - * Gets the Uri where the user will be redirected after authenticating with AD. - * - * @return the redirecting Uri. - */ - public String getClientRedirectUri() { - return clientRedirectUri; + @Override + public String getToken(String resource) throws IOException { + AuthenticationResult authenticationResult = tokens.get(resource); + if (authenticationResult == null || authenticationResult.getExpiresOnDate().before(new Date())) { + authenticationResult = acquireAccessToken(resource); + } + return authenticationResult.getAccessToken(); } /** @@ -145,50 +112,47 @@ public AzureEnvironment getEnvironment() { return environment; } - @Override - public String getToken() throws IOException { - if (authenticationResult != null - && authenticationResult.getExpiresOnDate().before(new Date())) { - acquireAccessTokenFromRefreshToken(); - } else { - acquireAccessToken(); - } - return authenticationResult.getAccessToken(); - } - - @Override - public void refreshToken() throws IOException { - acquireAccessToken(); - } - - private void acquireAccessToken() throws IOException { + private AuthenticationResult acquireAccessToken(String resource) throws IOException { String authorityUrl = this.getEnvironment().getAuthenticationEndpoint() + this.getDomain(); - AuthenticationContext context = new AuthenticationContext(authorityUrl, this.getEnvironment().isValidateAuthority(), Executors.newSingleThreadExecutor()); + ExecutorService executor = Executors.newSingleThreadExecutor(); + AuthenticationContext context = new AuthenticationContext(authorityUrl, this.getEnvironment().isValidateAuthority(), executor); try { - authenticationResult = context.acquireToken( - this.resourceEndpoint, + AuthenticationResult result = context.acquireToken( + resource, this.getClientId(), this.getUsername(), this.getPassword(), null).get(); + tokens.put(resource, result); + return result; } catch (Exception e) { throw new IOException(e.getMessage(), e); + } finally { + executor.shutdown(); } } - private void acquireAccessTokenFromRefreshToken() throws IOException { + // Refresh tokens are currently not used since we don't know if the refresh token has expired + private AuthenticationResult acquireAccessTokenFromRefreshToken(String resource) throws IOException { String authorityUrl = this.getEnvironment().getAuthenticationEndpoint() + this.getDomain(); ExecutorService executor = Executors.newSingleThreadExecutor(); AuthenticationContext context = new AuthenticationContext(authorityUrl, this.getEnvironment().isValidateAuthority(), executor); try { - authenticationResult = context.acquireTokenByRefreshToken( - authenticationResult.getRefreshToken(), + AuthenticationResult result = context.acquireTokenByRefreshToken( + tokens.get(resource).getRefreshToken(), this.getClientId(), null, null).get(); + tokens.put(resource, result); + return result; } catch (Exception e) { throw new IOException(e.getMessage(), e); } finally { executor.shutdown(); } } + + @Override + public void applyCredentialsFilter(OkHttpClient.Builder clientBuilder) { + clientBuilder.interceptors().add(new AzureTokenCredentialsInterceptor(this)); + } } diff --git a/runtimes/azure-client-authentication/src/test/java/com/microsoft/azure/credentials/UserTokenCredentialsTests.java b/runtimes/azure-client-authentication/src/test/java/com/microsoft/azure/credentials/UserTokenCredentialsTests.java index 7905ba7e7b21e..caab41dd8e7c2 100644 --- a/runtimes/azure-client-authentication/src/test/java/com/microsoft/azure/credentials/UserTokenCredentialsTests.java +++ b/runtimes/azure-client-authentication/src/test/java/com/microsoft/azure/credentials/UserTokenCredentialsTests.java @@ -21,7 +21,6 @@ public class UserTokenCredentialsTests { "domain", "username", "password", - "redirect", AzureEnvironment.AZURE ); @@ -36,8 +35,8 @@ public void testAcquireToken() throws Exception { public static class MockUserTokenCredentials extends UserTokenCredentials { private AuthenticationResult authenticationResult; - public MockUserTokenCredentials(String clientId, String domain, String username, String password, String clientRedirectUri, AzureEnvironment environment) { - super(clientId, domain, username, password, clientRedirectUri, environment); + public MockUserTokenCredentials(String clientId, String domain, String username, String password, AzureEnvironment environment) { + super(clientId, domain, username, password, environment); } @Override diff --git a/runtimes/azure-client-runtime/src/main/java/com/microsoft/azure/AzureEnvironment.java b/runtimes/azure-client-runtime/src/main/java/com/microsoft/azure/AzureEnvironment.java index 897e29b622c09..421bc2869d0f4 100644 --- a/runtimes/azure-client-runtime/src/main/java/com/microsoft/azure/AzureEnvironment.java +++ b/runtimes/azure-client-runtime/src/main/java/com/microsoft/azure/AzureEnvironment.java @@ -14,17 +14,22 @@ public final class AzureEnvironment { /** * Base URL for calls to Azure management API. */ - private final String baseURL; + private final String resourceManagerEndpoint; /** - * ActiveDirectory Endpoint for the Azure Environment. + * ActiveDirectory Endpoint for the authentications. */ private String authenticationEndpoint; /** - * Token audience for an endpoint. + * Base URL for calls to service management and authentications to Active Directory. */ - private String tokenAudience; + private String managementEndpoint; + + /** + * Base URL for calls to graph API. + */ + private String graphEndpoint; /** * Determines whether the authentication endpoint should @@ -36,20 +41,20 @@ public final class AzureEnvironment { * Initializes an instance of AzureEnvironment class. * * @param authenticationEndpoint ActiveDirectory Endpoint for the Azure Environment. - * @param tokenAudience token audience for an endpoint. - * @param validateAuthority whether the authentication endpoint should - * be validated with Azure AD. - * @param baseUrl the base URL for the current environment. + * @param managementEndpoint token audience for an endpoint. + * @param resourceManagerEndpoint the base URL for the current environment. + * @param graphEndpoint the base URL for graph API. */ public AzureEnvironment( String authenticationEndpoint, - String tokenAudience, - boolean validateAuthority, - String baseUrl) { + String managementEndpoint, + String resourceManagerEndpoint, + String graphEndpoint) { this.authenticationEndpoint = authenticationEndpoint; - this.tokenAudience = tokenAudience; - this.validateAuthority = validateAuthority; - this.baseURL = baseUrl; + this.managementEndpoint = managementEndpoint; + this.resourceManagerEndpoint = resourceManagerEndpoint; + this.graphEndpoint = graphEndpoint; + this.validateAuthority = false; } /** @@ -58,8 +63,8 @@ public AzureEnvironment( public static final AzureEnvironment AZURE = new AzureEnvironment( "https://login.microsoftonline.com/", "https://management.core.windows.net/", - true, - "https://management.azure.com/"); + "https://management.azure.com/", + "https://graph.windows.net/"); /** * Provides the settings for authentication with Azure China. @@ -67,8 +72,8 @@ public AzureEnvironment( public static final AzureEnvironment AZURE_CHINA = new AzureEnvironment( "https://login.chinacloudapi.cn/", "https://management.core.chinacloudapi.cn/", - true, - "https://management.chinacloudapi.cn/"); + "https://management.chinacloudapi.cn/", + "https://graph.chinacloudapi.cn/"); /** * Provides the settings for authentication with Azure US Government. @@ -76,8 +81,8 @@ public AzureEnvironment( public static final AzureEnvironment AZURE_US_GOVERNMENT = new AzureEnvironment( "https://login.microsoftonline.com/", "https://management.core.usgovcloudapi.net/", - true, - "https://management.usgovcloudapi.net/"); + "https://management.usgovcloudapi.net/", + "https://graph.windows.net/"); /** * Provides the settings for authentication with Azure Germany. @@ -85,8 +90,8 @@ public AzureEnvironment( public static final AzureEnvironment AZURE_GERMANY = new AzureEnvironment( "https://login.microsoftonline.de/", "https://management.core.cloudapi.de/", - true, - "https://management.microsoftazure.de/"); + "https://management.microsoftazure.de/", + "https://graph.cloudapi.de/"); /** * Gets the base URL of the management service. @@ -94,12 +99,10 @@ public AzureEnvironment( * @return the Base URL for the management service. */ public String getBaseUrl() { - return this.baseURL; + return this.resourceManagerEndpoint; } /** - * Gets a builder for {@link RestClient}. - * * @return a builder for the rest client. */ public RestClient.Builder.Buildable newRestClientBuilder() { @@ -109,8 +112,6 @@ public RestClient.Builder.Buildable newRestClientBuilder() { } /** - * Gets the ActiveDirectory Endpoint for the Azure Environment. - * * @return the ActiveDirectory Endpoint for the Azure Environment. */ public String getAuthenticationEndpoint() { @@ -118,12 +119,17 @@ public String getAuthenticationEndpoint() { } /** - * Gets the token audience for an endpoint. - * - * @return the token audience for an endpoint. + * @return the Azure Resource Manager endpoint for the environment. + */ + public String getManagementEndpoint() { + return managementEndpoint; + } + + /** + * @return the Graph API endpoint. */ - public String getTokenAudience() { - return tokenAudience; + public String getGraphEndpoint() { + return graphEndpoint; } /** @@ -136,4 +142,15 @@ public String getTokenAudience() { public boolean isValidateAuthority() { return validateAuthority; } + + /** + * Sets whether the authentication endpoint should + * be validated with Azure AD. + * + * @param validateAuthority true if the authentication endpoint should + * be validated with Azure AD, false otherwise. + */ + public void setValidateAuthority(boolean validateAuthority) { + this.validateAuthority = validateAuthority; + } } diff --git a/runtimes/azure-client-runtime/src/main/java/com/microsoft/azure/PagedList.java b/runtimes/azure-client-runtime/src/main/java/com/microsoft/azure/PagedList.java index 8db10337d9898..46c02402ed531 100644 --- a/runtimes/azure-client-runtime/src/main/java/com/microsoft/azure/PagedList.java +++ b/runtimes/azure-client-runtime/src/main/java/com/microsoft/azure/PagedList.java @@ -17,8 +17,6 @@ import java.util.ListIterator; import java.util.NoSuchElementException; -import javax.xml.bind.DataBindingException; - /** * Defines a list response from a paging operation. The pages are * lazy initialized when an instance of this class is iterated. @@ -28,10 +26,10 @@ public abstract class PagedList implements List { /** The actual items in the list. */ private List items; - /** Stores the link to get the next page of items. */ - private String nextPageLink; /** Stores the latest page fetched. */ private Page currentPage; + /** Cached page right after the current one. */ + private Page cachedPage; /** * Creates an instance of Pagedlist. @@ -48,11 +46,26 @@ public PagedList() { public PagedList(Page page) { this(); List retrievedItems = page.getItems(); - if (retrievedItems != null && retrievedItems.size() != 0) { + if (retrievedItems != null) { items.addAll(retrievedItems); } - nextPageLink = page.getNextPageLink(); currentPage = page; + cachePage(page.getNextPageLink()); + } + + private void cachePage(String nextPageLink) { + try { + while (nextPageLink != null) { + cachedPage = nextPage(nextPageLink); + nextPageLink = cachedPage.getNextPageLink(); + if (hasNextPage()) { + // a legit, non-empty page has been fetched, otherwise keep fetching + break; + } + } + } catch (IOException ex) { + throw new RuntimeException(ex); + } } /** @@ -71,7 +84,7 @@ public PagedList(Page page) { * @return true if there are more pages to load. False otherwise. */ public boolean hasNextPage() { - return this.nextPageLink != null; + return this.cachedPage != null && this.cachedPage.getItems() != null && !this.cachedPage.getItems().isEmpty(); } /** @@ -79,14 +92,10 @@ public boolean hasNextPage() { * The exceptions are wrapped into Java Runtime exceptions. */ public void loadNextPage() { - try { - Page nextPage = nextPage(this.nextPageLink); - this.nextPageLink = nextPage.getNextPageLink(); - this.items.addAll(nextPage.getItems()); - this.currentPage = nextPage; - } catch (IOException e) { - throw new DataBindingException(e.getMessage(), e); - } + this.currentPage = cachedPage; + cachedPage = null; + this.items.addAll(currentPage.getItems()); + cachePage(currentPage.getNextPageLink()); } /** @@ -108,12 +117,17 @@ public Page currentPage() { } /** - * Gets the next page's link. + * Sets the current page. * - * @return the next page link. + * @param currentPage the current page. */ - public String nextPageLink() { - return nextPageLink; + protected void setCurrentPage(Page currentPage) { + this.currentPage = currentPage; + List retrievedItems = currentPage.getItems(); + if (retrievedItems != null) { + items.addAll(retrievedItems); + } + cachePage(currentPage.getNextPageLink()); } /** @@ -141,17 +155,14 @@ public boolean hasNext() { public E next() { if (!itemsListItr.hasNext()) { if (!hasNextPage()) { - throw new NoSuchElementException(); + throw new NoSuchElementException(); } else { int size = items.size(); loadNextPage(); itemsListItr = items.listIterator(size); } } - if (itemsListItr.hasNext()) { - return itemsListItr.next(); - } - return null; + return itemsListItr.next(); } @Override diff --git a/runtimes/azure-client-runtime/src/main/java/com/microsoft/azure/credentials/AzureTokenCredentials.java b/runtimes/azure-client-runtime/src/main/java/com/microsoft/azure/credentials/AzureTokenCredentials.java new file mode 100644 index 0000000000000..d91962e798554 --- /dev/null +++ b/runtimes/azure-client-runtime/src/main/java/com/microsoft/azure/credentials/AzureTokenCredentials.java @@ -0,0 +1,40 @@ +/** + * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + * + */ + +package com.microsoft.azure.credentials; + +import com.microsoft.azure.AzureEnvironment; +import com.microsoft.rest.credentials.ServiceClientCredentials; + +import java.io.IOException; + +/** + * AzureTokenCredentials represents a credentials object with access to Azure + * Resource management. + */ +public interface AzureTokenCredentials extends ServiceClientCredentials { + /** + * Override this method to provide the mechanism to get a token. + * + * @param resource the resource the access token is for + * @return the token to access the resource + * @throws IOException exceptions from IO + */ + String getToken(String resource) throws IOException; + + /** + * Override this method to provide the domain or tenant ID the token is valid in. + * + * @return the domain or tenant ID string + */ + String getDomain(); + + /** + * @return the environment details the credential has access to. + */ + AzureEnvironment getEnvironment(); +} diff --git a/runtimes/azure-client-runtime/src/main/java/com/microsoft/azure/credentials/AzureTokenCredentialsInterceptor.java b/runtimes/azure-client-runtime/src/main/java/com/microsoft/azure/credentials/AzureTokenCredentialsInterceptor.java new file mode 100644 index 0000000000000..33f8b7c7a16d0 --- /dev/null +++ b/runtimes/azure-client-runtime/src/main/java/com/microsoft/azure/credentials/AzureTokenCredentialsInterceptor.java @@ -0,0 +1,59 @@ +/** + * + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + * + */ + +package com.microsoft.azure.credentials; + +import okhttp3.Interceptor; +import okhttp3.Request; +import okhttp3.Response; + +import java.io.IOException; + +/** + * Token credentials filter for placing a token credential into request headers. + */ +public class AzureTokenCredentialsInterceptor implements Interceptor { + /** + * The credentials instance to apply to the HTTP client pipeline. + */ + private AzureTokenCredentials credentials; + + /** + * Initialize a TokenCredentialsFilter class with a + * TokenCredentials credential. + * + * @param credentials a TokenCredentials instance + */ + public AzureTokenCredentialsInterceptor(AzureTokenCredentials credentials) { + this.credentials = credentials; + } + + @Override + public Response intercept(Chain chain) throws IOException { + String resource = credentials.getEnvironment().getManagementEndpoint(); + // Use graph resource if the host if graph endpoint + if (credentials.getEnvironment().getGraphEndpoint().contains(chain.request().url().host())) { + resource = credentials.getEnvironment().getGraphEndpoint(); + } + Request newRequest = chain.request().newBuilder() + .header("Authorization", "Bearer " + credentials.getToken(resource)) + .build(); + return chain.proceed(newRequest); + } + + private Response sendRequestWithToken(Chain chain) throws IOException { + String resource = credentials.getEnvironment().getManagementEndpoint(); + // Use graph resource if the host if graph endpoint + if (chain.request().url().host().equals(credentials.getEnvironment().getGraphEndpoint())) { + resource = credentials.getEnvironment().getGraphEndpoint(); + } + Request newRequest = chain.request().newBuilder() + .header("Authorization", "Bearer " + credentials.getToken(resource)) + .build(); + return chain.proceed(newRequest); + } +} diff --git a/runtimes/azure-client-runtime/src/main/java/com/microsoft/azure/credentials/package-info.java b/runtimes/azure-client-runtime/src/main/java/com/microsoft/azure/credentials/package-info.java new file mode 100644 index 0000000000000..22ff7d1a5d6ed --- /dev/null +++ b/runtimes/azure-client-runtime/src/main/java/com/microsoft/azure/credentials/package-info.java @@ -0,0 +1,6 @@ +/** + * The package contains the credentials classes required for AutoRest generated + * Azure clients to compile and function. To learn more about AutoRest generator, + * see https://github.com/azure/autorest. + */ +package com.microsoft.azure.credentials; \ No newline at end of file diff --git a/runtimes/azure-client-runtime/src/test/java/com/microsoft/azure/PagedListTests.java b/runtimes/azure-client-runtime/src/test/java/com/microsoft/azure/PagedListTests.java index b82c8d0628787..04567aa1c6730 100644 --- a/runtimes/azure-client-runtime/src/test/java/com/microsoft/azure/PagedListTests.java +++ b/runtimes/azure-client-runtime/src/test/java/com/microsoft/azure/PagedListTests.java @@ -21,11 +21,11 @@ public class PagedListTests { @Before public void setupList() { - list = new PagedList(new TestPage(0, 20)) { + list = new PagedList(new TestPage(0, 21)) { @Override public Page nextPage(String nextPageLink) throws CloudException, IOException { int pageNum = Integer.parseInt(nextPageLink); - return new TestPage(pageNum, 20); + return new TestPage(pageNum, 21); } }; } @@ -119,9 +119,13 @@ public String getNextPageLink() { @Override public List getItems() { - List items = new ArrayList<>(); - items.add(page); - return items; + if (page + 1 != max) { + List items = new ArrayList<>(); + items.add(page); + return items; + } else { + return new ArrayList<>(); + } } } } diff --git a/runtimes/client-runtime/src/main/java/com/microsoft/rest/ServiceResponseBuilder.java b/runtimes/client-runtime/src/main/java/com/microsoft/rest/ServiceResponseBuilder.java index 3ad57cb938f40..34d11a14c17a7 100644 --- a/runtimes/client-runtime/src/main/java/com/microsoft/rest/ServiceResponseBuilder.java +++ b/runtimes/client-runtime/src/main/java/com/microsoft/rest/ServiceResponseBuilder.java @@ -9,6 +9,8 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.microsoft.rest.serializer.JacksonMapperAdapter; +import okhttp3.ResponseBody; +import retrofit2.Response; import java.io.IOException; import java.io.InputStream; @@ -18,9 +20,6 @@ import java.util.HashMap; import java.util.Map; -import okhttp3.ResponseBody; -import retrofit2.Response; - /** * The builder for building a {@link ServiceResponse}. * @@ -144,9 +143,10 @@ public ServiceResponse build(Response response) throws E, IOExc return new ServiceResponse<>((T) buildBody(statusCode, responseBody), response); } else { try { - E exception = (E) exceptionType.getConstructor(String.class).newInstance("Invalid status code " + statusCode); + Object errorBody = buildBody(statusCode, responseBody); + E exception = (E) exceptionType.getConstructor(String.class).newInstance(mapperAdapter.serialize(errorBody)); exceptionType.getMethod("setResponse", response.getClass()).invoke(exception, response); - exceptionType.getMethod("setBody", (Class) responseTypes.get(0)).invoke(exception, buildBody(statusCode, responseBody)); + exceptionType.getMethod("setBody", (Class) responseTypes.get(0)).invoke(exception, errorBody); throw exception; } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new IOException("Invalid status code " + statusCode + ", but an instance of " + exceptionType.getCanonicalName()