Last active
December 12, 2023 15:14
-
-
Save maisarissi/2a9076ed31a797372c90af707dd58bf4 to your computer and use it in GitHub Desktop.
microsoftgraph-java-v6-batch-collection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Use adjusted pageIterator sample from above to get list of first 100 messageIds. | |
MessageCollectionResponse messages = graphClient | |
.me() | |
.messages() | |
.get(); | |
List<String> messagesIdList = new LinkedList<String>(); | |
PageIterator pageIterator = new PageIterator.Builder<Message, MessageCollectionResponse>() | |
.client(graphClient) | |
.collectionPage(messages) | |
.collectionPageFactory(MessageCollectionResponse::createFromDiscriminatorValue) | |
.processPageItemCallback(message -> { | |
messagesIdList.add(message.getId()); | |
if(messagesIdList.size() >= 100) { | |
return false; | |
} | |
return true; }) | |
.build(); | |
pageIterator.iterate(); | |
// Create new BatchRequestContentCollection to hold all requests. | |
BatchRequestContentCollection batchCollection = new BatchRequestContentCollection(graphClient); | |
// Use for loop to add requests to the BatchRequestContentCollection. | |
for (String messageId: messagesIdList) { | |
RequestInformation deleteRequest = graphClient | |
.me() | |
.messages() | |
.byMessageId(messageId) | |
.toDeleteRequestInformation(); | |
batchCollection.addBatchRequestStep(deleteRequest); | |
} | |
// Create a list of the requestIDs of the added requests from above | |
List<String> requestIds = new LinkedList<String>(); | |
batchCollection.getBatchRequestSteps().forEach((key, value) -> requestIds.add(value.getRequestId())); | |
// Execute the batch request | |
BatchResponseContentCollection batchResponseCollection = graphClient.getBatchRequestBuilder().post(batchCollection, null); | |
//Specify a custom and optional ResponseHandler to handle individual response as you wish | |
batchResponseCollection.getResponseById(requestIds.get(1), new CustomResponseHandler()); | |
// Custom ResponseHandler class example: | |
public class CustomResponseHandler implements ResponseHandler { | |
@Override | |
public <NativeResponseType, ModelType> ModelType handleResponse(NativeResponseType response, | |
HashMap<String, ParsableFactory<? extends Parsable>> errorMappings) { | |
// Do your own implementation of the reponse here | |
try{ | |
okhttp3.Response castResponse = (okhttp3.Response) response; | |
assert castResponse.body() != null; | |
System.out.println(castResponse.body().string()); | |
} | |
catch(ClassCastException ex) { | |
throw new RuntimeException(ex); | |
} catch (IOException e) { | |
throw new RuntimeException(e); | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment