FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Updated to v3 of the Graph SDK by jasonjoh · Pull Request #27 · microsoftgraph/msgraph-training-java · GitHub

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .gradle  (1) .java  (4) .md  (4) All 3 file types selected
Deleted files Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
5 changes: 2 additions & 3 deletions demo/graphtutorial/build.gradle
This file contains hidden or 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
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,8 @@ dependencies {

// Use JUnit test framework
testImplementation 'junit:junit:4.12'
implementation 'com.microsoft.azure:msal4j:1.8.0'
implementation 'com.microsoft.graph:microsoft-graph:2.4.1'
implementation 'org.slf4j:slf4j-nop:1.8.0-beta4'
implementation 'com.azure:azure-identity:1.2.5'
implementation 'com.microsoft.graph:microsoft-graph:3.2.0'
}
// </DependenciesSnippet>

Expand Down
30 changes: 16 additions & 14 deletions demo/graphtutorial/src/main/java/graphtutorial/App.java
This file contains hidden or 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
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,16 @@
import java.time.format.FormatStyle;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.Arrays;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;

import com.microsoft.graph.models.extensions.DateTimeTimeZone;
import com.microsoft.graph.models.extensions.Event;
import com.microsoft.graph.models.extensions.User;
import com.microsoft.graph.models.DateTimeTimeZone;
import com.microsoft.graph.models.Event;
import com.microsoft.graph.models.User;

