Skip to content

Instantly share code, notes, and snippets.

@maisarissi
Last active December 12, 2023 15:14
Show Gist options
  • Save maisarissi/2a9076ed31a797372c90af707dd58bf4 to your computer and use it in GitHub Desktop.
Save maisarissi/2a9076ed31a797372c90af707dd58bf4 to your computer and use it in GitHub Desktop.
microsoftgraph-java-v6-batch-collection
//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