Build Java apps with Microsoft Graph
This tutorial teaches you how to build a Java console app that uses the Microsoft Graph API to retrieve calendar information for a user.
Tip
If you prefer to just download the completed tutorial, you can download or clone the GitHub repository.
Prerequisites
Before you start this tutorial, you should have the Java SE Development Kit (JDK) and Gradle installed on your development machine. If you do not have the JDK or Gradle, visit the previous links for download options.
You should also have either a personal Microsoft account with a mailbox on Outlook.com, or a Microsoft work or school account. If you don't have a Microsoft account, there are a couple of options to get a free account:
- You can sign up for a new personal Microsoft account.
- You can sign up for the Office 365 Developer Program to get a free Office 365 subscription.
Note
This tutorial was written with OpenJDK version 14.0.0.36 and Gradle 6.7.1. The steps in this guide may work with other versions, but that has not been tested.
Feedback
Please provide any feedback on this tutorial in the GitHub repository.
Create a Java console app
In this section you'll create a basic Java console app.
Open your command-line interface (CLI) in a directory where you want to create the project. Run the following command to create a new Gradle project.
gradle init --dsl groovy --test-framework junit --type java-application --project-name graphtutorial --package graphtutorialOnce the project is created, verify that it works by running the following command to run the app in your CLI.
./gradlew --console plain runIf it works, the app should output
Hello World..
Install dependencies
Before moving on, add some additional dependencies that you will use later.
- Azure Identity client library for Java to authenticate the user and acquire access tokens.
- Microsoft Graph SDK for Java to make calls to the Microsoft Graph.
Open ./build.gradle. Update the
dependenciessection to add those dependencies.dependencies { // This dependency is used by the application. implementation 'com.google.guava:guava:28.2-jre' // Use JUnit test framework testImplementation 'junit:junit:4.12' implementation 'com.azure:azure-identity:1.2.5' implementation 'com.microsoft.graph:microsoft-graph:3.2.0' }Add the following to the end of ./build.gradle.
run { standardInput = System.in }
The next time you build the project, Gradle will download those dependencies.
Design the app
Open the ./src/main/java/graphtutorial/App.java file and replace its contents with the following.
package graphtutorial; import java.util.InputMismatchException; import java.util.Scanner; /** * Graph Tutorial * */ public class App { public static void main(String[] args) { System.out.println("Java Graph Tutorial"); System.out.println(); Scanner input = new Scanner(System.in); int choice = -1; while (choice != 0) { System.out.println("Please choose one of the following options:"); System.out.println("0. Exit"); System.out.println("1. Display access token"); System.out.println("2. View this week's calendar"); System.out.println("3. Add an event"); try { choice = input.nextInt(); } catch (InputMismatchException ex) { // Skip over non-integer input } input.nextLine(); // Process user choice switch(choice) { case 0: // Exit the program System.out.println("Goodbye..."); break; case 1: // Display access token break; case 2: // List the calendar break; case 3: // Create a new event break; default: System.out.println("Invalid choice"); } } input.close(); } }This implements a basic menu and reads the user's choice from the command line.
Register the app in the portal
In this exercise you will create a new Azure AD application using the Azure Active Directory admin center.
Open a browser and navigate to the Azure Active Directory admin center and login using a personal account (aka: Microsoft Account) or Work or School Account.
Select Azure Active Directory in the left-hand navigation, then select App registrations under Manage.

Select New registration. On the Register an application page, set the values as follows.
- Set Name to
Java Graph Tutorial. - Set Supported account types to Accounts in any organizational directory and personal Microsoft accounts.
- Under Redirect URI, change the dropdown to Public client (mobile & desktop), and set the value to
https://login.microsoftonline.com/common/oauth2/nativeclient.

- Set Name to
Choose Register. On the Java Graph Tutorial page, copy the value of the Application (client) ID and save it, you will need it in the next step.

Select Authentication under Manage. Locate the Advanced settings section and change the Treat application as a public client toggle to Yes, then choose Save.

Add Azure AD authentication
In this exercise you will extend the application from the previous exercise to support authentication with Azure AD. This is required to obtain the necessary OAuth access token to call the Microsoft Graph. In this step you will integrate the Microsoft Authentication Library (MSAL) for Java into the application.
Create a new directory named graphtutorial in the ./src/main/resources directory.
Create a new file in the ./src/main/resources/graphtutorial directory named oAuth.properties, and add the following text in that file. Replace
YOUR_APP_ID_HEREwith the application ID you created in the Azure portal.app.id=YOUR_APP_ID_HERE app.scopes=User.Read,MailboxSettings.Read,Calendars.ReadWriteThe value of
app.scopescontains the permission scopes the application requires.- User.Read allows the app to access the user's profile.
- MailboxSettings.Read allows the app to access settings from the user's mailbox, including the user's configured time zone.
- Calendars.ReadWrite allows the app to list the user's calendar and add new events to the calendar.
Important
If you're using source control such as git, now would be a good time to exclude the oAuth.properties file from source control to avoid inadvertently leaking your app ID.
Open App.java and add the following
importstatements.import java.io.IOException; import java.util.Properties;Add the following code just before the
Scanner input = new Scanner(System.in);line to load the oAuth.properties file.// Load OAuth settings final Properties oAuthProperties = new Properties(); try { oAuthProperties.load(App.class.getResourceAsStream("oAuth.properties")); } catch (IOException e) { System.out.println("Unable to read OAuth configuration. Make sure you have a properly formatted oAuth.properties file. See README for details."); return; } final String appId = oAuthProperties.getProperty("app.id"); final List<String> appScopes = Arrays .asList(oAuthProperties.getProperty("app.scopes").split(","));
Implement sign-in
Create a new file in the ./graphtutorial/src/main/java/graphtutorial directory named Graph.java and add the following code.
package graphtutorial; import java.net.URL; import java.time.LocalDateTime; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.LinkedList; import java.util.List; import java.util.Set; import okhttp3.Request; import com.azure.identity.DeviceCodeCredential; import com.azure.identity.DeviceCodeCredentialBuilder; import com.microsoft.graph.authentication.TokenCredentialAuthProvider; import com.microsoft.graph.logger.DefaultLogger; import com.microsoft.graph.logger.LoggerLevel; import com.microsoft.graph.models.Attendee; import com.microsoft.graph.models.DateTimeTimeZone; import com.microsoft.graph.models.EmailAddress; import com.microsoft.graph.models.Event; import com.microsoft.graph.models.ItemBody; import com.microsoft.graph.models.User; import com.microsoft.graph.models.AttendeeType; import com.microsoft.graph.models.BodyType; import com.microsoft.graph.options.HeaderOption; import com.microsoft.graph.options.Option; import com.microsoft.graph.options.QueryOption; import com.microsoft.graph.requests.GraphServiceClient; import com.microsoft.graph.requests.EventCollectionPage; import com.microsoft.graph.requests.EventCollectionRequestBuilder; public class Graph { private static GraphServiceClient<Request> graphClient = null; private static TokenCredentialAuthProvider authProvider = null; public static void initializeGraphAuth(String applicationId, List<String> scopes) { // Create the auth provider final DeviceCodeCredential credential = new DeviceCodeCredentialBuilder() .clientId(applicationId) .challengeConsumer(challenge -> System.out.println(challenge.getMessage())) .build(); authProvider = new TokenCredentialAuthProvider(scopes, credential); // Create default logger to only log errors DefaultLogger logger = new DefaultLogger(); logger.setLoggingLevel(LoggerLevel.ERROR); // Build a Graph client graphClient = GraphServiceClient.builder() .authenticationProvider(authProvider) .logger(logger) .buildClient(); } public static String getUserAccessToken() { try { URL meUrl = new URL("https://graph.microsoft.com/v1.0/me"); return authProvider.getAuthorizationTokenAsync(meUrl).get(); } catch(Exception ex) { return null; } } }In App.java, add the following code just before the
Scanner input = new Scanner(System.in);line to get an access token.// Initialize Graph with auth settings Graph.initializeGraphAuth(appId, appScopes); final String accessToken = Graph.getUserAccessToken();Add the following line after the
// Display access tokencomment.System.out.println("Access token: " + accessToken);Run the app. The application displays a URL and device code.
Java Graph Tutorial To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code F7CG945YZ to authenticate.Open a browser and browse to the URL displayed. Enter the provided code and sign in. Once completed, return to the application and choose the 1. Display access token option to display the access token.
Tip
Access tokens for Microsoft work or school accounts can be parsed for troubleshooting purposes at https://jwt.ms. Access tokens for personal Microsoft accounts use a proprietary format and cannot be parsed.
Get a calendar view
In this exercise you will incorporate the Microsoft Graph into the application. For this application, you will use the Microsoft Graph SDK for Java to make calls to Microsoft Graph.
Get user details
Create a new file in the ./graphtutorial/src/main/java/graphtutorial directory named Graph.java and add the following code.
public static User getUser() { if (graphClient == null) throw new NullPointerException( "Graph client has not been initialized. Call initializeGraphAuth before calling this method"); // GET /me to get authenticated user User me = graphClient .me() .buildRequest() .select("displayName,mailboxSettings") .get(); return me; }Add the following
importstatement at the top of App.java.import com.microsoft.graph.models.User;Add the following code in App.java just before the
Scanner input = new Scanner(System.in);line to get the user and output the user's display name.// Greet the user User user = Graph.getUser(); System.out.println("Welcome " + user.displayName); System.out.println("Time zone: " + user.mailboxSettings.timeZone); System.out.println();Run the app. After you log in the app welcomes you by name.
Get calendar events from Outlook
Add the following function to the
Graphclass in Graph.java to get events from the user's calendar.public static List<Event> getCalendarView( ZonedDateTime viewStart, ZonedDateTime viewEnd, String timeZone) { if (graphClient == null) throw new NullPointerException( "Graph client has not been initialized. Call initializeGraphAuth before calling this method"); List<Option> options = new LinkedList<Option>(); options.add(new QueryOption("startDateTime", viewStart.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME))); options.add(new QueryOption("endDateTime", viewEnd.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME))); // Sort results by start time options.add(new QueryOption("$orderby", "start/dateTime")); // Start and end times adjusted to user's time zone options.add(new HeaderOption("Prefer", "outlook.timezone=\"" + timeZone + "\"")); // GET /me/events EventCollectionPage eventPage = graphClient .me() .calendarView() .buildRequest(options) .select("subject,organizer,start,end") .top(25) .get(); List<Event> allEvents = new LinkedList<Event>(); // Create a separate list of options for the paging requests // paging request should not include the query parameters from the initial // request, but should include the headers. List<Option> pagingOptions = new LinkedList<Option>(); pagingOptions.add(new HeaderOption("Prefer", "outlook.timezone=\"" + timeZone + "\"")); while (eventPage != null) { allEvents.addAll(eventPage.getCurrentPage()); EventCollectionRequestBuilder nextPage = eventPage.getNextPage(); if (nextPage == null) { break; } else { eventPage = nextPage .buildRequest(pagingOptions) .get(); } } return allEvents; }
Consider what this code is doing.
- The URL that will be called is
/me/calendarview.QueryOptionobjects are used to add thestartDateTimeandendDateTimeparameters, setting the start and end of the calendar view.- A
QueryOptionobject is used to add the$orderbyparameter, sorting the results by start time. - A
HeaderOptionobject is used to add thePrefer: outlook.timezoneheader, causing the start and end times to be adjusted to the user's time zone. - The
selectfunction limits the fields returned for each event to just those the app will actually use. - The
topfunction limits the number of events in the response to a maximum of 25.
- The
getNextPagefunction is used to request additional pages of results if there are more than 25 events in the current week.
Create a new file in the ./graphtutorial/src/main/java/graphtutorial directory named GraphToIana.java and add the following code.
package graphtutorial; import java.time.ZoneId; import java.util.Map; // Basic lookup for mapping Windows time zone identifiers to // IANA identifiers // Mappings taken from // https://github.com/unicode-org/cldr/blob/master/common/supplemental/windowsZones.xml public class GraphToIana { private static final Map<String, String> timeZoneIdMap = Map.ofEntries( Map.entry("Dateline Standard Time", "Etc/GMT+12"), Map.entry("UTC-11", "Etc/GMT+11"), Map.entry("Aleutian Standard Time", "America/Adak"), Map.entry("Hawaiian Standard Time", "Pacific/Honolulu"), Map.entry("Marquesas Standard Time", "Pacific/Marquesas"), Map.entry("Alaskan Standard Time", "America/Anchorage"), Map.entry("UTC-09", "Etc/GMT+9"), Map.entry("Pacific Standard Time (Mexico)", "America/Tijuana"), Map.entry("UTC-08", "Etc/GMT+8"), Map.entry("Pacific Standard Time", "America/Los_Angeles"), Map.entry("US Mountain Standard Time", "America/Phoenix"), Map.entry("Mountain Standard Time (Mexico)", "America/Chihuahua"), Map.entry("Mountain Standard Time", "America/Denver"), Map.entry("Central America Standard Time", "America/Guatemala"), Map.entry("Central Standard Time", "America/Chicago"), Map.entry("Easter Island Standard Time", "Pacific/Easter"), Map.entry("Central Standard Time (Mexico)", "America/Mexico_City"), Map.entry("Canada Central Standard Time", "America/Regina"), Map.entry("SA Pacific Standard Time", "America/Bogota"), Map.entry("Eastern Standard Time (Mexico)", "America/Cancun"), Map.entry("Eastern Standard Time", "America/New_York"), Map.entry("Haiti Standard Time", "America/Port-au-Prince"), Map.entry("Cuba Standard Time", "America/Havana"), Map.entry("US Eastern Standard Time", "America/Indianapolis"), Map.entry("Turks And Caicos Standard Time", "America/Grand_Turk"), Map.entry("Paraguay Standard Time", "America/Asuncion"), Map.entry("Atlantic Standard Time", "America/Halifax"), Map.entry("Venezuela Standard Time", "America/Caracas"), Map.entry("Central Brazilian Standard Time", "America/Cuiaba"), Map.entry("SA Western Standard Time", "America/La_Paz"), Map.entry("Pacific SA Standard Time", "America/Santiago"), Map.entry("Newfoundland Standard Time", "America/St_Johns"), Map.entry("Tocantins Standard Time", "America/Araguaina"), Map.entry("E. South America Standard Time", "America/Sao_Paulo"), Map.entry("SA Eastern Standard Time", "America/Cayenne"), Map.entry("Argentina Standard Time", "America/Buenos_Aires"), Map.entry("Greenland Standard Time", "America/Godthab"), Map.entry("Montevideo Standard Time", "America/Montevideo"), Map.entry("Magallanes Standard Time", "America/Punta_Arenas"), Map.entry("Saint Pierre Standard Time", "America/Miquelon"), Map.entry("Bahia Standard Time", "America/Bahia"), Map.entry("UTC-02", "Etc/GMT+2"), Map.entry("Azores Standard Time", "Atlantic/Azores"), Map.entry("Cape Verde Standard Time", "Atlantic/Cape_Verde"), Map.entry("UTC", "Etc/GMT"), Map.entry("GMT Standard Time", "Europe/London"), Map.entry("Greenwich Standard Time", "Atlantic/Reykjavik"), Map.entry("Sao Tome Standard Time", "Africa/Sao_Tome"), Map.entry("Morocco Standard Time", "Africa/Casablanca"), Map.entry("W. Europe Standard Time", "Europe/Berlin"), Map.entry("Central Europe Standard Time", "Europe/Budapest"), Map.entry("Romance Standard Time", "Europe/Paris"), Map.entry("Central European Standard Time", "Europe/Warsaw"), Map.entry("W. Central Africa Standard Time", "Africa/Lagos"), Map.entry("Jordan Standard Time", "Asia/Amman"), Map.entry("GTB Standard Time", "Europe/Bucharest"), Map.entry("Middle East Standard Time", "Asia/Beirut"), Map.entry("Egypt Standard Time", "Africa/Cairo"), Map.entry("E. Europe Standard Time", "Europe/Chisinau"), Map.entry("Syria Standard Time", "Asia/Damascus"), Map.entry("West Bank Standard Time", "Asia/Hebron"), Map.entry("South Africa Standard Time", "Africa/Johannesburg"), Map.entry("FLE Standard Time", "Europe/Kiev"), Map.entry("Israel Standard Time", "Asia/Jerusalem"), Map.entry("Kaliningrad Standard Time", "Europe/Kaliningrad"), Map.entry("Sudan Standard Time", "Africa/Khartoum"), Map.entry("Libya Standard Time", "Africa/Tripoli"), Map.entry("Namibia Standard Time", "Africa/Windhoek"), Map.entry("Arabic Standard Time", "Asia/Baghdad"), Map.entry("Turkey Standard Time", "Europe/Istanbul"), Map.entry("Arab Standard Time", "Asia/Riyadh"), Map.entry("Belarus Standard Time", "Europe/Minsk"), Map.entry("Russian Standard Time", "Europe/Moscow"), Map.entry("E. Africa Standard Time", "Africa/Nairobi"), Map.entry("Iran Standard Time", "Asia/Tehran"), Map.entry("Arabian Standard Time", "Asia/Dubai"), Map.entry("Astrakhan Standard Time", "Europe/Astrakhan"), Map.entry("Azerbaijan Standard Time", "Asia/Baku"), Map.entry("Russia Time Zone 3", "Europe/Samara"), Map.entry("Mauritius Standard Time", "Indian/Mauritius"), Map.entry("Saratov Standard Time", "Europe/Saratov"), Map.entry("Georgian Standard Time", "Asia/Tbilisi"), Map.entry("Volgograd Standard Time", "Europe/Volgograd"), Map.entry("Caucasus Standard Time", "Asia/Yerevan"), Map.entry("Afghanistan Standard Time", "Asia/Kabul"), Map.entry("West Asia Standard Time", "Asia/Tashkent"), Map.entry("Ekaterinburg Standard Time", "Asia/Yekaterinburg"), Map.entry("Pakistan Standard Time", "Asia/Karachi"), Map.entry("Qyzylorda Standard Time", "Asia/Qyzylorda"), Map.entry("India Standard Time", "Asia/Calcutta"), Map.entry("Sri Lanka Standard Time", "Asia/Colombo"), Map.entry("Nepal Standard Time", "Asia/Katmandu"), Map.entry("Central Asia Standard Time", "Asia/Almaty"), Map.entry("Bangladesh Standard Time", "Asia/Dhaka"), Map.entry("Omsk Standard Time", "Asia/Omsk"), Map.entry("Myanmar Standard Time", "Asia/Rangoon"), Map.entry("SE Asia Standard Time", "Asia/Bangkok"), Map.entry("Altai Standard Time", "Asia/Barnaul"), Map.entry("W. Mongolia Standard Time", "Asia/Hovd"), Map.entry("North Asia Standard Time", "Asia/Krasnoyarsk"), Map.entry("N. Central Asia Standard Time", "Asia/Novosibirsk"), Map.entry("Tomsk Standard Time", "Asia/Tomsk"), Map.entry("China Standard Time", "Asia/Shanghai"), Map.entry("North Asia East Standard Time", "Asia/Irkutsk"), Map.entry("Singapore Standard Time", "Asia/Singapore"), Map.entry("W. Australia Standard Time", "Australia/Perth"), Map.entry("Taipei Standard Time", "Asia/Taipei"), Map.entry("Ulaanbaatar Standard Time", "Asia/Ulaanbaatar"), Map.entry("Aus Central W. Standard Time", "Australia/Eucla"), Map.entry("Transbaikal Standard Time", "Asia/Chita"), Map.entry("Tokyo Standard Time", "Asia/Tokyo"), Map.entry("North Korea Standard Time", "Asia/Pyongyang"), Map.entry("Korea Standard Time", "Asia/Seoul"), Map.entry("Yakutsk Standard Time", "Asia/Yakutsk"), Map.entry("Cen. Australia Standard Time", "Australia/Adelaide"), Map.entry("AUS Central Standard Time", "Australia/Darwin"), Map.entry("E. Australia Standard Time", "Australia/Brisbane"), Map.entry("AUS Eastern Standard Time", "Australia/Sydney"), Map.entry("West Pacific Standard Time", "Pacific/Port_Moresby"), Map.entry("Tasmania Standard Time", "Australia/Hobart"), Map.entry("Vladivostok Standard Time", "Asia/Vladivostok"), Map.entry("Lord Howe Standard Time", "Australia/Lord_Howe"), Map.entry("Bougainville Standard Time", "Pacific/Bougainville"), Map.entry("Russia Time Zone 10", "Asia/Srednekolymsk"), Map.entry("Magadan Standard Time", "Asia/Magadan"), Map.entry("Norfolk Standard Time", "Pacific/Norfolk"), Map.entry("Sakhalin Standard Time", "Asia/Sakhalin"), Map.entry("Central Pacific Standard Time", "Pacific/Guadalcanal"), Map.entry("Russia Time Zone 11", "Asia/Kamchatka"), Map.entry("New Zealand Standard Time", "Pacific/Auckland"), Map.entry("UTC+12", "Etc/GMT-12"), Map.entry("Fiji Standard Time", "Pacific/Fiji"), Map.entry("Chatham Islands Standard Time", "Pacific/Chatham"), Map.entry("UTC+13", "Etc/GMT-13"), Map.entry("Tonga Standard Time", "Pacific/Tongatapu"), Map.entry("Samoa Standard Time", "Pacific/Apia"), Map.entry("Line Islands Standard Time", "Pacific/Kiritimati") ); public static String getIanaFromWindows(String windowsTimeZone) { String iana = timeZoneIdMap.get(windowsTimeZone); // If a mapping was not found, assume the value passed // was already an IANA identifier return (iana == null) ? windowsTimeZone : iana; } public static ZoneId getZoneIdFromWindows(String windowsTimeZone) { String timeZoneId = getIanaFromWindows(windowsTimeZone); return ZoneId.of(timeZoneId); } }This class implements a simple lookup to convert Windows time zone names to IANA identifiers, and to generate a ZoneId based on a Windows time zone name.
Display the results
Add the following
importstatements in App.java.import java.time.DayOfWeek; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.time.format.FormatStyle; import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalAdjusters; import java.util.HashSet; import java.util.List; import com.microsoft.graph.models.DateTimeTimeZone; import com.microsoft.graph.models.Event;Add the following function to the
Appclass to format the dateTimeTimeZone properties from Microsoft Graph into a user-friendly format.private static String formatDateTimeTimeZone(DateTimeTimeZone date) { LocalDateTime dateTime = LocalDateTime.parse(date.dateTime); return dateTime.format( DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)) + " (" + date.timeZone + ")"; }Add the following function to the
Appclass to get the user's events and output them to the console.private static void listCalendarEvents(String timeZone) { ZoneId tzId = GraphToIana.getZoneIdFromWindows("Pacific Standard Time"); // Get midnight of the first day of the week (assumed Sunday) // in the user's timezone, then convert to UTC ZonedDateTime startOfWeek = ZonedDateTime.now(tzId) .with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY)) .truncatedTo(ChronoUnit.DAYS) .withZoneSameInstant(ZoneId.of("UTC")); // Add 7 days to get the end of the week ZonedDateTime endOfWeek = startOfWeek.plusDays(7); // Get the user's events List<Event> events = Graph.getCalendarView( startOfWeek, endOfWeek, timeZone); System.out.println("Events:"); for (Event event : events) { System.out.println("Subject: " + event.subject); System.out.println(" Organizer: " + event.organizer.emailAddress.name); System.out.println(" Start: " + formatDateTimeTimeZone(event.start)); System.out.println(" End: " + formatDateTimeTimeZone(event.end)); } System.out.println(); }Add the following just after the
// List the calendarcomment in themainfunction.listCalendarEvents(user.mailboxSettings.timeZone);Save all of your changes, build the app, then run it. Choose the List calendar events option to see a list of the user's events.
Welcome Adele Vance Please choose one of the following options: 0. Exit 1. Display access token 2. View this week's calendar 3. Add an event 2 Events: Subject: Weekly meeting Organizer: Lynne Robbins Start: 12/7/20, 2:00 PM (Pacific Standard Time) End: 12/7/20, 3:00 PM (Pacific Standard Time) Subject: Carpool Organizer: Lynne Robbins Start: 12/7/20, 4:00 PM (Pacific Standard Time) End: 12/7/20, 5:30 PM (Pacific Standard Time) Subject: Tailspin Toys Proposal Review + Lunch Organizer: Lidia Holloway Start: 12/8/20, 12:00 PM (Pacific Standard Time) End: 12/8/20, 1:00 PM (Pacific Standard Time) Subject: Project Tailspin Organizer: Lidia Holloway Start: 12/8/20, 3:00 PM (Pacific Standard Time) End: 12/8/20, 4:30 PM (Pacific Standard Time) Subject: Company Meeting Organizer: Christie Cline Start: 12/9/20, 8:30 AM (Pacific Standard Time) End: 12/9/20, 11:00 AM (Pacific Standard Time) Subject: Carpool Organizer: Lynne Robbins Start: 12/9/20, 4:00 PM (Pacific Standard Time) End: 12/9/20, 5:30 PM (Pacific Standard Time) Subject: Project Team Meeting Organizer: Lidia Holloway Start: 12/10/20, 8:00 AM (Pacific Standard Time) End: 12/10/20, 9:30 AM (Pacific Standard Time) Subject: Weekly Marketing Lunch Organizer: Adele Vance Start: 12/10/20, 12:00 PM (Pacific Standard Time) End: 12/10/20, 1:00 PM (Pacific Standard Time) Subject: Project Tailspin Organizer: Lidia Holloway Start: 12/10/20, 3:00 PM (Pacific Standard Time) End: 12/10/20, 4:30 PM (Pacific Standard Time) Subject: Lunch? Organizer: Lynne Robbins Start: 12/11/20, 12:00 PM (Pacific Standard Time) End: 12/11/20, 1:00 PM (Pacific Standard Time) Subject: Friday Unwinder Organizer: Megan Bowen Start: 12/11/20, 4:00 PM (Pacific Standard Time) End: 12/11/20, 5:00 PM (Pacific Standard Time)
Create a new event
In this section you will add the ability to create events on the user's calendar.
Open ./graphtutorial/src/main/java/graphtutorial/Graph.java and add the following function to the Graph class.
public static void createEvent( String timeZone, String subject, LocalDateTime start, LocalDateTime end, Set<String> attendees, String body) { if (graphClient == null) throw new NullPointerException( "Graph client has not been initialized. Call initializeGraphAuth before calling this method"); Event newEvent = new Event(); newEvent.subject = subject; newEvent.start = new DateTimeTimeZone(); newEvent.start.dateTime = start.toString(); newEvent.start.timeZone = timeZone; newEvent.end = new DateTimeTimeZone(); newEvent.end.dateTime = end.toString(); newEvent.end.timeZone = timeZone; if (attendees != null && !attendees.isEmpty()) { newEvent.attendees = new LinkedList<Attendee>(); attendees.forEach((email) -> { Attendee attendee = new Attendee(); // Set each attendee as required attendee.type = AttendeeType.REQUIRED; attendee.emailAddress = new EmailAddress(); attendee.emailAddress.address = email; newEvent.attendees.add(attendee); }); } if (body != null) { newEvent.body = new ItemBody(); newEvent.body.content = body; // Treat body as plain text newEvent.body.contentType = BodyType.TEXT; } // POST /me/events graphClient .me() .events() .buildRequest() .post(newEvent); }Open ./graphtutorial/src/main/java/graphtutorial/App.java and add the following function to the App class.
private static void createEvent(String timeZone, Scanner input) { DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("M/d/yyyy h:mm a"); // Prompt for subject String subject = ""; while (subject.isBlank()) { System.out.print("Subject (required): "); subject = input.nextLine(); } // Prompt for start date/time LocalDateTime start = null; while (start == null) { System.out.print("Start (mm/dd/yyyy hh:mm AM/PM): "); String date = input.nextLine(); try { start = LocalDateTime.parse(date, inputFormat); } catch (DateTimeParseException dtp) { System.out.println("Invalid input, try again."); } } // Prompt for end date/time LocalDateTime end = null; while (end == null) { System.out.print("End (mm/dd/yyyy hh:mm AM/PM): "); String date = input.nextLine(); try { end = LocalDateTime.parse(date, inputFormat); } catch (DateTimeParseException dtp) { System.out.println("Invalid input, try again."); } if (end.isBefore(start)) { System.out.println("End time must be after start time."); end = null; } } // Prompt for attendees HashSet<String> attendees = new HashSet<String>(); System.out.print("Would you like to add attendees? (y/n): "); if (input.nextLine().trim().toLowerCase().startsWith("y")) { String attendee = ""; do { System.out.print("Enter an email address (leave blank to finalize the list): "); attendee = input.nextLine(); if (!attendee.isBlank()) { attendees.add(attendee); } } while (!attendee.isBlank()); } // Prompt for body String body = null; System.out.print("Would you like to add a body? (y/n): "); if (input.nextLine().trim().toLowerCase().startsWith("y")) { System.out.print("Enter a body: "); body = input.nextLine(); } // Confirm input System.out.println(); System.out.println("New event:"); System.out.println("Subject: " + subject); System.out.println("Start: " + start.format(inputFormat)); System.out.println("End: " + end.format(inputFormat)); System.out.println("Attendees: " + (attendees.size() > 0 ? attendees.toString() : "NONE")); System.out.println("Body: " + (body == null ? "NONE" : body)); System.out.print("Is this correct? (y/n): "); if (input.nextLine().trim().toLowerCase().startsWith("y")) { Graph.createEvent(timeZone, subject, start, end, attendees, body); System.out.println("Event created."); } else { System.out.println("Canceling."); } System.out.println(); }This function prompts the user for subject, attendees, start, end, and body, then uses those values to call
Graph.createEvent.Add the following just after the
// Create a new eventcomment in theMainfunction.createEvent(user.mailboxSettings.timeZone, input);Save all of your changes and run the app. Choose the Add an event option. Respond to the prompts to create a new event on the user's calendar.
Congratulations!
You've completed the Java Microsoft Graph tutorial. Now that you have a working app that calls Microsoft Graph, you can experiment and add new features. Visit the Overview of Microsoft Graph to see all of the data you can access with Microsoft Graph.
Feedback
Please provide any feedback on this tutorial in the GitHub repository.
Have an issue with this section? If so, please give us some feedback so we can improve this section.