Batching getting permission for multiple items

Mangesh Shinde 0 Reputation points
2025-05-06T10:40:35.7166667+00:00

I am using MS graph java sdk

and want to get permission for five items at time by using batching concept

public void fetchPermissionsInBatch(Map<String, String> items) throws IOException {
		long startPermissionsBatch = System.currentTimeMillis();

		Map<String, List<Permission>> permissionsBatch = new HashMap<String, List<Permission>>();

		BatchRequestContent batchRequestContent = new BatchRequestContent(graphClient);

		Map<String, String> itemIdToRequestId = new HashMap<String, String>();
		Map<String, String> itemIdToStepId = new HashMap<String, String>();
		int counter = 1;

		for (String itemId : items.keySet()) {
			String driveID = items.get(itemId);
			String requestID = String.valueOf(counter);
			itemIdToRequestId.put(itemId, requestID);
			RequestInformation perissionRequestInformation = graphClient.drives().byDriveId(driveID).items()
					.byDriveItemId(itemId).permissions().toGetRequestInformation();
			String permissionRequestStepId = batchRequestContent.addBatchRequestStep(perissionRequestInformation);
			itemIdToStepId.put(itemId, permissionRequestStepId);
		}
		BatchResponseContent batchResponseContent = Objects
				.requireNonNull(graphClient.getBatchRequestBuilder().post(batchRequestContent, null));
		for (String stepid : itemIdToStepId.keySet()) {
			ResponseBody body = batchResponseContent.getResponseById(stepid).body();
			log.info(stepid);
		}
		long endPermissionsBatch = System.currentTimeMillis();
		log.info("Time required for PermissionsIndividually: " + (endPermissionsBatch - startPermissionsBatch) + "ms");
		if (!permissionsBatch.isEmpty()) {
			log.info("Found permissions: " + permissionsBatch.size());
		}
	}

<dependency>
			<groupId>com.microsoft.graph</groupId>
			<artifactId>microsoft-graph-auth</artifactId>
			<version>0.3.0</version>
		</dependency>
		<dependency>
			<groupId>com.microsoft.graph</groupId>
			<artifactId>microsoft-graph-core</artifactId>
			<version>3.1.14</version>
		</dependency>
		<dependency>
			<groupId>com.microsoft.graph</groupId>
			<artifactId>microsoft-graph</artifactId>
			<version>6.21.0</version>
		</dependency>
		<dependency>
			<groupId>com.azure</groupId>
			<artifactId>azure-identity</artifactId>
			<version>1.3.4</version>
		</dependency>