/**
* Graph Tutorial
Expand All @@ -43,15 +44,16 @@ public static void main(String[] args) {
}

final String appId = oAuthProperties.getProperty("app.id");
final String[] appScopes = oAuthProperties.getProperty("app.scopes").split(",");
final List<String> appScopes = Arrays
.asList(oAuthProperties.getProperty("app.scopes").split(","));
// </LoadSettingsSnippet>

// Get an access token
Authentication.initialize(appId);
final String accessToken = Authentication.getUserAccessToken(appScopes);
// Initialize Graph with auth settings
Graph.initializeGraphAuth(appId, appScopes);
final String accessToken = Graph.getUserAccessToken();

// Greet the user
User user = Graph.getUser(accessToken);
User user = Graph.getUser();
System.out.println("Welcome " + user.displayName);
System.out.println("Time zone: " + user.mailboxSettings.timeZone);
System.out.println();
Expand Down Expand Up @@ -87,11 +89,11 @@ public static void main(String[] args) {
break;
case 2:
// List the calendar
listCalendarEvents(accessToken, user.mailboxSettings.timeZone);
listCalendarEvents(user.mailboxSettings.timeZone);
break;
case 3:
// Create a new event
createEvent(accessToken, user.mailboxSettings.timeZone, input);
createEvent(user.mailboxSettings.timeZone, input);
break;
default:
System.out.println("Invalid choice");
Expand All @@ -112,7 +114,7 @@ private static String formatDateTimeTimeZone(DateTimeTimeZone date) {
// </FormatDateSnippet>

// <ListEventsSnippet>
private static void listCalendarEvents(String accessToken, String timeZone) {
private static void listCalendarEvents(String timeZone) {
ZoneId tzId = GraphToIana.getZoneIdFromWindows("Pacific Standard Time");

// Get midnight of the first day of the week (assumed Sunday)
Expand All @@ -126,7 +128,7 @@ private static void listCalendarEvents(String accessToken, String timeZone) {
ZonedDateTime endOfWeek = startOfWeek.plusDays(7);

// Get the user's events
List<Event> events = Graph.getCalendarView(accessToken,
List<Event> events = Graph.getCalendarView(
startOfWeek, endOfWeek, timeZone);

System.out.println("Events:");
Expand All @@ -143,7 +145,7 @@ private static void listCalendarEvents(String accessToken, String timeZone) {
// </ListEventsSnippet>

// <CreateEventSnippet>
private static void createEvent(String accessToken, String timeZone, Scanner input) {
private static void createEvent(String timeZone, Scanner input) {
DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("M/d/yyyy h:mm a");

// Prompt for subject
Expand Down Expand Up @@ -218,7 +220,7 @@ private static void createEvent(String accessToken, String timeZone, Scanner inp

System.out.print("Is this correct? (y/n): ");
if (input.nextLine().trim().toLowerCase().startsWith("y")) {
Graph.createEvent(accessToken, timeZone, subject, start, end, attendees, body);
Graph.createEvent(timeZone, subject, start, end, attendees, body);
System.out.println("Event created.");
} else {
System.out.println("Canceling.");
Expand Down

This file was deleted.

92 changes: 58 additions & 34 deletions demo/graphtutorial/src/main/java/graphtutorial/Graph.java
This file contains hidden or 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
Original file line number Diff line number Diff line change
Expand Up @@ -3,58 +3,80 @@

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.extensions.Attendee;
import com.microsoft.graph.models.extensions.DateTimeTimeZone;
import com.microsoft.graph.models.extensions.EmailAddress;
import com.microsoft.graph.models.extensions.Event;
import com.microsoft.graph.models.extensions.IGraphServiceClient;
import com.microsoft.graph.models.extensions.ItemBody;
import com.microsoft.graph.models.extensions.User;
import com.microsoft.graph.models.generated.AttendeeType;
import com.microsoft.graph.models.generated.BodyType;
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.extensions.GraphServiceClient;
import com.microsoft.graph.requests.extensions.IEventCollectionPage;
import com.microsoft.graph.requests.extensions.IEventCollectionRequestBuilder;
import com.microsoft.graph.requests.GraphServiceClient;
import com.microsoft.graph.requests.EventCollectionPage;
import com.microsoft.graph.requests.EventCollectionRequestBuilder;

/**
* Graph
*/
public class Graph {

private static IGraphServiceClient graphClient = null;
private static SimpleAuthProvider authProvider = null;
private static GraphServiceClient<Request> graphClient = null;
private static TokenCredentialAuthProvider authProvider = null;

@SuppressWarnings("unchecked")
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();

private static void ensureGraphClient(String accessToken) {
if (graphClient == null) {
// Create the auth provider
authProvider = new SimpleAuthProvider(accessToken);
authProvider = new TokenCredentialAuthProvider(scopes, credential);

// Create default logger to only log errors
DefaultLogger logger = new DefaultLogger();
logger.setLoggingLevel(LoggerLevel.ERROR);
// 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();
// 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;
}
}

public static User getUser(String accessToken) {
ensureGraphClient(accessToken);
// <GetUserSnippet>
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
Expand All @@ -65,11 +87,13 @@ public static User getUser(String accessToken) {

return me;
}
// <GetUserSnippet>

// <GetEventsSnippet>
public static List<Event> getCalendarView(String accessToken,
public static List<Event> getCalendarView(
ZonedDateTime viewStart, ZonedDateTime viewEnd, String timeZone) {
ensureGraphClient(accessToken);
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)));
Expand All @@ -81,7 +105,7 @@ public static List<Event> getCalendarView(String accessToken,
options.add(new HeaderOption("Prefer", "outlook.timezone=\"" + timeZone + "\""));

// GET /me/events
IEventCollectionPage eventPage = graphClient
EventCollectionPage eventPage = graphClient
.me()
.calendarView()
.buildRequest(options)
Expand All @@ -100,7 +124,7 @@ public static List<Event> getCalendarView(String accessToken,
while (eventPage != null) {
allEvents.addAll(eventPage.getCurrentPage());

IEventCollectionRequestBuilder nextPage =
EventCollectionRequestBuilder nextPage =
eventPage.getNextPage();

if (nextPage == null) {
Expand All @@ -118,15 +142,15 @@ public static List<Event> getCalendarView(String accessToken,

// <CreateEventSnippet>
public static void createEvent(
String accessToken,
String timeZone,
String subject,
LocalDateTime start,
LocalDateTime end,
Set<String> attendees,
String body)
{
ensureGraphClient(accessToken);
if (graphClient == null) throw new NullPointerException(
"Graph client has not been initialized. Call initializeGraphAuth before calling this method");

Event newEvent = new Event();

Expand Down

This file was deleted.

5 changes: 2 additions & 3 deletions tutorial/02-create-app.md
This file contains hidden or 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
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,12 @@ In this section you'll create a basic Java console app.

Before moving on, add some additional dependencies that you will use later.

- [Microsoft Authentication Library (MSAL) for Java](https://github.com/AzureAD/microsoft-authentication-library-for-java) to authenticate the user and acquire access tokens.
- [Azure Identity client library for Java](https://github.com/Azure/azure-sdk-for-java/tree/master/sdk/identity/azure-identity) to authenticate the user and acquire access tokens.
- [Microsoft Graph SDK for Java](https://github.com/microsoftgraph/msgraph-sdk-java) to make calls to the Microsoft Graph.
- [SLF4J NOP Binding](https://mvnrepository.com/artifact/org.slf4j/slf4j-nop) to suppress logging from MSAL.

1. Open **./build.gradle**. Update the `dependencies` section to add those dependencies.

:::code language="gradle" source="../demo/graphtutorial/build.gradle" id="DependenciesSnippet" highlight="7-9":::
:::code language="gradle" source="../demo/graphtutorial/build.gradle" id="DependenciesSnippet" highlight="7-8":::

1. Add the following to the end of **./build.gradle**.

Expand Down
Loading

Back | FazBrowse Home | New Git URL