Microsoft Security Microsoft Graph
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. SrideviM 5,630 Reputation points Microsoft External Staff Moderator
    2025-05-08T12:02:01.8833333+00:00

    Hello Mangesh Shinde,

    I understand you're trying to fetch permissions for multiple OneDrive items using batch requests in the Microsoft Graph Java SDK and facing issues with RequestInformation and how the response is handled.

    The approach you're following uses patterns from earlier SDK versions, which don’t align well with the latest Kiota-based SDK (v6.x+). This newer version changes how requests are built and managed.

    In my case, I used Microsoft Graph Java SDK version 5.5.0 with azure-identity for authentication. This combination worked without needing microsoft-graph-core or microsoft-graph-auth. Using BatchRequestContent and BatchResponseContent, I was able to fetch permissions for multiple items in one call.

    Initially, I registered an app in Entra ID and granted it the Files.Read.All permission (Application type) with admin consent:

    User's image

    Here’s the setup that worked for me:

    pom.xml:

        <dependencies>
            <dependency>
                <groupId>com.microsoft.graph</groupId>
                <artifactId>microsoft-graph</artifactId>
                <version>5.5.0</version>
            </dependency>
    
            <dependency>
                <groupId>com.azure</groupId>
                <artifactId>azure-identity</artifactId>
                <version>1.11.0</version>
            </dependency>
    
            <dependency>
                <groupId>com.google.code.gson</groupId>
                <artifactId>gson</artifactId>
                <version>2.10.1</version>
            </dependency>
    
            <!-- SLF4J with Logback for logs -->
            <dependency>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-classic</artifactId>
                <version>1.4.14</version>
            </dependency>
        </dependencies>
    

    Main.java:

    package com.example.graphbatch;
    
    import com.azure.identity.ClientSecretCredential;
    import com.azure.identity.ClientSecretCredentialBuilder;
    import com.google.gson.*;
    import com.microsoft.graph.authentication.TokenCredentialAuthProvider;
    import com.microsoft.graph.content.BatchRequestContent;
    import com.microsoft.graph.content.BatchResponseContent;
    import com.microsoft.graph.content.BatchResponseStep;
    import com.microsoft.graph.requests.GraphServiceClient;
    
    import java.util.*;
    
    public class Main {
        public static void main(String[] args) {
            System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "off");
    
            long startPermissionsBatch = System.currentTimeMillis();
    
            ClientSecretCredential credential = new ClientSecretCredentialBuilder()
                    .clientId("yourappId")
                    .clientSecret("yoursecret")
                    .tenantId("yourtenantId")
                    .build();
    
            TokenCredentialAuthProvider authProvider = new TokenCredentialAuthProvider(
                    List.of("https://graph.microsoft.com/.default"), credential
            );
    
            GraphServiceClient<?> graphClient = GraphServiceClient.builder()
                    .authenticationProvider(authProvider)
                    .buildClient();
    
            Map<String, String> items = Map.of(
                    "ItemId1", "DriveId1",
                    "ItemId2", "DriveId2",
                    "ItemId3", "DriveId3",
                    "ItemId4", "DriveId4",
                    "ItemId5", "DriveId5"
            );
    
            Map<String, List<String>> permissionsBatch = new HashMap<>();
    
            try {
                BatchRequestContent batchRequest = new BatchRequestContent();
                Map<String, String> requestIdToItemId = new HashMap<>();
    
                for (Map.Entry<String, String> entry : items.entrySet()) {
                    String stepId = batchRequest.addBatchRequestStep(
                            graphClient.drives(entry.getValue())
                                    .items(entry.getKey())
                                    .permissions()
                                    .buildRequest()
                    );
                    requestIdToItemId.put(stepId, entry.getKey());
                }
    
                BatchResponseContent response = graphClient.batch()
                        .buildRequest()
                        .post(batchRequest);
    
                Gson gson = new Gson();
    
                for (Map.Entry<String, String> entry : requestIdToItemId.entrySet()) {
                    BatchResponseStep<JsonElement> step = response.getResponseById(entry.getKey());
                    JsonElement body = step.getDeserializedBody(JsonElement.class);
    
                    if (body != null && body.isJsonObject() && body.getAsJsonObject().has("value")) {
                        JsonArray permissions = body.getAsJsonObject().getAsJsonArray("value");
                        List<String> summaries = new ArrayList<>();
    
                        for (JsonElement permElem : permissions) {
                            JsonObject perm = permElem.getAsJsonObject();
                            String userDisplayName = "Unknown";
    
                            if (perm.has("grantedToV2") && perm.getAsJsonObject("grantedToV2").has("user")) {
                                JsonObject user = perm.getAsJsonObject("grantedToV2").getAsJsonObject("user");
                                userDisplayName = user.has("displayName") ? user.get("displayName").getAsString() : "Unknown";
                            }
    
                            List<String> roles = new ArrayList<>();
                            if (perm.has("roles")) {
                                for (JsonElement role : perm.getAsJsonArray("roles")) {
                                    roles.add(role.getAsString());
                                }
                            } else {
                                roles.add("None");
                            }
    
                            summaries.add("Role: " + String.join(", ", roles) + ", User: " + userDisplayName);
                        }
    
                        permissionsBatch.put(entry.getValue(), summaries);
                    }
                }
    
            } catch (Exception e) {
                System.err.println("Batch request failed: " + e.getMessage());
            }
    
            long endPermissionsBatch = System.currentTimeMillis();
            System.out.println("Time required for PermissionsBatch: " + (endPermissionsBatch - startPermissionsBatch) + " ms");
    
            if (!permissionsBatch.isEmpty()) {
                System.out.println("Found permissions for " + permissionsBatch.size() + " items.");
                permissionsBatch.forEach((itemId, summaries) -> {
                    System.out.println("Permissions for item: " + itemId);
                    summaries.forEach(summary -> System.out.println(" - " + summary));
                });
            }
        }
    }
    

    Response:

    User's image Let me know if you have any other questions or need any further assistance.

    Hope this helps!


    If this answers your query, do click Accept Answer and Yes for was this answer helpful, which may help members with similar questions.

    User's image

    If you have any other questions or are still experiencing issues, feel free to ask in the "comments" section, and I'd be happy to help.


  2. Mangesh Shinde 0 Reputation points
    2025-05-08T12:12:45.5966667+00:00

    Yes I used this combination but with the 6.36 msgraph version

    <dependency>
    			<groupId>com.microsoft.graph</groupId>
    			<artifactId>microsoft-graph</artifactId>
    			<version>6.36.0</version>
    		</dependency>
    		<dependency>
    			<groupId>com.azure</groupId>
    			<artifactId>azure-identity</artifactId>
    			<version>1.15.4</version>
    		</dependency>
    
    
    

    and following is method for this

    public Map<String, List<Permission>> getPermissionBatching(Map<String, String> itemDetails, int batchCount) {
    		Map<String, List<Permission>> permissionsBatching = new HashMap<String, List<Permission>>();
    		Map<String, String> itemStepIdDetails = new HashMap<String, String>();
    		try {
    			long start = System.currentTimeMillis();
    			BatchRequestContent batchRequestContent = new BatchRequestContent(graphClient);
    			for (String itemid : itemDetails.keySet()) {
    				long startItem = System.currentTimeMillis();
    				String driveID = itemDetails.get(itemid);
    				RequestInformation requestInformation = graphClient.drives().byDriveId(driveID).items()
    						.byDriveItemId(itemid).permissions().toGetRequestInformation();
    				String requestId = batchRequestContent.addBatchRequestStep(requestInformation);
    				itemStepIdDetails.put(itemid, requestId);
    				/*
    				 * log.debug("Time taken for getting permissions request id for item[" + itemid
    				 * + "]is: " + (System.currentTimeMillis() - startItem) + "ms");
    				 */
    			}
    			long end = System.currentTimeMillis();
    			log.info("Time taken for getting permissions request Ids is: " + (end - start) + "ms");
    
    			BatchResponseContent batchResponseContent = Objects
    					.requireNonNull(graphClient.getBatchRequestBuilder().post(batchRequestContent, null));
    			log.info("Time taken for sending batch permissions api with request Ids is: "
    					+ (System.currentTimeMillis() - start) + "ms");
    
    			long parseStart = System.currentTimeMillis();
    			for (String itemid : itemStepIdDetails.keySet()) {
    				String requestId = itemStepIdDetails.get(itemid);
    				Response res = batchResponseContent.getResponseById(requestId);
    				if (res.isSuccessful()) {
    					ResponseBody body = res.body();
    					if (body != null) {
    						Gson gson = new Gson();
    						Map<String, Object> permissionsResponse = gson.fromJson(res.body().string(), Map.class);
    						if (permissionsResponse != null) {
    							List<Permission> permissions = (List<Permission>) permissionsResponse.get("value");
    							permissionsBatching.put(itemid, permissions);
    						}
    					}
    
    				}
    			}
    			log.info("Time taken for parsing response is: " + (System.currentTimeMillis() - parseStart) + "ms");
    
    		} catch (Exception e) {
    			log.error("Exception while batching permission api: ", e);
    		}
    		return permissionsBatching;
    	}
    
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.